Java if...else
In Java, the if..else
statement is used to make decisions based on certain conditions. The basic syntax for an if..else
statement is as follows:
if (condition) {
// code to execute if condition is true
} else { // code to execute if condition is false
}
The condition
is an expression that evaluates to either true
or false
. If the condition is true
, the code within the first set of curly braces will be executed. If the condition is false
, the code within the second set of curly braces will be executed.
For example, consider the following code:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
In this example, the condition x > 5
is true
, so the output will be "x is greater than 5".
Another example:
String name = "John";
if (name.equals("John")) {
System.out.println("Hello, John!");
} else { System.out.println("You are not John.");
}
In this example, the condition name.equals("John")
is true
because the variable name
is equal to "John", so the output will be "Hello, John!".
You can also chain multiple conditions using else if
like this:
int x = 15;
if (x < 10) {
System.out.println("x is less than 10");
} else if (x < 20) {
System.out.println("x is greater than or equal to 10 and less than 20");
} else {
System.out.println("x is greater than or equal to 20");
}
In this example, the output will be "x is greater than or equal to 10 and less than 20".