850 likes | 865 Views
Learn about if statements, logical operators, comparing objects, flowcharts, and how to declare variables in Java. Understand the conditional operator, switch statements, and formatted output. Improve your programming with Java conditionals.
E N D
Chapter Topics Chapter 3 discusses the following main topics: The if Statement The if-else Statement Nested if statements The if-else-if Statement Logical Operators Comparing String Objects
Chapter Topics Chapter 3 discusses the following main topics: More about Variable Declaration and Scope The Conditional Operator The switch Statement Displaying Formatted Output with System.out.printf and String.format
The if Statement The if statement decides whether a section of code executes or not. The if statement uses a boolean to decide whether the next statement or block of statements executes. if (boolean expression is true) execute next statement.
Flowcharts If statements can be modeled as a flow chart. Yes Is it cold outside? Wear a coat. boolean coldOutside = true; … if (coldOutside) wearCoat(); int xyz, abc; … if (xyz == abc) {incXYZ(); xyz++;} abc = xyz;
Flowcharts A block if statement may be modeled as: Yes Is it cold outside? Wear a coat. Wear a hat. Wear gloves. boolean coldOutside = false; if (coldOutside){ wearCoat(); wearHat(); wearGloves(); } Note the use of curly braces to block several statements together.
Relational Operators In most cases, the boolean expression, used by the if statement, uses relational operators.
Boolean Expressions A boolean expressionis any variable or calculation that results in a true or falsecondition.
if Statements and Boolean Expressions if (x > y) System.out.println("X is greater than Y" + boolean(x > y)); if(x == y) System.out.println("X is equal to Y"); if(x != y) { System.out.println("X is not equal to Y"); x = y; System.out.println("However, now it is."); } Example: AverageScore.java
package booleanStudy; publicclass BooleanExpr { publicstaticvoid main(String[] args) { booleanrainingDay = false; intx = 100, y = 50; x = 20; y = 40; if (x > y) {System.out.println("rainingDay is " + rainingDay); System.out.println("x > y? is " + (boolean)(x>y));} elseif (x == y) { System.out.println("x > y? is " + (boolean)(x>y)); System.out.println("x = y? is " + (boolean)(x == y));} else { System.out.println("x > y? is " + (boolean)(x > y)); System.out.println("x = y? is " + (boolean)(x == y)); System.out.println("x < y? is " + (boolean)(x < y));} System.out.println("End of if ese if else!"); } } Do not need the (boolean) to cast (x > y) etc. Simply use (x > y) will yield true or false. Output: x > y? is false x = y? is false x < y? is true End of if ese if else!
Programming Style and if Statements An if statement can span more than one line; however, it is still one statement. if (average > 95) grade = ′A′; is functionally equivalent to if(average > 95) grade = ′A′;
Programming Style and if Statements Rules of thumb: The conditionally executed statement should be on the line after the if condition. The conditionally executed statement should be indented one level from the if condition. If an if statement does not have the block curly braces, it is ended by the first semicolon encountered after the if condition. if (expression) statement; No semicolon here.Semicolon ends statement here.
Block if Statements Conditionally executed statements can be grouped into a block by using curly braces {} to enclose them. If curly braces are used to group conditionally executed statements, the if statement is ended by the closing curly brace. if (expression) { statement1; statement2; } Curly brace ends the statement.
Block if Statements Remember that when the curly braces are not used, then only the next statement after the if condition will be executed conditionally. if (expression) statement1; statement2; statement3; Only this statement is conditionally executed.
Flags A flag is a boolean variable that monitors some condition in a program. booleanhighScore; When a condition is true, the flag is set to true. The flag can be tested to see if the condition has changed. if (average > 95) highScore = true; Later, this condition can be tested: if (highScore) System.out.println("That′s a high" + "score!");
Comparing Characters Characters can be tested with relational operators. Characters are stored in memory using the Unicode character format. Unicode is stored as a sixteen (16) bit number. Characters are ordinal, meaning they have an order in the Unicode character set. Since characters are ordinal, they can be compared to each other. char c = ′A′; if(c < ′Z′) System.out.println("A is less than Z");
charc = 'A'; if(c < 'Z') System.out.println("A is less than Z is " + (boolean)(c < 'Z’)); System.out.println("A is less than Z is " + (c < 'Z')); Output is: A is less than Z is true A is less than Z is true
if-else Statements The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementOrBlockIfTrue; else statementOrBlockIfFalse; See example: Division.java
if-else Statement Flowcharts Yes Is it cold outside? Wear shorts. Wear a coat. No if (Is it cold outside) wear_short; else wear_a_coat;
Nested if Statements If an if statement appears inside another if statement (single or block) it is called a nested if statement. The nested if is executed only if the outer if statement results in a true condition. See example: LoanQualifier.java
Nested if Statement Flowcharts No Yes Is it cold outside? Wear shorts. Is it snowing? Yes No Wear a jacket. Wear a parka.
Nested if Statements Is it cold outside? No Yes Wear shorts. Is it snowing? Yes No Wear a jacket. Wear a parka. boolean coldOutside, snowing; coldOutside = true; snowing = false; if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); }
if-else Matching Curly brace use is not required if there is only one statement to be conditionally executed. However, sometimes curly braces can help make the program more readable. Additionally, proper indentation makes it much easier to match up else statements with their corresponding if statement.
Alignment and Nested if Statements if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); } This ifand else go together. This ifand else go together.
Alignment and Nested if Statements if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); } This ifand else go together. This ifand else go together.
if-else-if Statements if (expression_1) { statement; statement; etc. } else if (expression_2) { statement; statement; etc. } Insert as many else if clauses as necessary else { statement; statement; etc. } If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. These statements are executed if none of the expressions above are true.
if-else-if Statements • if (expression_1) • { • statement; • statement; • etc. • } • else • if (expression_2) • { • statement; • statement; • etc. • } • Insert as many else if clauses as necessary • else • { • statement; • statement; • etc. • } If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. These statements are executed if none of the expressions above are true.
if-else-if Statements Nested if statements can become very complex. The if-else-if statement makes certain types of nested decision logic simpler to write. Care must be used since else statements match up with the immediately preceding unmatched if statement. See example: TestResults.java
package chapter03; • importjava.util.Scanner; • publicclass Chapter03Example { • publicstaticvoid main(String[] args) { • intscore; • chargrade; • Scanner kbInput = new Scanner(System.in); • System.out.println("Enter a score, integer only, such as 60: "); • score = kbInput.nextInt(); • if (score < 60) • { grade = 'F'; • System.out.println("Grade is " + grade); • } • elseif (score < 70) • { grade = 'd'; • System.out.println("Grade is " + grade); • } • elseif (score < 80) • { • grade = 'C'; • System.out.println("Grade is " + grade); • } • elseif (score < 90) • { • grade = 'B'; • System.out.println("Grade is " + grade); • } • elseif (score <= 100) • { • grade = 'B'; • System.out.println("Grade is " + grade); • } • else • { • grade = 'X'; • System.out.println("Grade is " + grade); • } • } • }
Logical Operators Java provides two binary logical operators(&& and ||) that are used to combine boolean expressions. e.g. int x= 70, y = 60, z = 70; if (((x > y) || (y > x)) && (y = = z)) System.out.printf(“you %s”, “Good!”); Java also provides one unary (!) logical operator to reverse the truth of a boolean expression. if (((x > y) || (y > x)) && !(y = = z)) System.out.printf(“you %s”, “Good!”);
The && Operator The logical AND operator (&&) takes two operands that must both be boolean expressions. The resulting combined expression is true if (and only if) both operands are true. See example: LogicalAnd.java
The || Operator The logical OR operator (||) takes two operands that must both be boolean expressions. The resulting combined expression is false if (and only if) both operands are false. Example: LogicalOr.java
The ! Operator The ! operator performs a logical NOT operation. If an expression is true, !expression will be false. if (!(temperature > 100)) System.out.println("Below the maximum" + " temperature."); If temperature > 100 evaluates to false, then the output statement will be run.
Short Circuiting Logical AND and logical OR operations perform short-circuit evaluationof expressions. Logical AND will evaluate to false as soon as it sees that one of its operands is a false expression. Logical OR will evaluate to true as soon as it sees that one of its operands is a true expression.
Order of Precedence The ! operator has a higher order of precedence than the && and || operators. The && and || operators have a lower precedence than relational operators like < and >. Parenthesis can be used to force the precedence to be changed.
Comparing String Objects In most cases, you cannot use the relational operators to compare two String objects. Reference variables contain the address of the object they represent. Unless the references point to the same object, the relational operators will not return true. See example: StringCompare.java See example: StringCompareTo.java
Summary of the following next few slides: String one = "projects!"; String two = "projectiles!"; System.out.println(one.compareTo(two)); //10 = code(s) – code(i) System.out.println(two.compareTo(one)); //-10 = code(i) – code(s) String one = "project"; String two = "projectiles!"; System.out.println(one.compareTo(two)); //-5 – the string project Has 5 characters less than projectiles! System.out.println(two.compareTo(one)); //5 – the string projectiles! Has 5 characters more than project! String one = "project "; String two = "projectiles!"; System.out.println(one.compareTo(two)); //-73 = code(space) – code(i) System.out.println(two.compareTo(one)); //73 = code(i) – code(space)
String one = "projects!"; String two = "projectiles!"; System.out.println("The codes for s and i: " + 's' + " is " + (int)('s') + " and " + 'i' + " is " + (int)('i')); System.out.printf("The codes for %c and %c are %d and % d.", 's', 'i', (int)('s'), (int)('i')); System.out.println("\n" + one.compareTo(two)); //10 = code(s) – code(i) = 115 - 105 System.out.println(two.compareTo(one)); //-10 = code(i) – code(s) = 105 - 115 Output is: The codes for s and i: s is 115 and i is 105 The codes for s and i are 115 and 105. 10 -10
String one = "project"; String two = "projectiles!"; System.out.printf("Given two strings one has \"%s\" and two has \"%s\",\n" + "the operation of one.compareTo(two) " + "has the value : %d\n", "project", "projectiles!", one.compareTo(two)); System.out.println(one.compareTo(two) + " = " + one.length() + " - " + two.length()); //-5 – the string project Has 5 characters less than projectiles! System.out.println("The two.compareTo(one) is " + two.compareTo(one)); //5 – the string projectiles! Has 5 characters more than project! Output is : Given two strings one has "project" and two has "projectiles!", the operation of one.compareTo(two) has the value : -5 -5 = 7 - 12 The two.compareTo(one) is 5
String one = "project "; String two = "projectiles!"; System.out.println("The codes for space and i: " + ' ' + " is " + (int)(' ') + " and " + 'i' + " is " + (int)('i')); System.out.printf("The codes for %c and %c are %d and %d.", ' ', 'i', (int)(' '), (int)('i')); System.out.println("\nThe one.compareTo(two) operation yields " + one.compareTo(two)); //-73 = code(space) – code(i) System.out.println("The two.compareTo(one) operation yields " + two.compareTo(one)); //73 = code(i) – code(space) Output is: The codes for space and i: is 32 and i is 105 The codes for and i are 32 and 105. The one.compareTo(two) operation yields -73 The two.compareTo(one) operation yields 73
String oneStr = new String("tam"); String twoStr = new String("tam"); System.out.println(oneStr == twoStr); //false since they contain addresses booleanequalStrings = oneStr == twoStr; System.out.println(equalStrings); //false, since they contain addresses equalStrings = oneStr.equals(twoStr); System.out.println(equalStrings); //true, method equals on strings ("tam"); System.out.println(oneStr.equals(twoStr)); Conclusion: Each reference variable oneStr or twoStr reference their string objects which have the same string literal “tam”. Output is: false false true
The Difference of the following statements: String str = new String(“1amb”); and String str = “lamb”; String oneStr = new String("tam"); String twoStr = new String("tam"); String oneStr1 = "tam"; String twoStr1 = "tam";
String oneStr = new String("tam"); String twoStr = new String("tam"); System.out.println(oneStr == twoStr); //false since they contain addresses booleanequalStrings = oneStr == twoStr; System.out.println(equalStrings); //false, since they contain addresses equalStrings = oneStr.equals(twoStr); System.out.println(equalStrings); //true, method equals on strings ("tam"); System.out.println(oneStr.equals(twoStr));//true Output is: false false true true Conclusion: Each reference variable oneStr or twoStr reference their string objects which have the same string literal “tam”.
String oneStr1 = "tam"; String twoStr1 = "tam"; System.out.println(oneStr1 == twoStr1); //true booleanequalStrings1 = oneStr1 == twoStr1; System.out.println(equalStrings1); //true equalStrings = oneStr1.equals(twoStr1); System.out.println(equalStrings1); //true System.out.println(oneStr1.equals(twoStr1)); //true Conclusion: Both reference variables, oneStr1 and twoStr1 references the same string object "tam ". true true True True
Ignoring Case in String Comparisons In the String class the equals and compareTomethods are case sensitive. In order to compare two String objects that might have different case, use: equalsIgnoreCase, or compareToIgnoreCase See example: SecretWord.java
System.out.println("The compareTo results " + "dope".compareTo("dome")); System.out.println("The compareTo results " + "doPe".compareTo("dome")); System.out.println("The compareToIgnoreCase results " + "DOPE".compareToIgnoreCase("dome")); The compareTo results 3 //obtained from code(p) – code(m) The compareTo results -29//code(P) = 80 – code(m) = 109 The compareToIgnoreCase results 3 //obtained from code(P) – code(M) or code(p) – code(m).
Variable Scope In Java, a local variable does not have to be declared at the beginning of the method. The scope of a local variable begins at the point it is declared and terminates at the end of the method. When a program enters a section of code where a variable has scope, that variable has come into scope, which meansthe variable is visible to the program. See example: VariableScope.java