Type Conversion and Casting

If the two types are compatible, then Java will perform the conversion automatically. For example, assign an int value to a long variable.

For incompatible types we must use a cast. Casting is an explicit conversion between incompatible types.

Java's Automatic Conversions

An automatic type conversion will be used if the following two conditions are met:

  1. The two types are compatible.
  2. The destination type is larger than the source type.

int type is always large enough to hold all valid byte values, so an automatic type conversion takes place.



public class Main {
  public static void main(String[] argv) {
    byte b = 10;
    int i = 0;

    i = b;
    System.out.println("b is " + b);
    System.out.println("i is " + i);
  }
}

The output:


b is 10
i is 10

For widening conversions, integer and floating-point types are compatible with each other.


public class Main {
  public static void main(String[] argv) {
    int i = 1234;
    float f;

    f = i;

    System.out.println("i is " + i);
    System.out.println("f is " + f);
  }
}

The output:


i is 1234
f is 1234.0

The numeric types are not compatible with char or boolean


public class Main{
   public static void main(String[] argv){
      char ch = 'a';
      int num = 99;
      ch = num ;
    }
}

Compiling the code above will generate the following error message.

char and boolean are not compatible with each other.


public class Main {
  public static void main(String[] argv) {
    char ch = 'a';
    int num = 99;
    ch = num;
  }
}

Compiling the code above will generate the following error message.


D:\>javac Main.java
Main.java:5: possible loss of precision
found   : int
required: char
    ch = num;
         ^
1 error

Java performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, or long.


public class Main {
  public static void main(String[] argv) {
    byte b = 1;
  }
}

But you cannot store a value out of the byte scope


public class Main{
   public static void main(String[] argv){
      byte b = 11111;
    }
}

When compiling, it generates the following error message:


D:\>javac Main.java
Main.java:3: possible loss of precision
found   : int
required: byte
      byte b = 11111;
               ^
1 error
Home 
  Java Book 
    Language Basics  

Type Casting:
  1. Type Conversion and Casting
  2. Casting Incompatible Types
  3. Automatic Type Promotion in Expressions
  4. The Type Promotion Rules