Type casting in Java refers to the process of converting a value from one data type to another. It is essential because Java is a strongly typed language, meaning that variables must have a declared type, and operations between different data types often require explicit conversion.
Implicit vs. Explicit Casting: Implicit casting (widening) occurs when a smaller data type is automatically converted into a larger data type. Explicit casting (narrowing) involves manually converting a larger data type into a smaller one, and it may result in data loss.
In Java, you can cast between primitive data types. There are two main types of casting:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}