Java ternary operator

In this chapter you will learn:

  1. How to use the ternary ? Operator
  2. Syntax for Java ternary operator
  3. Example - Java ternary operator
  4. Example - obtain the absolute value of a variable.

Description

The ? operator is a ternary (three-way) operator.

Java ternary operator is basically a short form of simple if statement.

Syntax

The ? has this general form:


expression1 ? expression2 : expression3

expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated. Otherwise, expression3 is evaluated.

The expression evaluated is the result of the ? operation. Both expression2 and expression3 are required to return the same type, which can't be void.

Example

Here is an example of ? operator:

 
public class Main {
  public static void main(String[] argv) {
    int denom = 10;
    int num = 4;//from  w  ww. j a  v  a2  s . co m
    double ratio;

    ratio = denom == 0 ? 0 : num / denom;
    System.out.println("ratio = " + ratio);
  }
}

The output:

Example 2

Here is another program that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.

 
public class Main {
  public static void main(String args[]) {
    int i, k;/*w w w.j a  v a 2  s. c  o m*/
    i = 10;
    k = i < 0 ? -i : i; 
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);

    i = -10;
    k = i < 0 ? -i : i; 
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);

  }
}

The output generated by the program is shown here:

Next chapter...

What you will learn in the next chapter:

  1. What is Java If Statement
  2. Syntax for Java If Statement
  3. Example - for Java If Statement
  4. Example - If statement and comparison operators
  5. Example - If statement and single boolean variable
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator