The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
public class IfelseExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
else{
System.out.print("Age is lesser than 18");
}
}
}
watch for the implementation of if else in BLUEJ