If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, the if-else
statement is used for conditional branching, allowing your program to execute different blocks of code based on certain conditions. It's one of the fundamental control flow statements in Java and is widely used for decision-making.
The basic syntax of the if-else
statement is as follows:
javaCopy code
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Here's an example Java program demonstrating the usage of if-else
:
javaCopy code
import java.util.Scanner;
public class IfElseExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Check the age and display a message accordingly
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
scanner.close();
}
}
Example output:
mathematicaCopy code
Enter your age: 25
You are an adult.
In the example above, the program prompts the user to enter their age. The if-else
statement is used to check if the age is greater than or equal to 18. If the condition is true (age is 18 or older), the message "You are an adult." will be displayed. Otherwise, if the condition is false (age is younger than 18), the message "You are a minor." will be displayed.
You can also use nested if-else
statements to create more complex decision structures. Additionally, the else if
clause can be used to chain multiple conditions together.
javaCopy code
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
Remember that the if-else
statement evaluates the condition and executes the corresponding block of code based on whether the condition is true or false. It's an essential part of building logic and making decisions in Java programs.
Comments: 0