Ticker

6/recent/ticker-posts

Java if else and else if Statements

Java if else and else if Statements

Introduction: 

In Java, the "if-else" and "else if" statements are used to control the flow of a program based on certain conditions. These conditional statements allow you to execute different blocks of code depending on whether a specified condition evaluates to true or false.

1. The if-else Statement:
The "if-else" statement is used when you want to execute one block of code if a condition is true and another block of code if the condition is false.

Syntax:

java
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

Example:

java
int age = 20;

if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}

Explanation:
In this example, we have an "age" variable with a value of 20. The if condition checks if the age is greater than or equal to 18. Since 20 is greater than 18, the code inside the if block will be executed, and the output will be "You are an adult."

2. The else if Statement:
The "else if" statement allows you to test multiple conditions in sequence. It is used when you have more than two possible outcomes.

Syntax:

java
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if all conditions are false
}

Example:

java
int num = 5;

if (num > 0) {
System.out.println("The number is positive.");
} else if (num < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}

Explanation:
In this example, we have a variable "num" with a value of 5. The first condition checks if "num" is greater than 0, and since it is true, the output will be "The number is positive." If the value of "num" were -5, the second condition (num < 0) would be true, and the output would be "The number is negative." If "num" were 0, both conditions would be false, and the code inside the else block would be executed, resulting in the output "The number is zero."

Remember that you can nest if-else and else-if statements to create more complex decision-making structures based on multiple conditions. Be cautious about indentation and using curly braces {} properly to ensure code readability and correctness.

Post a Comment

0 Comments