Home | Computer Science
If-Else
Definition
Conditional statements in Java allow for different blocks of code to be executed based on certain conditions.
If-Else in Java
If else Types :
- If : Works If condition is true, Otherwise skip the excution.
- If-Else : First block works if condition true, Second block works if false
- Else If : Used to check multiple conditions.
- Ternary Operator : It provides a shorthand for if-else.
Syntax Example:
- if (condition) { }
- if (condition) { } else { }
- if (condition) { } else if { } else { }
- variable = (condition) ? value_if_true : value_if_false;
Program
Input:
public class CombinedExample {
public static void main(String[] args) {
int score = 85; // Example score
int age = 16;
// Single If statement
if (score > 50) {
System.out.println("Pass");
}
// If-Else statement
if (score >= 90) {
System.out.println("Grade A");
} else {
System.out.println("Not Grade A");
}
// Else-If Ladder
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Very Good");
} else if (score >= 70) {
System.out.println("Good");
} else {
System.out.println("Average");
}
// Ternary Operator (Shorthand If-Else)
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(eligibility);
}
}
OUTPUT