Just like the decisions we make in life such as for example buying a car. If the car we are looking for is higher than our searching price then that car is too expensive and we won’t buy it. Else if the car is at our searching price or less we will buy it. In Java and programming in general, we use conditional statements to evaluate our decision.
We use the comparison operators to evaluate our condition.
1. Less than (x < y)
2. Less than or equal to (x <= y)
3. Greater than (x > y)
4. Greater than or equal to (x >= y)
5. Equal (x == y)
6. Not equal (x != y)
If - one if if (condition) statement; if (condition) { statement; statement; }
It is recommended to use {} to specify where the block code ends. It is for readability.
if(10 > 5){ System.out.println("10 is greater than 5"); }
(10 > 5) – condition
System.out.println(“10 is greater than 5”); – statement
If Else – one if else
if(condition){
statement;
}else{
statement;
}
if(5 < 10){ System.out.println("5 is less than 10"); }else{ System.out.println("10 is greater than 5"); }
If ElseIf ElseIf Else - multiple if else if (condition1) { //block of code to execute if condition1 is true ; }else if(condition2){ //block of code to execute if condition2 is true ; }else if(condition3){ //block of code to execute if condition3 is true ;; }else{ //block of code to execute if none of the above conditions are true; }
int age 30; if(age < 19){ System.out.println("You are a baby."); } else if (age < 30){ System.out.println("You are an adult."); } else { System.out.println("You are old."); }
Switch Statement
Switch statement provides better readability when they are too many if else statements.
String gender = "MALE"; switch(gender){ case:"MALE"; System.out.println("You are a man"); break; case:"FEMALE"; System.out.println("You are a woman"); break; default: System.out.println("You are bisexual"); break; }
IF, IF ELSE, and ELSE
double amount = 0; if(amount>0) { System.out.println("amount>0"); }else if(amount<0) { System.out.println("amount<0"); }else { System.out.println("amount=0"); } // output amount=0
double amount = -0.60; if(amount < -0.50) { System.out.println("amount < -0.50"); }else { System.out.println("amount > -0.50"); } //output amount < -0.50