web analytics

Java Type Casting

Java type casting is a way in java that converts a data type into another data type manually or automatically. Manual conversion performed by the programmer and automatic conversion is done by the compiler. In this section, we will describe java type casting.

Types of Java Type Casting

Java type casting is of two types:

Narrowing Type Casting
Widening Type Casting

Narrow Type Casting

Conversion of a larger data type into a smaller one is called narrow type casting. It is also known as explicit conversion or casting down. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Let’s see an example of narrow type casting.

public class MyNarrowTypeCasting
public static void main(String args[])
double d = 203.541;
long l = (long)d; //converting double data type into long data type

int i = (int)l; //converting long data type into int data type
System.out.println("Before conversion from double to int: "+d);
//fractional part will be lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);

In the above example, we have performed the down/narrow java type casting two times. First, we have converted the double type into long data type after that long data type is converted into int type.

Widening Type Casting

Conversion from a lower data type into a higher data type is called widening type casting. It is also called implicit conversion or up casting. It is done automatically. It is safe because there is no chance to lose data. It takes place when:
Both data types must be compatible with each other.
The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between char data type to numeric or Boolean data is not done automatically because the char and Boolean data types are not compatible with each other. Let’s see an example.

public class MyWideningTypeCasting
public static void main(String[] args)
int a = 5;
//automatically converts the integer type into long type
long b = a;
//automatically converts the long type into float type
float c = b;
System.out.println("Before conversion, int value "+a);
System.out.println("After conversion, long value "+b);
System.out.println("After conversion, float value "+c);