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.
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); } }
Long: 878 Integer: 878
Let us see another example, wherein we are converting double to long using Narrowing Conversion.
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); } }
Double: 299.89 Long: 299