Boolean Expressions | If Statements and Control Flow | If-Else Statements | Code Example | Hacks | Quiz |
Unit 3 - Boolean Expressions and if Statements Examples
Boolean Expressions and if Statements Examples
- Simple if Statement with Boolean Expression Example
- Nested if Statements with Complex Boolean Expressions Example
Simple if Statement with Boolean Expression Example
public class Main {
public static void main(String[] args) {
int age = 18;
// Check if age is greater than or equal to 18
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Main.main(null);
Nested if Statements with Complex Boolean Expressions Example
public class Main {
public static void main(String[] args) {
int score = 85;
boolean hasGoodAttendance = true;
// Check if score is greater than or equal to 90
if (score >= 90) {
System.out.println("Grade: A");
}
// Check if score is between 80 and 89 inclusive
else if (score >= 80 && score < 90) {
// Check for good attendance
if (hasGoodAttendance) {
System.out.println("Grade: B+");
} else {
System.out.println("Grade: B");
}
}
// Check if score is between 70 and 79 inclusive
else if (score >= 70 && score < 80) {
System.out.println("Grade: C");
}
// If score is below 70
else {
System.out.println("Grade: F");
}
}
}
Main.main(null);