JAVA Type Casting - (Data type convert)
2026-03-04 09:46
Tags: #java
Author: Duke Hsu
Key Concept
Type casting means converting one data type into another. For example, turning an intinto a double .
In Java, there are two main types of casting:
-
Widening Casting(automatic) - Converting a smaller type to a larger type size
byte->short->char->int->long->float->double -
Narrowing Casting(manual) - Converting a larger type to a smaller type size
double->float->long->int->char->short->byte
Code Example
Widening Casting - Smaller to Larger- Automatic
1 2 3 4 5 6 7 8 9 | |
Narrowing Casting - Larger to Smaller - Manual
1 2 3 4 5 6 | |
float and doubledata type
- The double data type has higher precision than the float data type .
Note
In Java, the double data type provides higher precision than float.
1 2 3 4 5 | |
Real-Life Example
Gross profit margin
1 2 3 4 5 6 7 8 | |
References
Java Type Casting - https://www.w3schools.com/java/java_type_casting.asp