Java plus

A confusing piece of code here for you to parse. ;)
int i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);

prints
1
Later discussed on Stack Overflow here.

Comments

  1. So this is just a load of casts applied to unary operators applied ultimately to the 1 at the end of the line.

    i.e. you are casting the -1 to a long, applying the + unary operator to it (so still -1), casting as an int, applying the unary - to it (we now have a value of 1), casting as a char, applying unary + to it and finally casting as a byte before storing as (and implicitly casting to) an int.

    It is simply the presence of the two unary minuses that makes the result 1.

    ReplyDelete
  2. Very nice. This is like something I would come up when I teach Java programming. It is a slick example of confusion in simplicity.

    Ant does a good job describing the behavior.

    ReplyDelete

Post a Comment

Popular posts from this blog

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable

System wide unique nanosecond timestamps