Chapter 4b - If Else
Conditional Structureโ

If Elseโ
public class Main {
public static void main(String[] args) {
if(false){
System.out.println("Is True");
}else {
System.out.println("Is False");
}
}
}
๐งช Try the code out~!
Practice
- What do you think the program will be printing if we change
falsetotrueinline 3?
Using Comparisons to resolve If Else conditionalsโ

class Main{
public static void main (String args[]){
int my_age = 21;
int age_marie = 25;
if(my_age < age_marie){
System.out.println("I am Younger than Marie");
}else if(my_age > age_marie){
System.out.println("I am Older than Marie");
}
}
}
๐งช Try the code out~!
Comparison Operators
| Comparison Operator | Definition | Example |
|---|---|---|
== | Equals | 2==2 -> True, 2==4 -> False |
!= | Not Equal | 2!=3 -> True, 2!=2 -> False |
> | Larger | 3>2 -> True |
< | Smaller | 4 < 5 -> True |
>= | Larger or Equals | 4 >= 2 -> True, 2>=2 -> Tru |
Else IFโ
note

- I created this using draw.io
public class Main {
public static void main(String[] args) {
int age = 17;
if(age == 17){
System.out.println("Age is 17");
}else if(age>17) {
System.out.println("You are an adult now");
}else{
System.out.println("You are still a kid.");
}
}
}
Explaination:
If (Boolean condition1) Then
(perform computation or action)
Else if (Boolean condition2) Then
(perform another computation or action)
Else
(perform a default computation or action)
๐งช Try the code out~!
Exercise
๐ Exercise in the curriculum
Complete the following program so that it prints if number is positive or not.
- If the input is positive it should print:
num is positive. - else If the input is negative it should print:
num is negative - else (the case where input is neither positive or negative) it should print:
num is ZERO (0)
๐โโ๏ธ Sample expected program:
- Try entering
5 - Try entering
-5 - Try entering
0
Nested Conditionalsโ
๐ Curriculum - Nested Conditionals
public class Main{
public static void main(String args[]){
int num = 25;
if (num >5){
System.out.println("num is greater than 5");
if(num>10){
System.out.println("num is larger than 10");
if(num>20){
System.out.println("num is larger than 20");
}
}
}else if(num<0){
System.out.print ("num is negative");
}else{
System.out.print ("num is ZERO (0)");
}
}
}
Answer the following:
- What do you think it will print if num is 15
- What do you think it will print if num is 20
- What do you think it will print if num is 25