Title: Conditionals and Loops: Review
1Conditionals and Loops Review
if, if/else, if/else if Loops while, do-while,
for
2Boolean Expression
- Boolean expression
- evaluates to true or false
- has equality, relational or logical operators
- , ! equality operators
- lt, gt, lt, gt relational operators
3Boolean Expression
- Logical Operators take boolean operands
- ! Logical NOT (unary)
- Logical AND (binary)
- Logical OR (binary)
4Boolean Expression
Logical NOT if a is true, !a evaluates to
false Logical AND a b evaluates to true
if both a and b are true Logical OR a b
evaluates to true if a or b is true Short
Circuited operators - logical AND, logical OR
5Boolean Expression (examples)
- say, I have
- int x 3 int y 5 int z 3
- boolean a true boolean b false
- !(x y)
- (y ! 5) (z lt 5) - Short Circuit
- (y gt 5) (x lt 6)
6if statement
public class Calendar public static void
main(String args) int month 5
if( (month gt 1) (month lt 12) )
System.out.println( Valid month )
7if statement without block
public class Calendar public static void
main(String args) int month 13
if( (month gt 1) (month lt 12) )
System.out.println( Valid month )
System.out.println( month )
if( (month gt 1) (month lt 12) )
System.out.println( Valid month )
System.out.println( month )
Correct way !
8if/else statement
public static void main(String args)
int month 5
if( (month gt 1) (month lt 12) )
System.out.println( Valid month ) else
System.out.println( No such month )
9if/else if statement
public static void main(String args)
int month 12
if( month 1 ) System.out.println(
January ) else if ( month 12 )
System.out.println( December ) else
System.out.println( No such month )
10Nested if statement
public static void main(String args)
int month 1 int day 1
if( (month 1) ) System.out.println(
January ) if( day 1 )
System.out.println( Sunday )
else System.out.println( No such
month )
11conditional operator (?)
public static void main(String args)
int month 2 String str null
System.out.println( str )
str ((month gt 1) (month lt 12) )
? "Valid Month" "Invalid Month"
Exercise int count 5 boolean k
(count lt 10) ? true false
Answer k is true
12Loops while loop
always check if infinite loop !!
public static void main(String args)
int j 0 while( j lt 5 )
System.out.println(j is j) j j 1
Exercise int k 7 while(k lt 8) k
k 1 (an infinite loop)
13Loops for loop
always check if infinite loop !!
public static void main(String args)
for( int j 0 j lt 5 j j 1 )
System.out.println(j is j)
Exercise for(int k 10 k gt 1 k k 1)
(an infinite loop)
14Loops do loop
always check if infinite loop !!
public static void main(String args)
int j 0 do System.out.println(j is
j) j j 1 while( j lt 5 )
Exercise int k 1 (not an infinite
loop) do
System.out.println( k ) while( k lt 1
)
15Nested Loops
public static void main(String args)
for( int j 0 j lt 4 j j 1 ) for( int
k 0 k lt 4 k k 1 )
System.out.println(j j
k k )