Ép kiểu trong Java (Type casting)

Ép kiểu là gì?

Ép kiểu là việc gán giá trị của một biến có kiểu dữ liệu này sang biến khác có kiểu dữ liệu khác.

Ví dụ:

float soLe = 19.7f;
int soNguyen = (int)soLe  + 1;

Trong ví dụ trên, giá trị soLe được đổi thành giá trị nguyên 19. Sau đó, nó được cộng với 1 và kết quả là giá trị 20 được lưu vào soNguyen .

Trong Java, có hai loại ép kiểu dữ liệu:

Nới rộng (widening)

Nới rộng (widening): Là quá trình làm tròn số từ kiểu dữ liệu có kích thước nhỏ hơn sang kiểu có kích thước lớn hơn. Kiểu biến đổi này không làm mất thông tin. Ví dụ chuyển từ int sang float. Chuyển kiểu loại này có thế được thực hiện ngầm định bởi trình biên dịch.

byte -> short -> int -> long -> float -> double

public class TestWidening {
    public static void main(String[] args) {
        int i = 100;
        long l = i;    // không yêu cầu chỉ định ép kiểu
        float f = l;   // không yêu cầu chỉ định ép kiểu
        System.out.println("Giá trị Int: " + i); // Giá trị Int: 100
        System.out.println("Giá trị Long: " + l); // Giá trị Long: 100
        System.out.println("Giá trị Float:  " + f); // Giá trị Float: 100.0
    }
}

Thu hẹp (narrowwing)

Thu hẹp (narrowwing): Là quá trình làm tròn số từ kiểu dữ liệu có kích thước lớn hơn sang kiểu có kích thước nhỏ hơn. Kiểu biến đổi này có thể làm mất thông tin như ví dụ ở trên. Chuyển kiểu loại này không thể thực hiện ngầm định bởi trình biên dịch, người dùng phải thực hiện chuyển kiểu tường minh.

double -> float -> long -> int -> short -> byte

public class TestNarrowwing {
public static void main(String[] args) {
double d = 100.04;
long l = (long) d; // yêu cầu chỉ định kiểu dữ liệu (long)
int i = (int) l; // yêu cầu chỉ định kiểu dữ liệu (int)
System.out.println("Giá trị Double: " + d); System.out.println("Giá trị Long: " + l); System.out.println("Giá trị Int: " + i); }
}

Bảng mô tả ép kiểu trong Java

Ép kiểuChuyển sang kiểu
Từ kiểubooleanbyteshortcharint longfloatdouble
boolean–NoNoNoNoNoNoNo
byteNo–YesCastYesYesYesYes
shortNoCast–CastYesYesYesYes
charNoCastCast–YesYesYesYes
int NoCastCastCast–YesYesYes
longNoCastCastCastCast–YesYes
floatNoCastCastCastCastCast–Yes
doubleNoCastCastCastCastCastCast–

Trong đó

  • -: chính nó
  • No: không ép kiểu được
  • Yes: thực hiện ép kiểu nới rộng (widening)
  • Cast: thực hiện ép kiểu thu hẹp (narrowwing)

Related posts:

Spring RestTemplate Request/Response Logging
Introduction to Spring Cloud Rest Client with Netflix Ribbon
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Spring Security Remember Me
Java Program to Implement Euclid GCD Algorithm
Case-Insensitive String Matching in Java
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
OAuth 2.0 Resource Server With Spring Security 5
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Set Interface trong Java
Hướng dẫn Java Design Pattern – Null Object
Tính trừu tượng (Abstraction) trong Java
Java Program to Implement Adjacency Matrix
Java Program to Implement Efficient O(log n) Fibonacci generator
Send an email using the SMTP protocol
Java Program to Construct K-D Tree for 2 Dimensional Data
Custom HTTP Header with the HttpClient
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Spring Cloud AWS – RDS
Java Program to Generate N Number of Passwords of Length M Each
Java String Conversions
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Spring Boot - Rest Template
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Collect a Java Stream to an Immutable Collection
Spring Boot - Flyway Database
“Stream has already been operated upon or closed” Exception in Java
Tìm hiểu về Web Service
Jackson – Change Name of Field
Java Program to Implement Bloom Filter
Transaction Propagation and Isolation in Spring @Transactional

1 Trackback / Pingback

  1. Cơ chế Upcasting và Downcasting trong java – BLOG CHIA SẺ KIẾN THỨC CỦA VIETMX

Comments are closed.