Numeric Literals Teaser

1 AM February 25, 2005

Question: What are the largest integer and long literals allowed by the Java compiler? Bonus points for explaining what is odd about them, and a possible reason that the Java design team allowed this seeming inconsistency.

PS: There are two answers, either of which I would consider correct.

By alang | # | Comments (4)
(Posted to javablogs and Java)

Comments

At 02:51, 25 Feb 2005 Michael Chermside wrote:

==== SPOILERS ====

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Fortunately, Java has half-way decent docs available online:
http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282

"The largest decimal literal of type int is 2147483648 (2^31). All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear, but the literal 2147483648 may appear only as the operand of the unary negation operator -."

(and likewise for longs).

To me, that seems quite sensible. Did you have anything else in mind when asking the question?

(#)
At 04:07, 25 Feb 2005 Alan Green wrote:

Yep. That's one correct answer, but I notice you didn't go for bonus points :(

(#)
At 18:12, 28 Feb 2005 Cameron wrote:

Try it in hex ;-)

(Yes, I once wrote a Java compiler.)

(#)
At 19:36, 28 Feb 2005 Alan Green wrote:

And that's the other one. Java allows hex and octal literals up to (2^32 - 1 = 0xffffffff).

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green