In Java, typecasting between different data types plays a very important role, but it can also lead to unexpected errors, especially when we have to deal with signed and unsigned types. In this article, we will look at a situation where a signed byte is cast to an unsigned char, and then perform a few more typecasts.
Key feature of Java Chained Casting: Chained typecasting refers to the process of converting a value from one data type to another multiple times in sequence.
Problem: We need to find the output of the following Java program.
public class Geeks{
public static void main(String[] args) {
System.out.println((int) (char) (byte) -1);
}
}
This program is tricky because it involves multiple typecasts. Let's try to understand why the output is different from what we might think.
Step-by-Step Execution of Chained Typecasting
Let's now understand the problem step by step.
Step 1: Initial Value
The program begins with the int value -1. An int is a 32-bit signed integer. In two's complement, -1 is represented as:
11111111 11111111 11111111 11111111
Note: -1 in binary is a series of 32 1 bits.
Step 2: Casting from int to byte
In Java, casting from int to byte is known a narrowing primitive conversion, It simply means Java takes the least 8 significant bits and discard the rest. When casting -1 (represented by 0xFFFFFFFF) to byte and it only keeps the last 8 bits:
(byte) -1 -> 0xFF -> 11111111 (8 bits, which is `-1` in two's complement form)
Note: After casting the value is still -1, but now it's a byte (8 bits).
Step 3: Casting from byte to char
This step is tricky because a byte can be negative and a char is always positive. When we do casting from byte to char, Java first converts the byte to an int and then the int value get converted to char. Foe value -1 it becomes 0xFFFFFFFF (32-bit int), and when converting that int to a char, it only keeps the last 16 bits, turning into 0xFFFF, which is 65535.
(char) -1 -> 0xFFFF -> 65535
Step 4: Casting from char to int
The final cast is from char to int, which means the value is being converted to a larger type. int can hold larger values than char that why the value stays the same. So, the value 65535 remains unchanged when it’s cast to int.