InfoparkDailyCAREER TOOLS

Java · Lesson 3 of 9

Operators, if & switch

Comparisons, logical operators, if / else and modern switch expressions.

Comparison operators: == != < > <= >=. Logical: && (and), || (or), ! (not). For Strings, compare contents with .equals(), not ==.

if / else if / else picks a branch. The ternary cond ? a : b picks a value.

Switch expressions (Java 14+)

String level = switch (years) {
    case 0 -> "Fresher";
    case 1, 2, 3 -> "Junior";
    default -> "Senior";
};

The arrow form has no fall-through, so no break is needed.

Example program

Run with JDK 17+: java Main.java
public class Main {
    public static void main(String[] args) {
        int score = 72;
        String city = new String("Kochi");

        if (score >= 80) {
            System.out.println("Excellent");
        } else if (score >= 60) {
            System.out.println("Shortlisted");
        } else {
            System.out.println("Try again");
        }

        System.out.println(city == "Kochi");        // compares references
        System.out.println(city.equals("Kochi"));   // compares text

        int years = 2;
        String level = switch (years) {
            case 0 -> "Fresher";
            case 1, 2, 3 -> "Junior";
            default -> "Senior";
        };
        System.out.println("Level: " + level);
    }
}

Output

Shortlisted
false
true
Level: Junior

Save the code as Main.java and run java Main.java (JDK 11+ runs single files directly). Names and figures are fictional.

Key points

  • Use .equals() for String contents.
  • Arrow switch: no fall-through, can return a value.
  • && and || short-circuit.

Quick check

How should you compare two Strings' text?

Practice task

Using a switch expression, convert a day number (1–7) into its weekday name, with "Invalid" as the default.

Interview corner

== vs equals()?

== checks whether two references point to the same object (or compares primitive values). equals() checks logical equality as defined by the class.

What is short-circuit evaluation?

With && and ||, the right side is evaluated only if needed — e.g. obj != null && obj.isValid() avoids a NullPointerException.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.