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.
The general form is (target_type) value
Here target type specifies the desired type to convert the specified value.
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); } }
a=94
x=123
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.
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