Skip to main content

Chapter 4b - If Else

Conditional Structureโ€‹

๐Ÿ‘€ Reading Notes

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 false to true in line 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 OperatorDefinitionExample
==Equals2==2 -> True, 2==4 -> False
!=Not Equal2!=3 -> True, 2!=2 -> False
>Larger3>2 -> True
<Smaller4 < 5 -> True
>=Larger or Equals4 >= 2 -> True, 2>=2 -> Tru

Else IFโ€‹

note


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:
  1. What do you think it will print if num is 15


  2. What do you think it will print if num is 20


  3. What do you think it will print if num is 25


๐Ÿงช Try the code out~!