Java Tutorial menu

Java If...Else and Switch

Conditions let your program choose what to do based on a value.

The if Statement

Code inside an if block runs only when the condition is true:

Example

java
public class Main {
  public static void main(String[] args) {
    int marks = 75;
    if (marks >= 50) {
      System.out.println("You passed");
    }
  }
}
Output
You passed

if...else

Add else for what should happen when the condition is false:

Example

java
int balance = 300;
int price = 450;

if (balance >= price) {
  System.out.println("Payment done");
} else {
  System.out.println("Not enough balance");
}
Output
Not enough balance

else if

Use else if to test several conditions in order. Java runs the first block that is true and skips the rest.

Example

java
public class Main {
  public static void main(String[] args) {
    int marks = 68;

    if (marks >= 80) {
      System.out.println("Grade A");
    } else if (marks >= 65) {
      System.out.println("Grade B");
    } else if (marks >= 50) {
      System.out.println("Grade C");
    } else {
      System.out.println("Fail");
    }
  }
}
Output
Grade B

The Ternary Operator

For a short if...else that gives back a value, use condition ? valueIfTrue : valueIfFalse:

Example

java
int temperature = 38;
String weather = (temperature > 35) ? "Very hot" : "Pleasant";
System.out.println(weather);
Output
Very hot

The switch Statement

switch compares one value against many fixed choices. It is cleaner than a long chain of else if.

Example

java
public class Main {
  public static void main(String[] args) {
    int day = 5;

    switch (day) {
      case 1:
        System.out.println("Monday");
        break;
      case 5:
        System.out.println("Friday");
        break;
      case 6:
      case 7:
        System.out.println("Weekend");
        break;
      default:
        System.out.println("Weekday");
    }
  }
}
Output
Friday
KeywordPurpose
caseOne possible value
breakStops the switch so the next cases do not run
defaultRuns when no case matches

If you forget break, Java "falls through" and runs the next case too. This is a very common bug.

The Arrow switch (Java 14+)

Modern Java has a shorter switch with ->. It never falls through, so you do not need break:

Example

java
String size = "M";
int price = switch (size) {
  case "S" -> 800;
  case "M" -> 1000;
  case "L", "XL" -> 1200;
  default -> 0;
};
System.out.println("Shirt price: Rs " + price);
Output
Shirt price: Rs 1000

Exercise

Exercise

What is printed if x is 10? if (x > 10) { print "A" } else if (x == 10) { print "B" } else { print "C" }

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp