Menu
Coddy logo textTech

Ternary Operator

Part of the Fundamentals section of Coddy's Java journey — lesson 30 of 73.

The ternary operator is a simple one-line if-else statement. It has the following syntax:

variable = (condition) ? value_if_true : value_if_false;

The ternary operator evaluates the condition. If it's true, it assigns value_if_true to the variable; otherwise, it assigns value_if_false.

For example:

int age = 20;
String message = (age >= 18) ? "Adult" : "Minor";

In this example, since age is greater than or equal to 18, message will be assigned the value "Adult". If age were less than 18, message would be assigned "Minor".

You can nest ternary operators to handle multiple conditions:

int score = 75;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";

This checks multiple conditions in order. If score >= 90, grade is "A"; else if score >= 80, grade is "B"; else if score >= 70, grade is "C"; otherwise "F".

Note: Nested ternary operators can be hard to read. For complex conditions, use if-else statements instead.

challenge icon

Challenge

Beginner

Create a program that checks if a number is positive, negative, or zero using the ternary operator. The program should:

  1. Take an integer input from the user.
  2. Use the ternary operator to determine if the number is positive, negative, or zero.
  3. Print the result in the format: "The number is [positive/negative/zero]".

Cheat sheet

The ternary operator is a one-line if-else statement with the syntax:

variable = (condition) ? value_if_true : value_if_false;

It evaluates the condition and assigns value_if_true if the condition is true, otherwise assigns value_if_false.

Example:

int age = 20;
String message = (age >= 18) ? "Adult" : "Minor";

Nested ternary operators to handle multiple conditions:

int score = 75;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";

This checks multiple conditions in order. If score >= 90, grade is "A"; else if score >= 80, grade is "B"; else if score >= 70, grade is "C"; otherwise "F".

Note: Nested ternary operators can be hard to read. For complex conditions, use if-else statements instead.

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();
        String result = "";
        
        // Write your code below
        
        
        System.out.println("The number is " + result);
        scanner.close();
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals