Java Type Casting:-
Typecasting means that when we assign a one primitive data type to another data type.
There are two types of casting:-
- Implicit Type Casting.
- Explicit Type Casting.
Implicit Type Casting:-
- When we convert smaller data type into a bigger data type.
- It can be done automatically.
- It is also known as “Widening Casting”.
- byte -> short -> char -> int -> long -> float -> double.
Example
class MyClass {
public static void main(String[] args) {
int myInt = 25;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 25
System.out.println(myDouble); // Outputs 25.0
}
}
Explicit Type Casting:-
- When we convert bigger data type into a smaller data type that type of casting is known as explicating typecasting.
- It can be done manually.
- It is also known as “Narrowing Casting”.
- double -> float -> long -> int -> char -> short -> byte.
Example
class MyClass {
public static void main(String[] args) {
double myDouble = 22.71;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Output: 22.71
System.out.println(myInt); // Outputs 22
}
}
Khushi Singh
24-Feb-2025Typecasting in Java systems changes data type from one to another type. We use this process to let variables of different data types hold one type's value. Java includes two approaches to convert data types.
Implicit Typecasting (Widening Casting)
Explicit Typecasting (Narrowing Casting)
1. Implicit Typecasting (Widening Casting)
2. Explicit Typecasting (Narrowing Casting)
Typecasting is essential in Java when working with different data types and performing precise conversions between them.