Widening and Narrowing Primitive Conversions in Java

We have the following numeric primitive types:

Screen Shot 2018-01-21 at 11.27.08 AM

Apart of the above, we have the non numeric primitive type “char” : 16 bits and unsigned, so that it may represent Unicode characters.

For boolean types there is not a range; a boolean can be only true or false.A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion. we can only assign a boolean value to another boolean.

Widening primitive conversion

For the primitive data types, the value of a narrower data type can be converted to a value of a wider data type. This is called a widening primitive conversion.

Screen Shot 2018-01-21 at 11.03.12 AM

long l = 10; // Widening primitive conversion: long <— int

An implicit cast happens when you’re doing a widening conversion.

Narrowing primitive conversion

Converting from a wider primitive type to a narrower primitive type is called a narrowing primitive conversion.

float a = 100.001f;
int b = (int)a; // Explicit cast, the float could lose info.

Narrowing primitive conversion requires an explicit cast, where you tell the compiler that you are aware of the danger(“possible loss of precision/information”) and accept full responsibility.

Method Overloading and Primitive Widening 

package com.test;
package com.test;
public class PrimitiveMethodOverloading {
public void method(int x) { System.out.print(“int “); }
public void method(long x) { System.out.print(“long “); }
public void method(double x) { System.out.print(“double “); }
public static void main(String[] args) {
PrimitiveMethodOverloading pmo = new PrimitiveMethodOverloading();
byte b = 5; short s = 5; long l = 5; float f = 5.0f;

Output:int int long double

The calls that use byte and the short arguments are implicitly widened to match the version of the method() that takes an int. The call with the long uses the long version of method(), and finally, the call that uses a float is matched to the method that takes a double.

Related Article : Exploring Primitive Data Types in Java

Leave a Reply

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