The Java if statement is used to test the condition. There are various types of statement in java.
- If statement – In this statement, the expression is a boolean expression(returns true or false).
- if(condition)
{
//code to be executed
} - If-else statement – This statement also test the condition and it executes the if block if the condition is true otherwise else block is executed.
- if(condition)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
} - if-else-if statement – The if-else if ladder statement executes one statement from multiple conditions.
- if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions are false
}
class If1 { public static void main(String args[]) { int age=24; if(age>18) { System.out.println("You are eligible to vote"); } } } Output: You are eligible to vote
class If2 { public static void main(String args[]) { int a=2016; if(a%4==0) { System.out.println("Leap year"); } else { System.out.println("Not a leap year"); } } } Output: Leap year
class If3 { public static void main(String args[]) { int marks=60; if(marks<=33) { System.out.println("fail"); } else if(marks>=34 && marks<=50) { System.out.println("D grade"); } else if(marks>=51 && marks<=70) { System.out.println("C grade"); } else if(marks>=71 && marks<=80) { System.out.println("B grade"); } else if(marks>=81 && marks<=90) { System.out.println("A grade"); } else if(marks>=91 && marks<=100) { System.out.println("A+ grade"); } else { System.out.println("Invalid!"); } } } Output: C grade