Conditional Statement in Java|set 2

Nested if Statements:

You can use one if-else statement inside another if or else statement.
For example:

int age = 36;
if(age > 1) {
 if(age > 20) {
 System.out.println("Welcome to HelloTech!");
 } else {
 System.out.println("You are too Young");
 }
} else {
 System.out.println("Error");
}
//Outputs "Welcome to HelloTech!"

You can nest as many if-else statements as you want.

else if Statements:

Instead of using nested if-else statements, you can use the else if statement to check multiple conditions.
For example:

int age = 25;
if(age <= 5)
 {
 System.out.println("Error");
} 
else if(age <= 15) 
{
 System.out.println("Too Young");
} 
else if(age < 100) 
{
 System.out.println("Welcome to HelloTech!");
} 
else 
{
 System.out.println("Really?");
}
//Output: "Welcome to HelloTech!"

The code will check the condition to evaluate to true and execute the statements inside that block.You can include as many else if statements as you need.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s