The Narrowing Conversion : Data Type Conversion « Data Type « Java Tutorial






The narrowing conversion occurs from a type to a different type that has a smaller size, such as from a long (64 bits) to an int (32 bits).

In general, the narrowing primitive conversion can occur in these cases:

  1. short to byte or char
  2. char to byte or short
  3. int to byte, short, or char
  4. long to byte, short, or char
  5. float to byte, short, char, int, or long
  6. double to byte, short, char, int, long, or float
  1. The narrowing primitive conversion must be explicit.
  2. You need to specify the target type in parentheses.
public class MainClass {

  public static void main(String[] args) {
    long a = 10;
    int b = (int) a; // narrowing conversion

    System.out.println(a);
    System.out.println(b);
  }

}








2.16.Data Type Conversion
2.16.1.The Widening Conversion
2.16.2.The Narrowing Conversion
2.16.3.Narrowing conversion with information loss
2.16.4.An automatic type conversion
2.16.5.Casting Incompatible Types
2.16.6.Pass a string to the Integer class constructor and call the intValue()
2.16.7.Use toString method of Integer class to conver Integer into String.
2.16.8.Declaring Checked Exceptions
2.16.9.Automatic Type Promotion in Expressions
2.16.10.Convert byte array to Integer and Long
2.16.11.Class with methods for type conversion
2.16.12.Data type conversion
2.16.13.Convert primitive back and forth