Jan 31 2009

Java weirdness

Published by pj at 10:18 pm under java

“In Java, int x = 5; x += 2.5; works (x is now 7), whereas int x = 5; x = x + 2.5; gives a type error.”

The first one to explain this wins a free beer .. ;-)

2 responses so far

2 Responses to “Java weirdness”

  1. alexon 11 Feb 2009 at 7:54 pm

    Compound operators do implicit casting for you –> x +=2.5 so your double is casted to int.

    While arithmetical operation x+2.5 has to result to integer, so you have to explicitly cast to (int)2.5 –> x= x + (int)2.5

    What is says – both statements are not equivalent and can produce different results.
    I agree this is a weird.

  2. pjon 12 Feb 2009 at 3:15 pm

    You, sir, just won a beer!
    Let me know where you live, next time I’m in canada :-)

Trackback URI | Comments RSS

Leave a Reply