É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
booleanNoNoNoNoNoNoNo
byteNoYesCastYesYesYesYes
shortNoCastCastYesYesYesYes
charNoCastCastYesYesYesYes
int NoCastCastCastYesYesYes
longNoCastCastCastCastYesYes
floatNoCastCastCastCastCastYes
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:

Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Từ khóa throw và throws trong Java
Java Program to Find All Pairs Shortest Path
Spring Security 5 – OAuth2 Login
Java Program to Implement Max-Flow Min-Cut Theorem
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Using Spring @ResponseStatus to Set HTTP Status Code
Spring RestTemplate Request/Response Logging
A Guide to the ResourceBundle
The Spring @Controller and @RestController Annotations
Logout in an OAuth Secured Application
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Java Program to Perform the Shaker Sort
Java Program to Implement Sparse Array
Spring Boot Annotations
Using JWT with Spring Security OAuth
Chuyển đổi Array sang ArrayList và ngược lại
Spring Boot - Securing Web Applications
Create Java Applet to Simulate Any Sorting Technique
Spring Boot - Logging
Spring Boot - Hystrix
Daemon Threads in Java
Basic Authentication with the RestTemplate
Encode/Decode to/from Base64
Performance Difference Between save() and saveAll() in Spring Data
Generating Random Dates in Java
Serverless Functions with Spring Cloud Function
Sending Emails with Java
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Represent Graph Using 2D Arrays

1 Trackback / Pingback

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

Comments are closed.