Conditional Statements
If/else statements
In Java, you can use if/else statements to control the flow of your program based on certain conditions. Here's an example:
In the above example, we use an if/else statement to check if the age
variable is greater than or equal to 18. If it is, we display the message "You are an adult." If it's not, we display the message "You are a minor."
You can also use if statements without an else statement, like this:
In the above example, we use an if statement to check if the age
variable is greater than or equal to 18. If it is, we display the message "You are an adult." Regardless of the result, we then display the message "Program complete."
Switch statements
In Java, you can use switch statements to simplify complex if/else statements. Here's an example:
In the above example, we use a switch statement to check the value of the dayOfWeek
variable. Depending on its value, we display the corresponding day of the week. The default
case is used when none of the other cases match. The break
statement is used to exit the switch statement and continue with the rest of the program.
Last updated