There are two types of conversion in Java as:

  1. Implicit conversion
  2. Explicit conversion

Implicit Conversion:

Implicit conversion is also known as automatic conversion. When one type of data is assigned to different type of variable then automatic type conversion will take place if the following conditions are met.

  • both type (source and destination) are compatible.
  • The destination type is larger than the source type.

when these two conditions are met, a widening conversion take place.

For Example:

byte a=100;

int num=a; // a int value is large enough to hold all byte values.

Note:

  • when a large data type hold a small data type variable. then only it is known as implicit conversion.

Explicit Conversion:

As we see implicit conversion is helpful. but it will not fulfill all needs. For example, what if we want to assign a int value to byte variable? then this conversion will not take place automatically, because a byte is smaller than a int. This kind of conversion is also known as narrowing conversion or explicit type conversion.

To make a conversion between two incompatible types, then type casting is used.

Syntax:

(target type) value

Note:

  • here target type denotes the data type of destination.
  • values denotes the value of source type.

For example:

int a;

byte b;

b =(byte) a; // here a int value is converted to the byte value

//program for casting

class conversion{

public static void main(String a[]){

byte b;

int i=257;

double d=323.142;

System.out.println(“int to byte conversion”);

b= (byte) i;

System.out.println(“i =”+ i +” and b=  “+ b);

System.out.println(“double to int conversion”);

i= (int) d;

System.out.println(“d=” +d+” and i =” +i);

System.out.println(“double to byte conversion”);

b=(byte) d;

System.out.println(“d= “+d+” and b= ”  +b);

}

}

Output of this program:

int to byte conversion

i=257 and b=1

double to int conversion

d=323.142 and i=323

double to byte conversion

d=323.142 and b=67

One Reply to “Type Conversion and Casting”

Leave a Reply

Your email address will not be published. Required fields are marked *