Course contentsShow
← Java
Lesson 133 of 2,8703. Operators and ExpressionsFree lesson

Ternary Operator Type Resolution and Auto-boxing

Learn how Java determines the result type of ternary expressions, including numeric promotion and reference type handling.

Ternary Operator Type Resolution and Auto-boxing

What you'll learn: How Java decides what type to give the result of a ternary expression when the two branches have different types.

The Type Resolution Challenge

When you write a ternary operator expression like condition ? value1 : value2, Java must determine a single result type for the entire expression. But what happens when value1 and value2 are different types?

Java follows specific rules to resolve this:

Numeric Promotion Rules

When both operands are numeric primitives, Java promotes them to a common type:

  • If one is double, the result is double
  • If one is float, the result is float
  • If one is long, the result is long
  • Otherwise, the result is int
int x = 5;
double y = 3.14;
// Result type is double (wider type wins)
double result = true ? x : y;  // 5.0

The Auto-boxing Consideration

When one operand is a primitive and the other is a reference type (like Integer), Java must box the primitive to match:

Integer boxed = 10;
int primitive = 20;
// Result type is Integer (reference type)
Integer result = true ? boxed : primitive;  // primitive gets auto-boxed

Same-Type Rule

When both operands are already the same type, that's the result type:

int a = 10;
int b = 20;
int result = false ? a : b;  // Result type: int

Key Takeaway: Java resolves ternary operator result types by promoting numerics to the wider type, and when mixing primitives with wrapper objects, the result becomes the reference type through auto-boxing.