90 likes | 178 Views
Review. In the last lesson we discussed about: Objects and Instances Declaring Variables The “=“ used as an assignment operator We also looked at the ACM hierarchy. Casting and Precedence.
E N D
Review • In the last lesson we discussed about: • Objects and Instances • Declaring Variables • The “=“ used as an assignment operator • We also looked at the ACM hierarchy
Casting and Precedence • When performing arithmetic operations in Java we have to understand how precedence (priority) works. • First priority is given to parenthesis () • Second *, /, % • Least +,- • Starting from left to right
For example: • X = 1 + 3 * 5 / 2; • Lets see how this will evaluate. • 3 * 5 = 15 • 15 / 2 = 7 (Integer division) • Add 1 • X=8
Divide integers but get real • int x = 5; (Integer division) • double y = x / 2; • Evaluates the right side first and then returns the answer to the left side • In order to get a double value we will use a process called CAST!
CAST is just like in a film! • Just like a film has a cast of characters who act temporarily to fulfill a role similarly in Java a cast is a conversion of one data type to another. For e.g.: int x=5; double y = (double) x/2 (x remains as an integer) y now contains 2.5 due to the casting on the right side of the equal sign
Calculate Average • import acm.program.*; • public class CalculateAverage extends ConsoleProgram { public void run() { println(“This program requires two numbers:”); int n1 = readInt(“Enter n1”); int n2 = readInt(“Enter n2”); double avg = n1 + n2 / 2; //BUGGY! println(“The average is:” + avg + “.”); } • } // Whats the problem here?
Short hands • Seems like x = x +1 is very commonly used in programming languages • There are short hands for doing this: • x+=1; • x++; • x-=1; • x--; • x*=2; • x/=2;
Constants • Lets have a look at an example of area of a circle. • double PI =3.14; • double A = PI * r * r; • PI is a variable and it can be changed which means the whole equation will change. • Defining: • private static final double PI=3.14; • You could come up with a constant called SEVENTY_TWO=72
Downloading ACM • Before beginning to use ACM (Association of Computer Machinery) library you need to download it from: • http://www-cs-faculty.stanford.edu/~eroberts/jtf/acm.jar