Numeric Promotion ใน Ternary Operator
Java ใช้ Numeric Promotion Rules กำหนด type ของ ternary expression condition ? expr1 : expr2 โดยพิจารณาจาก type ของ expr1 และ expr2
ตัวอย่างโค้ด
public class Demo {
public static void main(String[] args) {
// Ternary: true ? Integer : Float -> ผลลัพธ์เป็น Float (promoted)
Object obj = true ? new Integer(91) : new Float(89);
System.out.println("Ternary result: " + obj); // 91.0 (Float)
// If-else: ไม่มี promotion
Object obj2;
if (true)
obj2 = new Integer(91);
else
obj2 = new Float(89);
System.out.println("If-else result: " + obj2); // 91 (Integer)
}
}
ผลลัพธ์
Ternary result: 91.0 If-else result: 91
คำอธิบาย
Ternary Operator (Conditional Expression)
JLS §15.25: Type ของ conditional expression ถูกกำหนดโดย Binary Numeric Promotion บน operand ที่ 2 และ 3
IntegerและFloat→ Binary Numeric Promotion → float (primitive)- จากนั้น Boxing → Float (wrapper)
- Assignment ให้
Object→ Polymorphism OK - พิมพ์
91.0เพราะเป็น Float object
If-Else Statement
- ไม่มี expression type unification
- แต่ละ branch มี type ของตัวเอง
- Assignment ให้ Object → เก็บ Integer object ตรงๆ
- พิมพ์
91เพราะเป็น Integer object
Numeric Promotion Rules สรุป
| Operand 1 | Operand 2 | Result Type |
|---|---|---|
| int | double | double |
| long | float | float |
| int | long | long |
| byte | short | int (promoted) |
| Integer | Float | Float (unbox → promote → box) |
| Integer | Double | Double |
ตัวอย่างเพิ่มเติม
// Primitive types int a = 10; double b = 20.0; Object result = true ? a : b; // double -> Double -> prints "10.0" // Both same type Object result2 = true ? 10 : 20; // int -> Integer -> prints "10" // Narrowing not allowed in ternary // byte b = true ? 1 : 2; // Compile error: int cannot convert to byte // ต้อง cast: byte b = (byte) (true ? 1 : 2);
Best Practices
- หลีกเลี่ยงการผสม primitive types ที่ต่างกันใน ternary
- ใช้ explicit casting หากต้องการ type เฉพาะ
- พิจารณาใช้ if-else หาก logic ซับซ้อน หรือ type ไม่ตรงกัน
- ระวัง
nullternary:condition ? "str" : null-> String, แต่condition ? null : "str"-> String (OK)