![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The if-else statement executes a single or block of statements of true block when condition becomes true otherwise, it executes the false block of statements.
The only difference in simple if and if-else statement is that the presence of else block when condition becomes false.
Syntax
if ( condition_to_check ) { // true block statements } else { // false block statements }
The compiler first executes the condition written into the if statement.
If the condition written inside the if statement gives result as true
, then compiler enters into the if
block otherwise it enters to the else
block.
Consider, if we want to check the age of person for the voting on election. The computer should decide whether person is eligible for voting or not.We will do this by using the if-else statement as below
class Voting { public static void main(String args[]) { byte age = 19; if (age < 18) { System.out.println("You are not eligible"); } else { System.out.println("Congrats, you can now vote."); } System.out.println("\nThank you for visiting."); } }
Output
Giving discount for golden tickets in the cinema hall.
class CinemaHall { public static void main(String args[]) { String type; byte numOfTickets = 4; short discount; int withoutDiscount,totalAmount; boolean isGolden = true; if (isGolden) { discount = (short) (numOfTickets * 50); withoutDiscount = (500 * numOfTickets); totalAmount = (500 * numOfTickets) - discount; type = "Golden"; } else { discount = (short) (numOfTickets * 30); withoutDiscount = (300 * numOfTickets); totalAmount = (300 * numOfTickets) - discount; type = "Non Golden"; } System.out.println("Ticket type : "+type); System.out.println("Total tickets : "+numOfTickets); System.out.println("Discount given : "+discount); System.out.println("Total without discount : "+withoutDiscount); System.out.println("Grand total with discount : "+totalAmount); } }
Output
In above example we have given discount for the golden tickets. If ticket is golden then we are giving discount based on number of tickets purchased multiplied by amount 50.