Type Conversion and Casting

Assigning a value of one type to a variable of another type is known as Type Casting.

  • Java’s Automatic Conversions
  • When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:


    • The two types are compatible.
    • The destination type is larger than the source type.
  • When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
  • char and boolean are not compatible with each other.


  • Casting Incompatible Types
  • Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type.
  • To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form:

(target-type) value


int a;

byte b;

// ...

b = (byte) a;


The following program demonstrates some type conversions that require casts:

// Demonstrate casts.

class Conversion {

 public static void main(String args[]) {

byte b;

int i = 257;

double d = 323.142;

System.out.println("\nConversion of int to byte.");

b = (byte) i;

System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");

i = (int) d;

System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");

b = (byte) d;

System.out.println("d and b " + d + " " + b);



This program generates the following output:

Conversion of int to byte.

i and b 257 1

Conversion of double to int.

d and i 323.142 323

Conversion of double to byte.

d and b 323.142 67


Automatic Type Promotion in Expressions

char à short à int à long à float à double à long double

  • Example
byte a = 40;

byte b = 50;

byte c = 100;

int d = a * b / c;
  • Another example
byte b = 50;

b = b * 2; // Error! Cannot assign an int to a byte!
  • Solution
byte b = 50;

b = (byte)(b * 2);// which yields the correct value of 100.
Scope and Lifetime of Variables
Java Operators