Type Casting in Java
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion.
There are two types of casting in Java as follows:
- Widening Casting (automatically)
- Narrowing Casting (manually)
1. Widening Casting (automatically)
- This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This involves the conversion of a smaller data type to the larger type size.
- byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (manually)
- if you want to assign a value of larger data type to a smaller data type, you can perform Explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done.
- double -> float -> long -> int -> char -> short -> byte
This Java program demonstrates type casting, which is the process of converting one data type to another.
- In this program, an integer a is initialized with the value 10. Then, a is assigned to a double variable b, which is automatically converted to a double because b is a double data type.
- Next, a double variable d is initialized with the value 25.5385. The value of d is then cast to an integer using the (int) operator and stored in an integer variable c. When casting a double to an integer, the decimal portion is truncated, resulting in a loss of precision.
- Finally, the values of a, b, d, and c are printed using the System.out.println() method.
Source Code
//04 Type Casting in Java
/*
Widening Casting
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting
double -> float -> long -> int -> char -> short -> byte
*/
import java.lang.*;
class casting
{
public static void main(String args[])
{
int a=10;
double b=a,d=25.5385;
int c=(int)d;
System.out.println("Int : "+a);
System.out.println("Double : "+b);
System.out.println("Double : "+d);
System.out.println("Int : "+c);
}
}
Output
Int : 10
Double : 10.0
Double : 25.5385
Int : 25
To download raw file
Click Here