Java Tutorial

Java Ternary Operator

condition ? a : b picks one of two values without a full if — a compact expression, not a statement.

A value, not a statement

The ternary operator produces a value. Both branches must have a compatible type so the whole expression has one type. Use it for short picks — labels, defaults, one-liners — not for long logic.

Example

public class Main {
  public static void main(String[] args) {
    int n = 4;
    String kind = n % 2 == 0 ? "even" : "odd";
    System.out.println(kind);
  }
}

Assign or return in one line

Because it is an expression, you can assign it, pass it to a method, or return it — anywhere a value is expected.

Example

public class Main {
  static int abs(int n) {
    return n >= 0 ? n : -n;
  }
  public static void main(String[] args) {
    System.out.println(abs(-7));   // 7
    System.out.println(abs(3));    // 3
  }
}

Choose between numbers or strings

Both sides must fit a common type. Mixing an int and a double promotes todouble. Mixing unrelated types is a compile error.

Example

public class Main {
  public static void main(String[] args) {
    int age = 16;
    double fare = age < 18 ? 5.0 : 9.5;
    String seat = age < 12 ? "child" : "adult";
    System.out.println(seat + " pays " + fare);
  }
}

Read it aloud: “if the condition is true, take the left; otherwise take the right.” Parentheses around the condition are optional but often clearer.

Nesting stays rare

One ternary is readable. Nested ternaries are not — they hide which condition belongs to which branch. Preferif / else if when there are three or more paths.

Example — prefer if for grades

public class Main {
  public static void main(String[] args) {
    int score = 82;
    // readable with if:
    String grade;
    if (score >= 90) grade = "A";
    else if (score >= 80) grade = "B";
    else grade = "C";
    System.out.println(grade);
  }
}

Do not nest ternaries just to save lines. Reviewers will ask you to rewrite them as if — and they will be right.

Try It Yourself

Exercise: Given an int temp, set a String to "cold" if temp is below 10, otherwise "warm", using a ternary. Print it.

Show solution
int temp = 7;
String feel = temp < 10 ? "cold" : "warm";
System.out.println(feel);

The condition is temp < 10; the true branch is "cold", the false branch is "warm".

Key Takeaways

  • condition ? a : b is an expression that yields one of two values.
  • Both branches must have a compatible type.
  • Use ternaries for short picks; use if for multi-step or multi-branch logic.
  • Avoid nested ternaries — clarity beats cleverness.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Chemistry

Acid or base label

A ternary picks one of two strings from a boolean. pH below 7 is acid; otherwise base — a compact if-else.

Example

public class Main {
  public static void main(String[] args) {
    double ph = 5.5;
    System.out.println(ph < 7 ? "acid" : "base");
  }
}

FAQ: Java Ternary Operator

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java ternary operator examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java ternary operator in this Java Java lesson (Java Ternary Operator).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.