The if and else statements in Java are conditional execution statements, used to execute different code blocks based on conditional judgments. Syntax: if (condition) {execute code block} else {execute code block}. condition is a Boolean expression that evaluates to true or false. Nested if statements can create more complex condition checks. Example: Check if num is greater than 0, if so, print "positive number", otherwise print "non-positive number".
Usage of if and else statements in Java
What are if and else statements?
if and else statements are conditional execution statements, used to execute different code blocks based on conditional judgments.
Syntax:
<code class="java">if (condition) { // 如果 condition 为 true,执行此代码块 } else { // 如果 condition 为 false,执行此代码块 }</code>
where condition
is a Boolean expression that evaluates to true
or false
.
How to use if and else statements?
Example:
<code class="java">int num = 10; if (num > 0) { System.out.println("正数"); } else { System.out.println("非正数"); }</code>
In this example, if num
is greater than 0, print "positive number"; otherwise, print " Non-positive number".
Supplementary Note:
condition
can be simple comparisons (e.g. num > 0
) or more complex expressions (e.g. num % 2 == 0
). else if
statement. The above is the detailed content of How to use if and else in java. For more information, please follow other related articles on the PHP Chinese website!