Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY Arithmetic Operators There are four basic arithmetic operations: OPERATOR USE DESCRIPTION + op1 + op2 Adds op1 and op2 - op1 + op2 Subtracts op2 from op1 * op1 + op2 Multiplies op1 and op2 / op1 + op2 Divides op1 by op2 The operands of the arithmetic operators must be of a numeric type The order of operations is the same as it is in algebra (BEDMAS!): o Parenthesis () o Multiplication/division o Addition/subtraction All terms are evaluated left to right Remainder Operator The remainder (%) operator will produce the remainder of a division operation o (Equivalent to mod in Turing) o 7 / 2 = 3 2 goes into 7 evenly 3 times, with 1 left over (2*3 = 6) o 7 % 2 = 1 leftover from 7 / 2 is 1 Another example: o 7 / 4 = 1 o 7 % 4 = 3 Applying the remainder operator: o The remainder operator is useful in lots of situations where floating point is not appropriate, for example, some types of monetary and date calculations public class Change public static void main(string [] args) int pennies = 23; int nickels = 84; int dimes = 74; int piggybank, cents, dollars;
piggybank = pennies + nickels*5 + dimes*10; dollars = piggybank / 100; cents = piggybank % 100; System.out.println( Dollars = + dollars); System.out.println( Cents = + cents); Run this code. What is the output? Type Conversion Sometimes it is convenient (or necessary) to convert data from one data type to another. For example, arithmetic operations require both operates and the result to be of the same type (example: you have to add two ints and assign the result to an int for an expression to work) Conversions between data types must be handled carefully to avoid losing information Conversions fall into one of two categories: o Widening conversion (safest conversion): converting data from a smaller data type to a larger one (e.g. short int). Widening conversions move left to right on the following scale: Smallest data type... Largest data type byte short int long float double These are done automatically by the system. Example: float b = 7/4; System.out.println( B is: + b); In the above example, the numbers 7 and 4 are integers. Integer math is performed on these two operands. Then, the result is converted to a float automatically, and is assigned to the variable b. Type in and run this example. What is the value of b? What happens when we assign a value in this way? How do we avoid the above loss of information? int a = 5; int b = 10; float result; result = (float) a / b; // result is 0.5 First a will be converted to a float, then b will automatically be converted to a float as well so that float division will be used (both operands must be float). Then, the float result will be stored in result.
o Narrowing conversion (more risky conversion): can lose information because data is converted from a larger type to a smaller type (e.g. int short). Will cause compiler errors unless explicitly requested by the use of a cast. They move right to left on the above scale. Example 1: Example 2: int dollars; double money = 121.35; // cast is (int) in the next line dollars = (int) money; //will put 121 in dollars short x = (short) 32000; byte y = (byte) x / 1000; In this example, you are attempting to divide two numbers. Since both operands need to be the same type, Java will assume x and 1000 are both shorts, and the result will be a short as well. Since we need a result of type byte, we need to cast the result to a byte. We do this by placing the name of the desired type in parentheses after the assignment operator. The Math Class Java s Math class provides a variety of methods for performing advanced mathematical operations. All of the methods are static (which you will learn about later), and can be used directly. Typical methods (functions): double Math.sin(double) //returns sine of argument double Math.floor(double) //returns largest integer less than or equal to argument double Math.rint(double) //returns the nearest integer to the argument double Math.random() //returns a random number in the range of [0, 1) double Math.sqrt(double) //returns the square root of the number CONSTANTS double Math.PI //approximately 3.14 double Math.E //approximately 2.72
Random Number Generator The Math class has a method that generates a random number between 0.0 and 1.0 1. To generate a random number between 0.0 and 1.0: Math.random(); 2. To generate a random integer between 0 and n 1: (int) (Math.random() * n); 3. To generate a random integer between 1 and n: (int) (Math.random() * n ) + 1; public class RandomNumberDemo public static void main(string[] args) int n = 6; double x = Math.random(); int y = (int) (Math.random() * n); int z = (int) (Math.random() * n) + 1; What is the difference between x, y, and z? What range of values can x, y and z have? PRPGRAMMING PRACTISE 1. Try the following statements to learn more about how Java performs arithmetic operations. Try to predict what will happen (and if the code will work), then add System.out.print() statements after each of the following lines to output the variable s final value (if the code works!): int a = 7 / 4; int b = 7.0 / 4; float c = 7 / 4; float d = 7.0 / 4; float e = 7.0f/ 4; // appending an f after a real number tells Java it s a float value double f = 7.0 / 4.0; double g = 7.0f / 4.0; 2. Write a program that generates random numbers until it finds one that has a value greater than 0.75. Use a while loop, and a flag variable (sentinel) to exit your loop. 3. Write a program that calculates the radius of a circle in feet and inches. Hint: Use the square root method of the Math class. Feet and inches should be int variables, while radius and circlearea should be double type variables.
4. Write a program that converts an ugly-looking double value to a nice real number with 2 decimal digits. Hint: you will need to use the Math.rint method, and you will need to multiply by 100.0 and then divide by 100.0 to make this work. 5. Write a program to determine whether a year is a leap year or not. A year is a leap year if it is evenly divisible by 4 but not evenly divisible by 100 unless it is also evenly divisible by 400. For example: 1996 is a leap year evenly divisible by 4 but not evenly divisible by 100. 1990 is not a leap year evenly divisible by 4 and 100, but not divisible by 400. 2000 is a leap year evenly divisible by 4, 100, and 400. Hint: you will need the % operator, as well as several if-else statements. 6. Write a program that checks numbers from 1 to 100 to see if they are prime or not. Output all numbers that are prime. Hint: you will need the % operator and you will also find the break statement useful.