Learn Java Typecast through simple programs

Hi friend,

This blog will help to better understanding of typecasting of datatypes in Java.

PROGRAM:

public class TypeCasting {
public static void main(String[] args) {
int a = 140;
byte b =(byte) a;
System.out.println(b);
}
}

OUTPUT :
-116

EXPLANATION:
This type of type casting will have loss of data. Lets see how 140 changes into -116 by simple binary calculation.

140 decimal value convert into binary number of 16 bits

integer – 16 bits value of 140 is 0000000010001100
byte – 8 bits value of 140 is 10001100

[1] 000110 – first digit represent the sign of number

1 – negative value
0 – positive value

so as per above reference,we will get negative number.

make the binary the 2’s complement
111001
000001
—————
111010

————–

by adding 0 on the last digits – 1110100

convert 1000111 binary into decimal,

116

Now combine the sign and number will be result of -116