Curriculum
In Java, an “if” statement is used to make decisions based on a certain condition. If the condition is true, then the code inside the “if” block is executed, otherwise, the code inside the “if” block is skipped and the program moves on to the next statement.
Here is an example of the basic syntax of an “if” statement:
if (condition) { // code to be executed if condition is true }
Here, “condition” is any expression that evaluates to a boolean value, either “true” or “false”. If the condition is true, then the code inside the curly braces will be executed.
Here is an example of an “if” statement in action:
int x = 5; if (x > 3) { System.out.println("x is greater than 3"); }
In this example, the condition is “x > 3”, which is true since x is 5. Therefore, the code inside the curly braces will be executed, and the output will be “x is greater than 3”.
You can also use an “else” statement to provide an alternative code block to execute if the condition is false. Here’s an example:
int x = 2; if (x > 3) { System.out.println("x is greater than 3"); } else { System.out.println("x is less than or equal to 3"); }
In this example, since the value of x is 2, the condition “x > 3” is false. Therefore, the code inside the “else” block will be executed, and the output will be “x is less than or equal to 3”.