80 likes | 90 Views
Learn about relational and boolean operators in Java, including how to use them to make decisions in your code. Understand if, if-else, multiple alternatives, and switch statements with examples and explanations.
E N D
Decisions: Relational Operators • Operators(result in a boolean value) • <, <=, ==, !=, >=, > • Used only for primitive types! • (== and != can be used to compare objects) • Examples (assume all variables are primitive types) x > 0 y != z k <= limit • All outcome either true or false. • For objects, can check whether two references are to the same object or not (assume variables are Chicken objects) currentChicken == chickTwo
Decisions: Boolean Operators • Defining AND,OR, andNOT with Truth Tables AND OR NOT
Decisions: Boolean Operators • Operate on boolean; result in boolean • !, &&, || (NOT, AND, OR) • Examples • Checking if number is in range (inclusive) lowerLimit <= n && n <= upperLimit • Do not use: lowerLimt <= n <= upperLimit • Why doesn’t it work? • Can this person vote (assume isCitizen and isFelon are boolean variablese)? age >= 18 && isCitizen && !isFelon • Short Circuit (lazy) Evaluation isStudent || hasPaid || age < 12 • What about prescedence rules?
Decisions: if Statement • Syntax • if (boolean_exp) { what_to_do_if_true } • Examples • if (age >= 18 && isCitizen && !isFelon){ campaignAd.mailTo(); } • if (one.getWeight() < 5.0) { message = ”too small to cook”; }
Decisions: if else Statement • Syntax • if (boolean_exp) { what_to_do_if_true } else { what_to_do_if_false } • Example • if (one.getWeight() < 5.0) { message = ”too small to cook”; } else { one.feed(); one.feed(); one.feed(); }
Decisions: Multiple Alternatives • Syntax (really just nestedifelses with different indentation) • if (1st_boolean_exp) { what_to_do_if_1st_true } elseif (2nd_boolean_exp){ what_to_do_if_2nd_true } . . . else { what_to_do_if_all_false } • Example • if (speed == 0.0) color = ”red”; else if (speed < 25.0) color = ”yellow”; else color = ”green”;
Decisions: switch Statement • Syntax • switch (int_type_exp) { case CONST1: action_for_CONST1; break; case CONST1: action_for_CONST1; break; case CONST2: action_for_CONST2; break; case CONST3: action_for_CONST3; break; . . . default: action_for_no_match; break; }
Decisions: switch Statement • Example • switch (stars) { case 4: message = ”truly exceptional”; break; case 3: message = ”quite good”; break; case 2: message = ”fair”; break; case 1: case 0: message = ”forget it”; break; default: message = ”no info found”; break; }