Java Conditional Statements - if...else
Conditional statements in Java allow the program to execute different code blocks based on different conditions.
An if statement contains a boolean expression and one or more statements.
Syntax
The syntax of the if statement is as follows:
If the value of the boolean expression is true, execute the code block in the if statement; otherwise, execute the code after the else statement block.
Test.java file code:
The result of compiling and running the above code is as follows:
这是 if 语句
if...else statement
An if statement can be followed by an else statement. When the boolean expression of the if statement is false, the else statement block will be executed.
Syntax
The usage of if…else is as follows:
Example
Test.java file code:
The result of compiling and running the above code is as follows:
这是 else 语句
if...else if...else statement
An if statement can be followed by an else if…else statement, which can detect multiple possible conditions.
When using if, else if, and else statements, you need to note the following points:
- An if statement can have at most one else statement, and the else statement comes after all else if statements.
- An if statement can have several else if statements, and they must come before the else statement.
- Once one of the else if statements evaluates to true, the other else if and else statements will be skipped.
Syntax
The if...else syntax format is as follows:
Example
Test.java file code:
The result of compiling and running the above code is as follows:
Value of X is 30
Nested if…else statements
Using nested if…else statements is legal. That is, you can use an if or else if statement inside another if or else if statement.
Syntax
The nested if…else syntax format is as follows:
You can nest else if...else just like if statements.
Example
Test.java file code:
The result of compiling and running the above code is as follows:
X = 30 and Y = 10Other extensions