If Statement in Java
Understanding Conditional Statements in Java
Your Name | Date
Introduction to Conditional Statements
• Java allows decision-making using conditional
statements.
• The if statement is used to execute a block of code if a
specified condition is true.
• Commonly used to control program flow based on
conditions.
Syntax of If Statement
• Syntax:
if (condition) {
// Code to execute if condition is true
}
Example of If Statement
• Example:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
• Explanation:
• • If age is 18 or more, the message "You are eligible to vote." is printed.
• • Otherwise, nothing happens.
If-Else Statement
• Syntax:
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
Example of If-Else Statement
• Example:
int number = 10;
if (number % 2 == 0) {
System.out.println("The number is a Even number");
} else {
System.out.println(" The number is a Odd number ");
}
• Explanation:
• • Checks if number is divisible by 2.
• • Prints "Even number" if true, otherwise prints "Odd number".
Else-If Ladder
• Syntax:
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition2 is true
} else {
// Executes if none of the above conditions are true
}
Example of Else-If Ladder
• Example:
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
• Explanation:
• Evaluates multiple conditions to determine the grade.
Nested If Statements
• Syntax:
if (condition1) {
if (condition2) {
// Executes if both conditions are true
}
}
Example of Nested If
• Example:
int num = 15;
if (num > 0) {
if (num % 5 == 0) {
System.out.println("Positive number and divisible by 5");
}
}
Explanation:
• • First checks if num is positive.
• • Then checks if it is divisible by 5.
Summary
• The if statement executes code only when a condition is true.
• The if-else statement provides an alternative action if the
condition is false.
• The else-if ladder handles multiple conditions.
• Nested if statements allow more complex decision-making.