Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai chuyển đổi kiểu nguyên trong JShell Java 9?

JShell là công cụ command-line tương tác giới thiệu trong Java 9 cho phép lập trình viên thực thi câu lệnh đơn giản, biểu thức, biến, method, class, interface... không cần khai báo phương thức main().

Trong JShell, compiler cảnh báo về vấn đề typecasting bằng cách ném lỗi. Tuy nhiên nếu lập trình viên nhận biết, ép kiểu tường minh (explicit casting) sẽ cần thiết. Nếu cần lưu giá trị dữ liệu nhỏ hơn vào kiểu lớn hơn, ép kiểu ngầm định (implicit casting) sẽ cần thiết.

Có hai loại ép kiểu nguyên:

  • Gán literal cho biến: Ví dụ short s1 = 123456, dữ liệu vượt phạm vi. Biết lúc compile-time, compiler báo lỗi.
  • Gán biến cho biến: Ví dụ s1 = i1. Giá trị lưu trong int lúc đó: 4567, nằm trong phạm vi short, compiler không báo lỗi. Có thể pre-empt bằng explicit casting s1 = (short) i1.

Đoạn mã dưới triển khai cả implicit và explicit type conversion.

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