Casting in Java refers to converting a variable from one data type to another. Java supports both implicit (automatic) and explicit (manual) casting.
Implicit Casting (Automatic)
Implicit casting happens when you assign a value of smaller data type to a larger data type. For example, assigning an int
to a long
:
int smallNumber = 10;
long largeNumber = smallNumber; // implicit casting
Explicit Casting (Manual)
Explicit casting is required when you are assigning a value of larger data type to a smaller data type. For example, assigning a double
to an int
:
double decimalNumber = 10.5;
int wholeNumber = (int) decimalNumber; // explicit casting
Here is a full example, including both implicit and explicit casting, using various data types:
public class DataTypeCasting {
public static void main(String[] args) {
// Implicit Casting
char aChar = 'A'; // size: 16-bit
int aInt = aChar; // size: 32-bit
System.out.println("Implicit Casting: char to int: " + aInt); // 65 (ASCII value of 'A')
long aLong = aInt; // size: 64-bit
System.out.println("Implicit Casting: int to long: " + aLong); // 65
float aFloat = aLong; // size: 32-bit
System.out.println("Implicit Casting: long to float: " + aFloat); // 65.0
double aDouble = aFloat; // size: 64-bit
System.out.println("Implicit Casting: float to double: " + aDouble); // 65.0
// Explicit Casting
aFloat = 65.65f; // size: 32-bit
aLong = (long) aFloat; // size: 64-bit
System.out.println("Explicit Casting: float to long: " + aLong); // 65
aInt = (int) aLong; // size: 32-bit
System.out.println("Explicit Casting: long to int: " + aInt); // 65
aChar = (char) aInt; // size: 16-bit
System.out.println("Explicit Casting: int to char: " + aChar); // A
byte aByte = (byte) aInt; // size: 8-bit
System.out.println("Explicit Casting: int to byte: " + aByte); // 65
}
}
In this example:
- We implicitly cast from
char
toint
tolong
tofloat
todouble
, each being of a larger data type. - We explicitly cast back down from
float
tolong
toint
tochar
and finally tobyte
, each being of a smaller data type.