Narrowing Conversion in Java



Narrowing conversion is needed when you convert from a larger size type to a smaller size. This is for incompatible data types, wherein automatic conversions cannot be done.

Let us see an example wherein we are converting long to integer using Narrowing Conversion.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       long longVal = 878;
       int intVal = (int) longVal;
       System.out.println("Long: "+longVal);
       System.out.println("Integer: "+intVal);
    }
}

Output

Long: 878
Integer: 878

Let us see another example, wherein we are converting double to long using Narrowing Conversion.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       double doubleVal = 299.89;
       long longVal = (long)doubleVal;
       System.out.println("Double: "+doubleVal);
       System.out.println("Long: "+longVal);
    }
}

Output

Double: 299.89
Long: 299
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements