Java Conditional Statements - if
In Java, conditional statements are used to perform different actions based on different conditions. Let's explore three main conditional statements: if, if else, and else if.
1. The if
Statement
The if
statement allows you to execute a block of code if a specific condition is true.
Syntax:
if (condition) { // code to be executed if condition is true }
Example:
public class IfExample { public static void main(String[] args) { int number = 10; if (number > 5) { System.out.println("The number is greater than 5."); } } }
In this example, since 10 is greater than 5, the message will be printed.
2. The if else
Statement
The if else
statement is used when you want to specify an alternative action if the condition is false.
Syntax:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
Example:
public class IfElseExample { public static void main(String[] args) { int number = 3; if (number > 5) { System.out.println("The number is greater than 5."); } else { System.out.println("The number is less than or equal to 5."); } } }
In this example, since 3 is less than 5, the second message will be printed.
3. The else if
Statement
The else if
statement allows you to check multiple conditions in sequence, and execute code depending on which condition is true.
Syntax:
if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if none of the above conditions are true }
Example:
public class ElseIfExample { public static void main(String[] args) { int number = 7; if (number > 10) { System.out.println("The number is greater than 10."); } else if (number == 7) { System.out.println("The number is equal to 7."); } else { System.out.println("The number is less than 7."); } } }
In this example, the condition number == 7
is true, so the message "The number is equal to 7." will be printed.
Conclusion
In Java, you can use if
, if else
, and else if
statements to control the flow of your program based on certain conditions. Use if
when you need to execute a block of code if a condition is true, if else
when you need an alternative for false conditions, and else if
when you need to test multiple conditions.