1

As per my understanding, casts are used to convert a value from one type to another.

I found the following program in the book "Java Puzzlers: Traps, Pitfalls, and Corner Cases" by Joshua Bloch and Neal Gafter

This program uses three casts in succession:

public class Multicast {  
    public static void main(String[] args) {  
      System.out.println((int) (char) (byte) -1);  
  }  
}

I thought it will print -1 but it is printing It prints 65535, but why?

Rob
  • 26,989
  • 16
  • 82
  • 98
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    already answered in great detail http://stackoverflow.com/questions/24635977/why-does-intcharbyte-2-produce-65534-in-java – Ramanlfc Dec 28 '15 at 05:00

2 Answers2

2

Expression: (int) (char) (byte) -1

  1. -1 is of type int
  2. (byte) -1 is a byte with value -1
  3. (char) (byte) -1 first the byte with value -1 is sign extended again to be an 32-bit integer of value -1. This means that all the 32-bit are set to 1 (the two-complement encoding of -1 in 32 bits). Then it is cast to the type char which is an unsigned 16-bit value, so you get 16 bits set to one, which has the value 65535.
  4. (int) (char) (byte) -1 by explicitly casting it again to a 32-bit integer, you make sure that it is printed as a number instead of the character with the codepoint 65535.
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
1

A char in java is an unsigned 16-bit integer. If you cast a negative integer literal like -1 to a char, then the value is interpreted as a positive number; in this case 65535- or Unicode character \uFFBF.

Check this -1 cast with char only,

System.out.println( (char) -1);

If it cast with int or byte type, this returns -1 only.

bNd
  • 7,512
  • 7
  • 39
  • 72