0

When to use if else if ladder in Java ?

Please kindly explain it in detail.

9th Oct 2018, 4:22 PM
Prince Gupta
Prince Gupta - avatar
1 Answer
+ 1
if-else statement example: int william = 20; lets check if william is 18 OR older. the if block will only execute if the condition is TRUE. william are older then 18 so ''welcome in!'' will prints out. so if williams age is for example 16 then the else block will execute because the condition is FALSE. if(william >= 18){ System.out.print("Welcome in!"); } else{ System.out.print("You are too young"); } if-else-if ladder statement example: int number = 30; here we will find the number and print the text. as you can see above the number we will find is 30. so lets check. if(number == 10){ // this condition is FALSE because 30 is not equal to 10, right? // so lets move to next. System.out.println("This is number 10"); } else if(number == 20){ // is this equal to 30? no its not! so lets move on. System.out.println("This is number 20"); } else if(number == 30){ // is this equal to 30? yes it is! so this block will execute System.out.println("This is number 30"); } else{ // BUT if you change the number to example 50, then none of the // conditions is TRUE so the else block will execute System.out.println("Cant find the number"); }
9th Oct 2018, 6:46 PM
JavaBobbo
JavaBobbo - avatar