if...else Statement in Java.

Java  If else statement

In Java, if...else statement is used to check the boolean condition is true or false and based on the outcome, it runs a particular block of code and skips the other block of code present. There are various different ways and conditions in which the if-else statement is used for solving easy and complex problems.  

Example 1: if statement.

The block of code will execute if the boolean condition is true else nothing will execute. 


public class Main
{
	public static void main(String[] args) {
		int age = 18;
		
		if(age >= 18)
		   System.out.println("You are eligible to vote.");
	}
}
Output:
You are eligible to vote.

Example 2: if...else statement.

If the, if condition is true then the block of code present in the if block will get executed otherwise else block code will get executed. 


public class Main
{
	public static void main(String[] args) {
		int age = 17;
		
		if(age >= 18)
		   System.out.println("You are eligible to vote");
		else
		   System.out.println("You are not eligible to vote");
	}
}
Output:
You are not eligible to vote

Example 3: if-else if statement.

If we have more than one condition to check and the particular block of code gets executed whose condition is true. 


public class Main
{
	public static void main(String[] args) {
		
		int mark = 65;
		
		if(mark > 90)
		   System.out.println("Grade A");
		else if(mark > 70 && mark <= 90)
		   System.out.println("Grade B");
		else if(mark > 50 && mark <= 70)
		   System.out.println("Grade C");
		else
		   System.out.println("Fail");
	}
}
Output:
Grade C

Example 4: nested if-else statement.

In the nested if-else block, we get an if-else statement inside another if or else block of code. Inner condition is checked only if the other condition is true and nesting can be done up to any level. 

public class Main
{
	public static void main(String[] args) {
		
		int year = 2024;
		
		if(year % 4 == 0) {
		    if(year % 100 == 0) {  //check if the year is century
		        if(year % 400 == 0)  
		            System.out.println(year+" is a Leap Year");
		        else 
		            System.out.println(year+" is NOT a Leap Year");
		    }
		    else
		       System.out.println(year+" is a Leap Year");
		}
		else
		   System.out.println(year+" is NOT a Leap Year");
	}
}
Output:
2024 is a Leap Year

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS