Java Conversions and Promotions

Java Programming Java8Java Technologies Object Oriented Programming

We can convert one data types into another data type using casting. 

Narrowing Conversion

Narrowing refers to passing a higher size data type like int to a lower size data type like short. It may lead to data loss. Following program output will be 44.

public class MyFirstJavaProgram {
   public static void main(String []args) {
      int a = 300;
      byte b = (byte)a; // narrowing
      System.out.println(b);
   }
}

Widening/Promotion Conversion

Widening refers to passing a lower size data type like int to a higher size data type like long. 

public class MyFirstJavaProgram {
   public static void main(String []args) {
      int a = 300;
      long b = a;
      System.out.println(b);
   }
}
raja
Published on 22-Jan-2018 10:20:26
Advertisements