Java condition statement detailed explanation: if, else, else if and nested if statement
This article will explore the conditional statements in Java, including if
, else
, else if
and nesting if
statements, and explain how to use them to control the program process. We will help you understand the working principles of these sentences and their application in actual programming through clear grammar examples and code examples.
Java uses the following conditional statements to execute different code blocks according to different conditions:
Sentence: if
When the specified condition is true, execute the code block.
Sentence: When the conditions in the else
statement are fake, execute the code block.
if
When the previous or else if
conditions are fake, test new conditions.
if
else if
switch
The statement is used to execute the code block according to the conditions. If the condition is true, execute the code block; otherwise, skip the code block.
if
grammar:
if
Note: must be a lowercase. Capital (if or IF) can cause errors.
<code class="language-java">if (condition) { // 条件为真时执行的代码块 }</code>
Output:
if
20 greater than 18
Sentence
<code class="language-java">if (20 > 18) { System.out.println("20 大于 18"); }</code>
statements. When the conditions in the statement are the code block when fake.
grammar:
Example: else
Output: else
if
if
Good every.
Sentence
<code class="language-java">if (condition) { // 条件为真时执行的代码块 } else { // 条件为假时执行的代码块 }</code>
grammar:
<code class="language-java">int time = 20; if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); }</code>
Example:
Output: else if
Good every.
else if
Stagenical sentence if
Stepses allow multiple conditions to test and perform only one of the codes corresponding to one of the conditions.
<code class="language-java">if (condition1) { // condition1 为真时执行的代码块 } else if (condition2) { // condition1 为假且 condition2 为真时执行的代码块 } else { // condition1 和 condition2 都为假时执行的代码块 }</code>
sentence
nested sentence refers to the other statement in the code block of one statement.
<code class="language-java">int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); }</code>
abbreviation (three yuan computing symbols) if...else
statements. if...else
Example: variable = (condition) ? expressionTrue : expressionFalse;
Reference link:
<code class="language-java">if (condition) { // 条件为真时执行的代码块 }</code>
W3Schools java conditional statement
javatpoint java if-ogse statementThe above is the detailed content of Java if-else Statement. For more information, please follow other related articles on the PHP Chinese website!