Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Type Casting

  • • When one type of value is assigned into another type of variable known as type casting.
  • • Basically java support two type of type casting such as
    1. Implict type casting
    2. Explict type casting
Implict type casting
  • • When the type conversion between two data type is done automatically known as implicit type casting.
  • • Automatic type conversion will take place when
    • • The two types are compatible.
    • • The destination type is larger than source type.
Example
int x;
byte a=50;

Now if we want to assign the value 50 into x then it is done automatically because here byte is the source type and int is the destination type and destination type is larger than source type.

Explicit type casting
  • • When two types are not compatible or the source type is larger than the destination type then we must use a cast.
  • • A cast is simple an explicit type conversion.

The general form is (target_type) value
Here target type specifies the desired type to convert the specified value.

Example
byte a;
int x=350;

if we want to assign the value 350 into a then we write

a=(byte)x;

Let us see a program for better understanding

class ExplicitDemo
{
	public static void main(String args[ ])
	{
		byte a;
		int x=350;
		double d=123.456;
		a=(byte)x;
		System.out.println("a="+a);
		x=(int)d;
		System.out.println("x="+x);
	}
}
Output

a=94
x=123

Type Promotion

Consider the following expressions

byte a= 30;
byte b= 40;
byte c= 120;
int x= a*b/c;

Here the intermediate expression a*b exceeds the range of byte. So to handle this kind of problem java automatically promotes byte into int when evaluating an expression. That means the expression a*b is performed using integers not byte. Hence 1200 is the result of the expression. So 30*40 is legal though a and b are specified as byte type.
Consider the following expressions

byte x= 30;
x= x*5; //error, cannot assign an int to a byte
so, we should use an explicit cast such as
byte x= 30;
x= (byte) x*5;

then we will get the value 150 as result.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext