Type Conversion and Casting: If you have a experience in a programming language, then you know this thing that it is common to assign a value of one type of variable to another type variable. Java performs type conversion automatically when the two types are compatible. For example, it is always possible to assign a int to a long. But not all types are compatible, therefor all types of conversions are not allowed implicitly. For example, there is a no conversion between double and byte. Still it is possible to obtain conversion between incompatible types.

Java’s Automatic Conversion

When one type of value is assigned to another type of variable, Automatic type conversion is take place. For that need to met the following two conditions:

  • Both types are compatible
  • The destination type is larger than the source type

For example, int type is enough large to hold byte values.

Casting Incompatible Types

All types of automatic conversion is not not possible. if you want to assign an int value to a byte variable this will not perform automatically because a byte is smaller than an int. This type of conversions called a narrowing conversion.

To create a type conversion between incompatible types you must need cast. It has following general form:

(target-type) value here target-type specifies the desired type to convert this value. For example, following example shows cast the int to a byte

int a;
byte b;

b= (byte) a;

Following program shows some Type Conversion and Casting which requires a casting:

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);
}
}

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
Type Conversion and Casting
Type Conversion and Casting

If you want to know about data types used in java then see this article Data Types In Java.

I hope you understand this concept If you have a any doubt then please comment me on below comment box.

Leave a Reply

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

Back to Top