Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การแปลงชนิดข้อมูล Integer ใน JShell Java 9

JShell เป็นเครื่องมือ command-line แบบโต้ตอบใน Java 9 ให้นักเขียนโปรแกรมรัน statements, expressions, variables, methods, classes, interfaces ฯลฯ โดยไม่ต้อง declare main() method

ใน JShell compiler จะเตือนเกี่ยวกับ typecasting issues โดยโยน errors แต่ถ้านักเขียนโปรแกรมรู้แล้ว ต้องใช้ explicit casting ถ้าต้องการเก็บ ค่าที่เล็กกว่าเข้า type ที่ใหญ่กว่า จะใช้ implicit casting

ประเภท Integer Type Casting 2 แบบ

  • Literal-to-variable assignment: เช่น short s1 = 123456 ค่าออกนอก range รู้ได้ที่ compile-time compiler โยน error
  • Variable-to-variable assignment: เช่น s1 = i1 ค่าที่เก็บใน int: 4567 อยู่ใน range ของ short compiler ไม่โยน error สามารถ pre-empt ด้วย explicit casting s1 = (short) i1

ตัวอย่างใน JShell


C:\Users\User>jshell
|  Welcome to JShell -- Version 9.0.4
|  For an introduction type: /help intro

jshell> byte b = 128;
|  Error:
|  incompatible types: possible lossy conversion from int to byte
|  byte b = 128;
|       ^---^

jshell> short s = 123456;
|  Error:
|  incompatible types: possible lossy conversion from int to short
|  short s = 123456;
|       ^----^

jshell> short s1 = 3456
s1 ==> 3456

jshell> int i1 = 4567;
i1 ==> 4567

jshell> s1 = i1;
|  Error:
|  incompatible types: possible lossy conversion from int to short
|  s1 = i1;
|       ^^

jshell> s1 = (short) i1;
s1 ==> 4567

jshell> int num = s1;
num ==> 4567

Primitive Type Ranges

Type Size Min Value Max Value
byte 8 bits -128 127
short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Casting Rules

From \ To byte short int long float double
byte - Implicit Implicit Implicit Implicit Implicit
short Explicit - Implicit Implicit Implicit Implicit
int Explicit Explicit - Implicit Implicit Implicit
long Explicit Explicit Explicit - Implicit Implicit
float Explicit Explicit Explicit Explicit - Implicit
double Explicit Explicit Explicit Explicit Explicit -

ข้อสังเกต

  • Widening (Implicit): ขนาดเล็ก → ใหญ่ (byte → short → int → long → float → double) ปลอดภัย ไม่สูญเสียข้อมูล
  • Narrowing (Explicit): ขนาดใหญ่ → เล็ก อาจสูญเสียข้อมูล ต้อง cast เอง
  • Literal integers เป็น int โดย default ต้อง cast ให้ byte/short
  • Compound assignment (+=, -=) มี implicit cast built-in

ตัวอย่าง Compound Assignment


jshell> byte b = 10;
b += 5;        // OK - implicit cast
b = b + 5;     // Error - ต้อง cast: b = (byte)(b + 5)

jshell> short s = 100;
s *= 2;        // OK
s = s * 2;     // Error - ต้อง cast