©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean Relational and Logical Operators
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Flow of Control Sequential: statements are executed in order they appear in the program. Method call causes jump from one code segment to an other and back. Control structures allow us much more flexibility. –Selection - choosing which code segments get executed –Repetition - executing a code segment multiple times For both types of control structures, we need expressions which can be either true or false
Why do we need selection? In MakeChange –What if the amount tendered is less than the amount due? –What of you only want to print out the coins for which the number to give is not 0? In Student –What if we want to keep track of the number of credits actually earned?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Control Flow JOptionPane. showMessageDialog (null, "You did pass"); JOptionPane. showMessageDialog (null, "You did pass"); false testScore < 70 ? JOptionPane. showMessageDialog (null, "You did not pass"); JOptionPane. showMessageDialog (null, "You did not pass"); true
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Boolean Expressions A boolean expression is either true or false –true and false are reserved words boolean primitive type has allowed values true or false boolean pass, done; done = true; Operators for boolean expressions –relational operators compare variables to give a boolean result –logical operators have boolean operands Methods can return a boolean value (predicate methods)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter testScore < 80 testScore * 2 >= < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= Relational Operators <//less than <=//less than or equal to ==//equal to !=//not equal to >//greater than >=//greater than or equal to
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Statements If statements –Two-way branch –Decision based on boolean expression Switch statement –Multi-way branch –Select between discrete set of values
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter if ( testScore < 70 ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Syntax for the if Statement if ( ) else Then Block Else Block Boolean Expression
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Blocks By default, the body of an if statement is a single statement. What if we want to do more than one thing? –A block is a sequence of statements enclosed in curly braces {…} –A block can contain any number of statements (including 0) –A block can contain other blocks –The body of a method is a block
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter if Without else testScore >= 95? false JOptionPane. showMessageDialog (null, "You are an honor student"); JOptionPane. showMessageDialog (null, "You are an honor student"); true
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The if-then Statement if ( ) if ( testScore >= 95 ) JOptionPane.showMessageDialog(null, "You are an honor student"); Then Block Boolean Expression
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter if ( ) { … } else { … } Style Guide if ( ) { … } else { … } Style 1 Style 2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Logical (Boolean) Operators Java has three logical operators –! is logical NOT (one operand) –&& is logical AND (two operands) –|| is logical OR (two operands) falsetrue falsetruefalse true falsetruefalse truefalse !PP || QP && QQP
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Short-Circuit Evaluation Consider the following boolean expression: x > y || x > z The expression is evaluated left to right. –If x > y is true, the expression will be true independent of value of x > z short-circuit evaluation.allows the evaluation once the result determined Why is it useful? –Consider what happens to the following if z=0 z == 0 || x / z > 20
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter De Morgan's Law De Morgan's Law allows us to rewrite boolean expressions in different ways Rule 1: !(P && Q) !P || !Q Rule 2: !(P || Q) !P && !Q !(temp >= 65 && dist < 2) !(temp >=65) || !(dist < 2) by Rule 1 (temp = 2)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Nested if statements Both the then part and the else part of an if statement can contain any other statement or group of statements If the then or else part of an if statement contains another another if statement, we have a nested if statement. if (condition1) if (condition_t1) statement_tt1; else statement_tf1; else if (condition_f1) statement_ft1; else statement_ff1;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Control Flow of Nested-if Statement messageBox.show ("You did not pass"); messageBox.show ("You did not pass"); false inner if messageBox.show ("You did pass"); messageBox.show ("You did pass"); false testScore >= 70 ? true studentAge < 10 ? messageBox.show ("You did a great job"); messageBox.show ("You did a great job"); true
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter if – else chains if (score >= 90) System.out.print("Your grade is A"); else if (score >= 80) System.out.print("Your grade is B"); else if (score >= 70) System.out.print("Your grade is C"); else if (score >= 60) System.out.print("Your grade is D"); else System.out.print("Your grade is F"); F score 60 D 60 score 70 C 70 score 80 B 80 score 90 A 90 score GradeTest Score A special case of nested if statements
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Dangling else Consider the following code if (test1) if (test2) statement1; else statement2; Under what conditions does statement2 get executed? – test1 is false? – test1 is true and test2 is false? The rule is –An else belongs to the nearest if So, case 2 is the correct one The compiler does not pay attention to indentation
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Comparing variables and >= can only be used to compare numeric values == and != can be used to compare variables of any type –These operators compare the memory content of the variables What if we compare two object variables using ==? –what is compared is the address stored in the variables – the comparison will return true only if the two variables refer to the same object –What if we need to compare the data inside the two objects? The class needs to define the equals method
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The Semantics of == for objects
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Literal String Objects
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter equals method The Object class (and by inheritance, every other class) has a method boolean equals ( Object obj) By default, this method has the same behavior as == The author of a class can override the equals method to compare object data instead of object references The String class has a version of equals that returns true if two Strings contain the same sequence of characters
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Comparing floating point values All relational operators can be used with floating point expressions Comparing two floating point variables for equality is not a good idea because of round-off error –Very few floating point numbers can be stored exactly in the number of bits available in memory to store a variable –round-off error is the part of the number that needs more significant digits that are available –For example, 0.1 is a repeating fraction in binary: … Only the first 23 bits can be stored in a float; the rest are truncated
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selecting between a discrete set of values Java has a second selection statement which is useful when your choices are a set of distinct values (integers or characters). –For example, the coins we use have only a few possible values - 1, 5, 10, 25, 50, 100 –The grades you get for the classes you take can only be A, B, C, D, F You still need to use if-else chains for decisions that involve ranges of numbers.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Syntax for the switch Statement switch ( gradeLevel ) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); break; case 3: System.out.print("Go to Harris Hall Rm A3"); break; case 4: System.out.print("Go to Bolt Hall Rm 101"); break; } switch ( ) { case : … case : default : } Case Body Arithmetic Expression Case Label
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter switch With break Statements switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true break;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter switch With No break Statements switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true