The if statement is a fundamental control structure used to execute a block of code only if a specified condition evaluates to true. It allows you to introduce decision-making into your programs, which makes your code dynamic and responsive to different inputs and scenarios.
if StatementThe syntax of a simple if statement in Java is:
if (condition) {
// Code to execute if the condition is true
}
Here:
condition is a Boolean expression (evaluates to true or false).condition is true, the code inside the { } block (known as the “if block”) is executed.condition is false, the code inside the if block is skipped.if Statementint score = 85;
if (score > 70) {
System.out.println("You passed!");
}
In this example, the message "You passed!" will only be printed if score is greater than 70.
else and else ifJava also provides ways to extend if statements with else and else if clauses for more complex conditions:
else Statement: Runs a block of code if the if condition is false.
int score = 55;
if (score > 70) {
System.out.println("You passed!");
} else {
System.out.println("You need to improve.");
}
else if Statement: Allows for multiple conditions to be checked sequentially. This is helpful when you have multiple possible outcomes based on different conditions.
int score = 85;
if (score > 90) {
System.out.println("Excellent!");
} else if (score > 70) {
System.out.println("Good job!");
} else {
System.out.println("Keep trying!");
}
if StatementsYou can also nest if statements within each other to handle more complex conditions.
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive.");
} else {
System.out.println("You need a driver’s license.");
}
} else {
System.out.println("You are too young to drive.");
}
In this example, the program checks two conditions: age and license status.
if Statementsif statement. Breaking down conditions can make code easier to read.{ }: Although Java allows omitting braces for single statements, including them is generally recommended to avoid logical errors.