Widening Primitive Conversion
การแปลงชนิดข้อมูล primitive จากขนาดเล็กไปขนาดใหญ่ อัตโนมัติ ไม่สูญเสียข้อมูล
ลำดับ Widening
byte → short → int → long → float → double
char → int → long → float → double
ตัวอย่าง: การรวม char ด้วย +
public class Demo {
public static void main(String[] args) {
System.out.print("H" + "E"); // String concatenation → "HE"
System.out.print('L'); // char → 'L'
System.out.print('L'); // char → 'L'
System.out.print('O'); // char → 'O'
}
}
ผลลัพธ์
HELLO
คำอธิบาย:
"H" + "E"เป็น String concatenation (ทั้งคู่เป็น String literal) ผลลัพธ์ "HE"'L'เป็น char literal พิมพ์ตัวอักษรเดี่ยว- ไม่ได้เป็น widening conversion จริงๆ ในตัวอย่างนี้
ตัวอย่าง Winding จริง
public class Demo {
public static void main(String[] args) {
byte b = 100;
short s = b; // byte → short (widening)
int i = s; // short → int (widening)
long l = i; // int → long (widening)
float f = l; // long → float (widening, อาจสูญเสีย precision)
double d = f; // float → double (widening)
// char → int
char c = 'A';
int charCode = c; // 65
// Expression promotion
byte x = 10, y = 20;
int sum = x + y; // byte + byte → int (promotion)
// byte z = x + y; // compile error! ต้อง cast
}
}
Narrowing (ตรงข้าม)
ต้อง cast ใส่ชนิดปลายทาง อาจสูญเสียข้อมูล
int i = 300;
byte b = (byte) i; // 44 (overflow)
double d = 3.14;
int j = (int) d; // 3 (truncate)