Java If-Else Practice Questions (Real-Life Examples)
1. Eligibility to Vote
Write a Java program that checks if a person is eligible to vote. The user inputs their
age.
Logic:
import java.util.Scanner;
public class VotingEligibility {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
2. Even or Odd Number
Write a Java program that takes a number and determines if it's even or odd.
Logic:
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
3. Temperature Check
Write a program to give clothing advice based on the temperature:
- >30°C -> "It's hot, wear light clothes"
- 15-30°C -> "Nice weather, dress comfortably"
- <15°C -> "It's cold, wear a jacket"
Java If-Else Practice Questions (Real-Life Examples)
Logic:
import java.util.Scanner;
public class WeatherAdvice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the temperature in °C: ");
int temp = sc.nextInt();
if (temp > 30) {
System.out.println("It's hot, wear light clothes.");
} else if (temp >= 15) {
System.out.println("Nice weather, dress comfortably.");
} else {
System.out.println("It's cold, wear a jacket.");
}
}
}
4. Student Grade Evaluator
A student enters a percentage. Print the grade:
- >= 90 -> A
- 80-89 -> B
- 70-79 -> C
- 60-69 -> D
- <60 -> F
Logic:
import java.util.Scanner;
public class GradeEvaluator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your percentage: ");
int percent = sc.nextInt();
if (percent >= 90) {
System.out.println("Grade: A");
} else if (percent >= 80) {
System.out.println("Grade: B");
} else if (percent >= 70) {
System.out.println("Grade: C");
} else if (percent >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}
Java If-Else Practice Questions (Real-Life Examples)
5. ATM Withdrawal
Simulate an ATM machine that checks if the user has enough balance to withdraw money.
Logic:
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
double balance = 5000.0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter amount to withdraw: ");
double amount = sc.nextDouble();
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: $" + balance);
} else {
System.out.println("Insufficient balance.");
}
}
}