📅  最后修改于: 2023-12-03 15:01:21.992000             🧑  作者: Mango
The if-else
statement is a control flow statement that allows us to execute certain statements based on certain conditions. In Java, the if-else
statement is used extensively, and it is a fundamental building block for creating more complex programs. In this guide, we will discuss the if-else
statement in Java in detail.
The syntax for the if-else
statement in Java is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
The condition
part of the if-else
statement is an expression that evaluates to a boolean value. If the condition
is true
, the code inside the curly braces following the if
statement gets executed. Otherwise, the else
block gets executed.
Here is an example of using the if-else
statement in Java:
int score = 85;
if (score >= 80) {
System.out.println("You passed the exam!");
} else {
System.out.println("Sorry, you failed the exam.");
}
In this example, we are checking whether the score
variable is greater than or equal to 80
. If it is, we print out a message saying that the user passed the exam. Otherwise, we print out a message saying that the user failed.
In Java, we can also use nested if-else
statements. A nested if-else
statement is an if-else
statement inside another if-else
statement. Here is an example:
int age = 25;
if (age >= 18) {
if (age < 21) {
System.out.println("You are an adult, but you cannot drink alcohol yet.");
} else {
System.out.println("You are an adult and can drink alcohol legally.");
}
} else {
System.out.println("You are not yet an adult.");
}
In this example, we are first checking whether the age
variable is greater than or equal to 18
. If it is, we are then checking whether it is less than 21
. If it is, we print out a message saying that the user is an adult but cannot drink alcohol yet. Otherwise, we print out a message saying that the user is an adult and can drink alcohol legally. If the age
variable is less than 18
, we print out a message saying that the user is not yet an adult.
The if-else
statement is a fundamental control flow statement in Java. It allows us to execute certain statements based on certain conditions. In this guide, we went over the syntax and examples of using the if-else
statement in Java. As you work on writing more complex programs, you will find that you will be using the if-else
statement quite often.