Docsity

Branching and Boolean Expressions: if, else, switch statements in Java, Slides of Java Programming

Partial preview of the text

Download Branching and Boolean Expressions: if, else, switch statements in Java and more Slides Java Programming in PDF only on Docsity!

Branching

Announcements

Hand in HW1 before class (now) HW2 posted, due in 2 weeks.

boolean

boolean - either true or false In the book's infinite wisdom, boolean expressions are in Ch 3. We will use the following today:

(greater than), e.g. 7 > 2.5 is true == (equals), e.g. 5 == 4 is false < (less than), e.g. 8 < 1 is false

if statement

Code inside an if statement is only run if the condition is true. Need parenthesis (no semi-colon) Indent

if/else statement

Immediately after an if statement, you can make an else statement If the “if statement” does not run, then the else statement will (See: IfElse.java)

Nested if statements

You can have as many if statements inside each other as you want.

Switch

A switch statement checks to see if a variable has a specific value. Controlling Variable Case label Break statement

Switch

If the value of the controlling variable is found in a case label, all code until a break statement is ran (or the switch ends) Switch statements only test equality with case labels (not greater or less than) (See: Switch.java)

Conditional operator

We will not use in this class, but if you use other people's code you will encounter Example: max = (x>y)? x : y; Shorthand for an if-else statement (boolean)? [if true] : [if false]