Java | Wide and Narrow typecast in Java with examples

|
| By Webner

Cast means converting one data type to another data type.

Automatic Type Conversion

Automatic type conversion means programmer doesn’t need to write code for the cast. In Automatic Type Conversion, narrower data type is converted to broader data type automatically by Java. Automatic Type Conversion is also called Widening Conversion (Wide Type Cast).

In Automatic Type Conversion, following conversions can be done automatically:

From byte To short, int, long, float, or double
From short to int, long, float, or double
From int to long, float, or double
From long to float, or double
From float to double
From char to int, long, float or double

Narrow and Wide Type Cast

In Wide Type Cast, a narrower data type is converted to Broader data type. Wide Type Cast is also called Automatic Type Conversion.

Let’s see an example:

public class TypeCastProgram {
public static void main(String[] args) {
short shortVar = 10;
int intVar = shortVar;
int intVar1 = 1000;
float floatVar = intVar1;
System.out.println(intVar);
System.out.println(floatVar);
}
}

The above code sample produces following output:
10
1000.0

In the above example, variable of short data type i.e. shortVar is automatically converted to int data type when we assign shortVar to intVar and data type (int) of
intVar1 is type-casted to float and this code sample does not produce any error.

We can also do explicit Wide Type Cast as shown below:

short shortVar = 50;
short var1 = (short)100;		// Explicit Wide Type Cast
system.out.println(var1);		// print output: 100

In Narrow Type Cast, broader data type is converted to narrower data type explicitly.
Narrow Type Cast is also called Explicit Type Conversion because Narrow Type Cast cannot be done by JVM, programmer has to explicitly changed data type to narrow data type. In this case, loss of data can occur.

In Narrow Type Cast, following conversions can be done by programmer explicitly:

From byte to char
From short to byte, or char
From char to short or byte
From int to short, byte, or char
From long to int, short, byte, or char
From float to long, int, short, byte, or char
From double to float, long, int, short, char or byte

Let’s see an example of narrowing conversion:

If we write sample code as follows:

int var1 = 50;
short var2 = var1;
System.out.println(var2);

The above code will cause error because Java does not allow this type of assignment because larger value held by var1 can not be held by var2 always because var2 is of smaller data type than of var1.

Now, if we write above assignment as follows:

short var2 = (short)var1;

This time it will work.

Leave a Reply

Your email address will not be published. Required fields are marked *