
If you have already register Login here.
Decision making Statements
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.
Java if Statement
The structure of the “if” statement in Java looks like this:
if (condition) {
  // execute this code
}
public class IfExample{
	public static void main(String[] args) {
		int age = 3;
		System.out.println("Shivani is " + age + " years old");
		if (age < 4) {
			System.out.println("Shivani is a baby");
		}
	}
}
Shivani is 3 years old
Shivani is a babyOutput Detail : In the example above we check if the age is lower than 4. As the age is set to be 3, the boolean condition age < 4 is true and as result we print “Shivani is a baby”. If we change the age to any value greater than 3 the code in the block want execute anymore and “Shivani is a baby” is not printed.
The structure of the “if-else” statement in Java looks like this:
if(condition){  
//code if condition is true  
}else{  
//code if condition is false  
}  
public class IfElseExample{
	public static void main(String[] args) {
		int age = 15;
		System.out.println("Shivani is " + age + " years old");
		if (age < 4) {
			System.out.println("Shivani is a baby");
		}else{
			System.out.println("Shivani is not a baby may be adult");
        }
	}
}
Shivani is 15 years old
Shivani is not a baby may be adultOutput Detail : In the example above we check if the age is lower than 4. As the age is set to be 15, the boolean condition age < 4 is true and as result we print “Shivani is a baby”. If we change the age to any value greater than 4 the code in the block want execute anymore and “Shivani is not a baby may be adult” is printed.
The structure of the “if-else-if ladder” statement in Java looks like this:
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 if(condition4){  
//code to be executed if condition4 is true  
}   
...  
else{  
//code to be executed if all the conditions are false  
}  
public class IfElseIfLedder{
	public static void main(String[] args) {
		int age = 20;
		System.out.println("Shivani is " + age + " years old");
		if (age < 4) {
			System.out.println("Shivani is a baby");
		} else if (age >= 4 && age < 14) {
			System.out.println("Shivani is a child");
		} else if (age >= 14 && age < 18) {
			System.out.println("Shivani is a teenager");
		} else if (age >= 18 && age < 68) {
			System.out.println("Shivani is adult");
		} else {
			System.out.println("Shivani is an old women");
		}
	}
}Shivani is 20 years oldShivani is adult
© 2025 Easy To Learning. All Rights Reserved | Design by Easy To Learning
