Back to Java
2025-12-135 min read

Java If Else

Learn Java If Else step by step with clear examples and exercises.

Title: Mastering Java If Else Statements - A full guide

Why This Matters

Java's if and else statements are fundamental building blocks for making decisions within your code, allowing you to write more sophisticated programs. Understanding these constructs will help you tackle real-world programming challenges, ace coding interviews, and even debug common errors in your own projects.

Prerequisites

Before diving into the if and else statements, it's essential that you have a solid grasp of:

  1. Basic Java syntax (variables, data types, operators)
  2. Control structures (loops - for, while, and do-while)
  3. Understanding how to declare and use methods in Java

Core Concept

The if statement in Java allows you to execute a block of code if a specific condition is met, while the else statement provides an alternative block of code to be executed when the initial condition is not satisfied. Let's take a look at the basic structure:

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

Single if statement example

int age = 25;

if (age >= 18) {
System.out.println("You are eligible to vote.");
}

In this example, the code inside the if block will be executed if the condition (age >= 18) is true, and the code within the else block will be executed if the condition is false.

Multiple conditions with if-else if ladder

int grade = 75;

if (grade >= 90) {
System.out.println("Grade A");
} else if (grade >= 80) {
System.out.println("Grade B");
} else if (grade >= 70) {
System.out.println("Grade C");
} else {
System.out.println("You need to study more.");
}

In this example, the program checks multiple conditions using an if-else if ladder, and the first matching condition will be executed. If none of the conditions are met, the code within the final else block will be executed.

Nested if statements

You can also nest if statements to create more complex decision structures:

int age = 20;
int height = 165;

if (age >= 18) {
if (height >= 170) {
System.out.println("Eligible for military service.");
} else {
System.out.println("Height is too short for military service.");
}
} else {
System.out.println("Too young for military service.");
}

In this example, the outer if statement checks if the person's age is 18 or older. If so, the inner if statement checks whether their height meets the requirements for military service.

Worked Example

Let's create a simple Java program that calculates the grade point average (GPA) and determines the student's academic standing based on the GPA:

import java.util.Scanner;

public class GpaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of subjects: ");
int numSubjects = scanner.nextInt();

double totalGradePoints = 0;
int totalCredits = 0;

for (int i = 1; i <= numSubjects; i++) {
System.out.printf("Enter the grade and credits for subject %d: ", i);
double grade = scanner.nextDouble();
int credits = scanner.nextInt();

if (grade >= 90) {
totalGradePoints += 4 * credits;
} else if (grade >= 80) {
totalGradePoints += 3 * credits;
} else if (grade >= 70) {
totalGradePoints += 2 * credits;
} else if (grade >= 60) {
totalGradePoints += 1 * credits;
} else {
System.out.printf("Invalid grade for subject %d.\n", i);
}

totalCredits += credits;
}

double gpa = totalGradePoints / totalCredits;
String academicStanding = "";

if (gpa >= 3.7) {
academicStanding = "Honors";
} else if (gpa >= 3.3) {
academicStanding = "Good Standing";
} else if (gpa >= 2.0) {
academicStanding = "Probation";
} else {
academicStanding = "Dismissed";
}

System.out.printf("Your GPA is %.2f.\n", gpa);
System.out.println("Academic Standing: " + academicStanding);
}
}

Common Mistakes

  1. Forgetting to enclose the condition in parentheses:

Correct: if (condition)

Incorrect: if condition

  1. Leaving out braces {} for the code blocks:

Correct:

if (condition) {
// Code to be executed
}

Incorrect:

if (condition)
// Code to be executed
  1. Neglecting to consider the order of if-else conditions:

Correct:

if (grade >= 90) {
System.out.println("Grade A");
} else if (grade >= 80) {
System.out.println("Grade B");
} else if (grade >= 70) {
System.out.println("Grade C");
} else {
System.out.println("You need to study more.");
}

Incorrect:

if (grade >= 90) {
System.out.println("Grade A");
}
if (grade >= 80) {
System.out.println("Grade B");
}
if (grade >= 70) {
System.out.println("Grade C");
} else {
System.out.println("You need to study more.");
}

Practice Questions

  1. Write a Java program that takes two numbers as input and determines whether the first number is greater than, equal to, or less than the second number using if statements.
  2. Write a Java program that calculates the area of a rectangle based on user input for length and width using nested if-else statements.
  3. Write a Java program that checks if a year entered by the user is a leap year using if-else statements.

FAQ

  1. Why do I need to use braces in my if statement?

Braces are essential for organizing your code and making it easier to read and maintain. They help you group related lines of code together, so the compiler knows which lines belong within the if block. Without braces, it can be difficult to understand the intended behavior of your code.

  1. What happens if I forget to put a semicolon at the end of an if statement?

In Java, a missing semicolon at the end of an if statement will not cause a syntax error. However, it can lead to unexpected results and make your code harder to understand. It's best to always include semicolons for clarity and consistency.

  1. Can I nest more than two levels of if-else statements?

Yes, you can nest as many levels of if-else statements as needed in your Java programs. Keep in mind that deeply nested structures can make your code harder to read and maintain, so it's best to keep things simple whenever possible.

Java If Else | Java | XQA Learn