Home >Java >javaTutorial >Day16
Conditional statements, such as Java's if-else
construct, govern program execution based on specified conditions. The fundamental structure involves a condition followed by code blocks for both true and false outcomes. This branching capability allows the program to follow different execution paths depending on whether a condition evaluates to true or false.
Several types of decision-making statements exist, each offering varying levels of complexity and control:
if
statementif-else
statementif-else-if
statement (chained conditionals)if
statementswitch
statementif
Statement:An if
statement executes a block of code only when a given condition is true. If the condition is false, the code block is skipped.
Example:
<code class="language-java">package day1if; public class Main { public static void main(String[] args) { int bat = 500; if (bat >= 500) { System.out.println("Go to play"); } System.out.println("Don't play"); // This line always executes } }</code>
Output:
<code>Go to play Don't play</code>
if-else
Statement:The if-else
statement provides a choice between two code blocks. If the condition is true, the if
block executes; otherwise, the else
block executes.
Example:
<code class="language-java">package day1if; public class Main1 { public static void main(String[] args) { int bat = 500; if (bat > 600) { System.out.println("Go to play"); } else { System.out.println("Don't play"); } } }</code>
Output:
<code>Don't play</code>
if-else-if
Statement:This construct allows for multiple conditional checks. The code executes the block corresponding to the first true condition encountered. If none of the conditions are true, an optional else
block is executed. This provides a more structured way to handle multiple possible outcomes.
The above is the detailed content of Day16. For more information, please follow other related articles on the PHP Chinese website!