Java if Statement
The if
statement in Java is a conditional control statement that allows you to execute a block of code only if a specified condition evaluates to true
. If the condition is false
, the code block will not be executed. This is useful for making decisions in your program based on certain conditions.
Syntax of if
Statement
if (condition) {
// Block of code to be executed if the condition is true
}
- condition: A boolean expression that evaluates to either
true
orfalse
. - Block of code: The code inside the braces
{}
will execute only if the condition istrue
.
Example of if
Statement
Here’s a simple example demonstrating the use of an if
statement:
public class IfStatementExample {
public static void main(String[] args) {
int number = 10;
// Using if statement to check if the number is positive
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
Explanation
- Declaration: The variable
number
is declared and initialized with the value10
. - Condition Check: The
if
statement checks whethernumber > 0
. Since10
is greater than0
, the condition evaluates totrue
. - Execution: Because the condition is
true
, the code inside theif
block (System.out.println("The number is positive.");
) is executed, and the output will be:
The number is positive.
Example with Multiple Conditions
You can also use the if
statement with various conditions. Here's an example that checks if a number is positive, negative, or zero:
public class IfStatementMultipleConditions {
public static void main(String[] args) {
int number = -5;
// Using if statement to check if the number is positive, negative, or zero
if (number > 0) {
System.out.println("The number is positive.");
}
if (number < 0) {
System.out.println("The number is negative.");
}
if (number == 0) {
System.out.println("The number is zero.");
}
}
}
Explanation
In this example:
- The program checks three different conditions:
- If
number
is greater than0
(positive). - If
number
is less than0
(negative). - If
number
is equal to0
.
- If
- Since
number
is-5
, the output will be:
The number is negative.
Summary
The if
statement is a fundamental control structure in Java that enables you to implement conditional logic in your programs. It helps you execute code selectively based on whether a certain condition holds true, making your applications more dynamic and responsive to different inputs and states.