Advertisement

Google Ad Slot: content-top

Java If Else


if Statement:

The if statement is used to execute a block of code only if a specified condition evaluates to true.


Syntax:

if (condition) { 
   // Code to execute if condition is true 
}
Example
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
Try it yourself

if...else Statement:

The if...else statement allows you to execute one block of code if the condition is true and another block if the condition is false


Syntax:

if (condition) { 
   // Code to execute if condition is true 
} else { 
   // Code to execute if condition is false 
}
Example
int age = 16;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}

Try it yourself

if...else if...else Statement

For multiple conditions, you can use else if blocks.


Syntax:

if (condition) { 
   // Code to execute if condition is true 
} else if(condition2) { 
   // Code to execute else if condition is true 
} else {
   // Code to execute if and else if condition is false 
}
Example
int score = 85;

if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
Try it yourself

Ternary Operator:

For simple if...else conditions, you can use the ternary operator:

Example
int age = 20;
String status = age >= 18 ? "Adult" : "Minor";
System.out.println(status); // Adult
Try it yourself

Nested if...else:

You can nest if...else statements inside each other, but keep readability in mind.

Example
int number = 10;

if (number > 0) {
if (number % 2 == 0) {
System.out.println("The number is positive and even.");
} else {
System.out.println("The number is positive and odd.");
}
} else {
System.out.println("The number is not positive.");
}
Try it yourself

Logical Operators in Conditions

You can use logical operators (&&||!) to combine conditions.

1.AND (&&):

Example
int age = 25;

if (age > 18 && age < 30) {
System.out.println("You are in your 20s.");
}
Try it yourself

2.OR (||):

Example
String day = "Saturday";

if (day == "Saturday" || day === "Sunday") {
System.out.println("It's the weekend!");
}
Try it yourself

3.NOT (!):

Example
boolean isRaining = false;

if (!isRaining) {
System.out.println("You can go outside without an umbrella.");
}
Try it yourself