Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Operators and Assignments - Ternary Operator

Syntax

    operand1 ? operand2 : operand3
  • also referred to as the conditional operator
  • if operand1 is true, operand2 is returned, else operand3 is returned
       true ? op2 : op3             // op2 returned
      false ? op2 : op3             // op3 returned
  • operand1 must be a boolean type
  • operand1 can be an expression that evaluates to a boolean type
       (5 == 5) ? "yes" : "no"     // output: yes
  • operand1 and operand2 must be promotable numeric types or castable object references, or null
  • if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
      byte = true ? byte : short  // found short, required byte
  • if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands range, the type of the returned value will be the type of the other operand
      short =  true ? short : 1000 // compiles and runs ok
      short = false ? short : 1000 // compiles and runs ok
  • otherwise, normal binary numeric promotion applies
  • if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
  • if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type
Class_A a = new Class_A();
Class_B b = new Class_B();  // subclass of Class_A
Class_C c = new Class_C();
Class_A a1 = b;
Class_C c1;

c1 = false ? a : c;         // compile-error: incompatible types
a1 =  true ? b : a;         // returns class type of Class_B

Example Code

Traps

  • a non-boolean value or expression used for operand1


Conversions Promotion Overflow Unary Prefix Arithmetic
  Bin/Hex/Octal Bitwise Shift Comparison Logical Assignment
  Cast Ternary String equals() Precedence Bit vs Logic
  Method Invocation