ObjectOriented Programming 95 712 MISMMSIT Carnegie Mellon University
Object-Oriented Programming 95 -712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control
Today We Look At Java operators n Control structures n More example programs n
Java Operators An operator takes one or more “things” and produces a resultant “thing”. n “Things” are usually primitive types, but they are sometimes objects. n The “things” operated upon are called operands. n An operator is just a function, but with a different syntax. n
A Familiar Example int i = 3, j = 4, k; k = i + j; The assignment operator and the addition operator are used (each exactly once!). n This is a more familiar syntax than, e. g. , n k. equals(i. add(j));
More Operator Facts All operators produce a value. n Sometimes they produce side effects, i. e. , they change the value of an operand. n Evaluation of a statement with several operators follows precedence rules. Use parentheses for readability. n (x + y) * z / 3 is different than x + y * z / 3 n
Assignment Is Tricky, Part I public class Number { int i; } public class Assignment 1 { public static void main(String[] args) { Number n 1 = new Number(); n 1. i = 2; n 2. i = 5; n 1. i = n 2. i; n 2. i = 10; // what is n 1. i? } }
Assignment Is Tricky, Part II public class Assignment 2 { public static void main(String[] args) { Number n 1 = new Number(); n 1. i = 2; n 2. i = 5; n 1 = n 2; n 2. i = 10; // what is n 1. i? n 1. i = 20; // what is n 2. i? } }
A Picture Might Help Before assignment n 1 = n 2 reference variables n 1 n 2 Number objects n 2. i 5 n 1. i 2 After assignment n 1 = n 2 Number objects reference variables n 1 n 2. i n 1. i 5 2
“Aliasing” In Function Calls public class Pass. Object { static void f(Number m) { m. i = 15; } public static void main(String[] args) { Number n = new Number(); f(n); // what is n. i now? } }
Math Operators n n +, -, *, /, % Integer division truncates, i. e. , 16/3 = 5 Modulus operator returns remainder on integer division, i. e. , 16%3 = 1 Shorthand: x += 4; is the same as x = x + 4; n This works for the other math operators as well.
Auto Increment and Decrement ++ increases by one, and -- decreases by one. n Two flavors of each: pre and post: n int i = 1, j; j = i++; j = ++i; j = i--; j = --i; // j = 1, i = 2 // j = 3, i = 3 // j = 3, i = 2 // j = 1, i = 1
Booleans and Relational Operators The boolean type has two possible values, true and false. n The relational operators >, >=, <, <=, == and != produce a boolean result. n >, >=, <, <= are legal for all built-in types except booleans, == and != are legal for all. n
Testing for (Non-)Equivalence n The == and != operators need to be used with care with objects. public class Equivalence { public static void main(String[] args) { Integer n 1 = new Integer(47); Integer n 2 = new Integer(47); System. out. println(n 1 == n 2); // prints false System. put. println(n 1 != n 2); // prints true } }
The equals( ) Operator n This exists for all objects (don’t need it for built-in types). Integer n 1 = new Integer(47); Integer n 2 = new Integer(47); System. out. println(n 1. equals(n 2); // prints true
The equals( ) Operator (cont. ) n But exists doesn’t necessarily mean properly defined! class Number { int i; } : Number n 1 = new Number(); Number n 2 = new Number(); n 1. i = 3; n 2. i = 3; System. out. println(n 1. equals(n 2)); // prints false
The equals( ) Operator (cont. ) The equals( ) operator is properly defined for most Java library classes. n The default behavior is to compare references, so… n When you define a class, if you’re planning to use equals( ), you need to define it (i. e. , override the default behavior). n
Logical Operators These are AND (&&), OR (||), and NOT (!). n These work on booleans only; if you have old “C” habits, forget them! n Use parentheses freely to group logical expressions. n Logical expressions short-circuit; as soon as the result is known, evaluation stops. n
Short-Circuiting Example public class Short. Circuit { static boolean test 1(int val) {return val < 1; } static boolean test 2(int val) {return val < 2; } static boolean test 3(int val) {return val < 3; } public static void main(String[] args) { if (test 1(0) && test 2(2) && test 3(2)) System. out. println(“Expression is true”); else System. out. println(“Expression is false”); } }
Bitwise, Shift, Ternary Operators Bitwise & shift operators manipulate individual bits in integral primitive types. n I almost never use them, except for masks, when memory is tight. YMMV n The ternary if-else operator looks like this: n boolean-expression ? value 0 : value 1 n The result is either value 0 or value 1, depending on the truth of the boolean.
The String + Operator The + operator is “overloaded” for String objects; it means concatenation. n It reminds me of good old C++… n If an expression begins with a String, then all the following operands of + will be converted into Strings: n int x = 0, y = 1; z = 2; String my. String = “x, y, z ”; System. out. println(my. String + x + y + z);
Casting A cast produces a temporary new value of a designated type. n Implicit and explicit casts: n int i = 2; float f = i; // OK, since f can hold all of i float g = 3. 14159; //! int j = g; // not OK, loses information int k = (int) g; // OK, compiler is reassured
Execution Control: if-else if (boolean_expression) statement else if(boolean_expression) statement : else if(boolean_expression) statement else statement
if-else Example public int test(int test. Val, int target) { int result = 0; if (test. Val > target) result = +1; else if (test. Val < target) result = -1; else { System. out. println(“They are equal”); result = 0; } return result; }
Execution Control: return n Exit a method, returning an actual value or object, or not (if the return type is void). public int test(int test. Val, int target) { if (test. Val > target) return = +1; else if (test. Val < target) return = -1; else { System. out. println(“They are equal”); result = 0; } }
Three Kinds of Iteration while (boolean_expression) // evaluate first statement_or_block do statement_or_block while (boolean_expression) // evaluate last for (initialization ; boolean_expression ; step) statement_or_block Example: for (int i = 0; i < my. Array. size(); i++) { my. Array[i] = 0; }
public class Break. And. Continue { public static void main(String[] args) { for (int i = 0; i < 100; i++) { if (i == 74) break; // out of for loop if (i % 9 != 0) continue; // next iteration System. out. println(i); } int i = 0; // this does work while (true) { // an infinite loop i++; int j = i * 27; if (j == 1269) break; // out of loop if (i % 10 != 0) continue; // top of loop } }
Selection Via switch for (int i = 0; i < 100; i++) { char c = (char) (Math. random() * 26 + ‘a’); switch(c) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: System. out. println(“Vowel”); break; case ‘y’: case ‘w’: System. out. println(“Sometimes a vowel”); break; default: System. out. println(“Not a vowel”); }
Digression on Random Numbers n Despite theory, most random number generators are more like “kids playing with matches”. – See “Random Number Generators: Good Ones Are Hard to Find” by S. Park and K. Miller, CACM Oct. 1988. n Most random number generators use “multiplicative linear congruential” schemes: – A modulus m, a large prime integer – A multiplier a, an integer in the range 2, 3, …m-1 – These produce a sequence z 1, z 2, z 3… using the iterative equation – zi+1 = f(zi) = a*z % m
Random Numbers (cont. ) n n n The sequence is initiated by choosing a seed. Example: f(z) = 6 z %13. This produces the sequence. . . 1 , 6, 10, 8, 9, 2, 12, 7, 3, 5, 4, 11, 1, . . . Example: f(z) = 7 z % 13. This produces the sequence. . . 1 , 7, 10, 5, 9, 11, 12, 6, 3, 8, 4, 2, 1, . . . Is the latter somehow "less random"? Example: f(z) = 5 z %13. This produces the sequence. . . 1 , 5, 12, 8, 1. . .
Examples of Rotten RNGs n IBM's RANDU for SYSTEM/360: – f(z) = 65539 z % 231. Not full period, dependent on results of overflow operations, low-order bits cycle w/ period 2! n n n n Prime’s Scheffield Pascal, an even worse version SAS Modula 2 Many LISPs and Prologs Hundreds of CS textbooks Turbo Pascal One generator had a fixed point!
Using Java’s RNGs (cont. ) n java. lang. Math – static double random() random in [0, 1. 0) The sequence doesn’t seem to be repeatable n Bad for debugging n Good for experimental work n
What’s a Seed? Here is a sequence I generated on Friday at 9: 30, with the code: Random random. Generator = new Random(); for (int i = 0; i < 10; i++) System. out. println(random. Generator. next. Int()); -1321140701 i=0 1591074477 i=1 646222811 i=2 Random number i = 3 1633627825 sequence -2039264851 i=4 i=5 -315534709
What’s a Seed? I ran the same code again at 10: 30, and got this: -403585738 i=0 -2092042741 i=1 -333693675 i=2 Random number i = 3 -331823022 sequence 1651689643 i=4 i=5 133526058
What’s a Seed? I ran this code at 10: 35 Random random. Generator = new Random(1234); for (int i = 0; i < 10; i++) System. out. println(random. Generator. next. Int()); -1517918040 i=0 1115789266 i=1 -208917030 i=2 Random number i = 3 1019800440 sequence -6116528751 i=4 i=5 1362132786
What’s a Seed? I ran this code at 10: 45 and got the same sequence. Random random. Generator = new Random(1234); for (int i = 0; i < 10; i++) System. out. println(random. Generator. next. Int()); -1517918040 i=0 1115789266 i=1 -208917030 i=2 Random number i = 3 1019800440 sequence -6116528751 i=4 i=5 1362132786
Using Java’s RNGs (cont. ) n java. util. Random – Constructors: » Random() » Random(long seed) – Methods: » » n next. Int() next. Int(int n) next. Float() set. Seed(long seed) random in (-231, 231 -1) random in [0, n) random in [0, 1) java. lang. Math – static double random() random in [0, 1. 0)
Random Numbers In Action: The Monte Hall Paradox Monte Hall hosts a TV game show, “Let’s Make a Deal”. n One contestant is shown three doors. n Behind one of the doors is a “Fabulous Grand Prize”. n Behind the other two doors are “worthless prizes”. n
The Monte Hall Paradox The contestant selects a door. n Monte opens a door not selected by the contestant, and this always shows a worthless prize. n The contestant can choose to change her selection to the other door not opened by Monte Hall. n Should the contestant change doors? n
The Monte Hall Paradox n Very intelligent people are confused! – Any initial door choice has a 1/3 chance of winning. – Why would changing the door choice increase or decrease the odds of winning the “Fabulous Grand Prize”? – Can’t we settle this with a computer simulation?
The Door Class public class Door { boolean open; boolean has. Grand. Prize; boolean chosen. By. Contestant; }
The Game Class import java. util. *; public class Game { Door door 1, door 2, door 3; void set. Up. Game() { door 1 = new Door(); door 2 = new Door(); door 3 = new Door(); // initialize all the Door variables to false Random r = new Random(); int grand. Prize. Door = r. next. Int(3); switch(grand. Prize. Door) { case 0: door 1. has. Grand. Prize = true; break; case 1: // etc. } }
Reality Check For Game Class void print. State. Of. Doors() { System. out. println("Door 1 is " + (door 1. open ? " open, " : "not open, ") + (door 1. has. Grand. Prize ? "is the grand prize, and " : "is no (door 1. chosen. By. Contestant ? "is chosen. " : "is not chosen System. out. println("Door 2 is " + (door 2. open ? " open, " : "not open, ") + (door 2. has. Grand. Prize ? "is the grand prize, and " : "is no (door 2. chosen. By. Contestant ? "is chosen. " : "is not chosen System. out. println("Door 3 is " + (door 3. open ? " open, " : "not open, ") + (door 3. has. Grand. Prize ? "is the grand prize, and " : "is no (door 3. chosen. By. Contestant ? "is chosen. " : "is not chosen }
The Game Class public class Game { Door door 1, door 2, door 3; void set. Up. Game() { // shown earlier} void contestant. Choose. Door() { Random r = new Random(); int contestant. Door = r. next. Int(3); switch(contestant. Door) { case 0: door 1. chosen. By. Contestant = true; break; case 1: door 2. chosen. By. Contestant = true; break; case 2: door 3. chosen. By. Contestant = true; break; } } }
The Play. Many. Games Class public class Play. Many. Games { public static void main(String[] args) { Game the. Game = new Game(); the. Game. set. Up. Game(); the. Game. print. State. Of. Doors(); the. Game. contestant. Choose. Door(); the. Game. print. State. Of. Doors(); } }
A Problem: First Run Door 1 is not open, is not the grand prize, and is not chosen. Door 2 is not open, is not the grand prize, and is not chosen. Door 3 is not open, is the grand prize, and is not chosen. Door 1 is not open, is not the grand prize, and is not chosen. Door 2 is not open, is not the grand prize, and is not chosen. Door 3 is not open, is the grand prize, and is chosen.
A Problem: Second Run Door 1 is not open, is not the grand prize, and is not chosen. Door 2 is not open, is the grand prize, and is not chosen. Door 3 is not open, is not the grand prize, and is not chosen. Door 1 is not open, is not the grand prize, and is not chosen. Door 2 is not open, is the grand prize, and is chosen. Door 3 is not open, is not the grand prize, and is not chosen.
A Problem: Third Run Door 1 is not open, is the grand prize, and is not chosen. Door 2 is not open, is not the grand prize, and is not chosen. Door 3 is not open, is not the grand prize, and is not chosen. Door 1 is not open, is the grand prize, and is chosen. Door 2 is not open, is not the grand prize, and is not chosen. Door 3 is not open, is not the grand prize, and is not chosen.
The Solution The RNGs in both methods of the Game class are starting from the same seed. n Solution: Take the RNG out of the methods, and into the Game class itself. n But each instance of the Game class will start at the same place. n Solution: Make the RNG a static variable. n
The New Game Class public class Game { Door door 1, door 2, door 3; static Random r = new Random(); void set. Up. Game() { int grand. Prize. Door = r. next. Int(3); switch(grand. Prize. Door) { // etc. } void contestant. Choose. Door() { int contestant. Door = r. next. Int(3); switch(contestant. Door) { // etc. } }
Completing the Simulation n Add Game methods for – Monte choosing a door to open – The player switching or not – Deciding if the player has won n Add Play. Many. Games code to – Call the new Game methods – Put everything in a loop – Prompt the user for # of trials, switching policy – Display the results
- Slides: 50