Unit 3 Team Teach - 3.3
Unit 3 Team Teach
3.3 If Else Statements
Purpose of Else Statements
Else statements: Handles what happens when the if condition is false. Structure of If-Else:
- If statement with a condition.
- Else statement without a condition.
- Both parts have code blocks surrounded by {}.
don’t forget the brackets
int x = 10;
if (x > 10) {
System.out.println("x is greater than 10");
System.out.println("This code when the condition is true");
} else {
System.out.println("x is 10 or less");
System.out.println("This code runs when the condition is false");
}
//Without brackets:
if (x > 10)
System.out.println("x is greater than 10");
System.out.println("this code will always run");
x is 10 or less
This code runs when the condition is false
this code will always run
- Based on this code, if you were younger than 16 what would it print out?
- Write your own if else statement
If i were younger than 16 it would print out “Current age: [number less than 16]” “You are not old enough for a license yet.”
int myAge = 16;
System.out.println("Current Age: "+myAge);
if(myAge > 16)
{
System.out.println("haha old");
}
else if(myAge == 16)
{
System.out.println("haha teen");
}
else
{
System.out.println("haha young person");
}
Current Age: 16
haha teen