Java If...Else: Real-Life Examples
Understanding how to use if...else
statements in real-world scenarios can help solidify the concept. Below are examples demonstrating practical applications.
1. Age Verification
A program that checks if a user is old enough to vote.
import java.util.Scanner;
public class AgeVerification {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
scanner.close();
}
}
Output:
Enter your age: 20
You are eligible to vote.
2. Simple Login System
A program that checks user credentials.
import java.util.Scanner;
public class LoginSystem {
public static void main(String[] args) {
String username = "admin";
String password = "password123";
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String inputUsername = scanner.nextLine();
System.out.print("Enter password: ");
String inputPassword = scanner.nextLine();
if (inputUsername.equals(username) && inputPassword.equals(password)) {
System.out.println("Login successful.");
} else {
System.out.println("Invalid credentials.");
}
scanner.close();
}
}
Output:
Enter username: admin
Enter password: password123
Login successful.
3. Grading System
A program that assigns grades based on marks.
import java.util.Scanner;
public class GradingSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your marks: ");
int marks = scanner.nextInt();
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
} else if (marks >= 70) {
System.out.println("Grade C");
} else if (marks >= 60) {
System.out.println("Grade D");
} else {
System.out.println("Grade F");
}
scanner.close();
}
}
Output:
Enter your marks: 85
Grade B
Key Takeaways
if...else
statements are essential for decision-making in applications.- They can be used in various scenarios like authentication, data validation, and conditional operations.
- Understanding practical examples helps in applying the concept effectively.