views:

2165

answers:

7

Hi all,

It appears that when you type in a number in java, the compiler automatically reads it as an integer, which is why when you type in (long) 6000000000 (not in Integer's range) it will complain that 6000000000 is not an integer. To make it shut up, I had to specify 6000000000L. I just learned about this specification.

Are there other number specifications like for short, byte, float, double? It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it - that is an assumption, correct me if I'm wrong. I would normally search this question myself, but I don't know what this kind of number specification is even called.

Please let me know.

Thanks, jbu

A: 

Yes, you can use f to force float, otherwise it assumes double or int. Also, 0x33234 is hex.

CookieOfFortune
And d is for double (although you can get the same effect by appending .0 to the number).
Michael Myers
A: 

Consider:

long l = -1 >>> 1;

versus

int a = -1;
long l = a >>> 1;

Now you'd expect bother code fragments to give the same value to variable l. So we need expression on int literals to be done as ints.

Tom Hawtin - tackline
+2  A: 

I believe what you want is in this document:

http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html

McWafflestix
I think the third edition would be better: http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10
Michael Myers
Ah, yes, most likely. That one was the first one I found... :-)
McWafflestix
+4  A: 

These are literals and are described in section 3.10 of the Java language spec.

McDowell
+9  A: 

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details.

Simon Nickerson
-1 Always use upper case for suffixes. l can too easily be confused with 1.
starblue
A good point - have updated my answer with the recommendation
Simon Nickerson
+3  A: 
erickson
that would be nice...I've always found that all the casts are really annoying
jbu
A: 

It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it

Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short and byte suffixes would be nice is that it lead to more compact code.

Michael Borgwardt