Reputation: 26374
I understand that "2.5" is automatically a double, and to make it a float, I need to do "2.5F" (or should the F be lowercase?), and that I should use a float, say, if I had a constant that only ever needed 2 decimal spaces (like "0.08F" for Ontario PST tax), but I'm not sure whether "12" is an int or a long, but I know "12L" is a long, but "long l = 12" and "long l = 12L" seem to compile to the same thing, and I use long's if I want maximum non-floating point precision, and int if I know I won't need beyond int's limits.
Please correct me if there's something there that isn't right, and answer the quesions I have.
Upvotes: 3
Views: 36315
Reputation: 308021
Note that while int
literals will be auto-widened to long
when assigning to a long
variable, you will need to use an explicit long
literal when expressing a value that is greater than Integer.MAX_VALUE
(2147483647) or less than Integer.MIN_VALUE
(-2147483648):
long x1 = 12; //OK
long x2 = 2147483648; // not OK! That's not a valid int literal
long x3 = 2147483648L; // OK
Upvotes: 3
Reputation: 91871
12 as a constant in java is an int.
The reason long l = 12 compiles is that it is automatically widened to a long.
EDIT: Regarding your comment, there is nothing wrong with automatic widening, use whatever makes your code clearer, but just be aware of what is going on when you do math on primitives. For example:
int i = 1213;
long l = 112321321L * i;
The long will have a very different value if you don't explicitly put that first number as a long because Java will treat it as integer math, and cause an overflow.
Upvotes: 14
Reputation: 39485
It doesn't make a difference if you use lower or upper case when declaring your float
s .
...like "0.08F" for Ontario PST tax
If you are using these fields for currency, you should consider using BigDecimal
instead. See this explanation and its related links from Sun for more detail.
Upvotes: 7
Reputation: 405745
First, 12 is an int
. Since you didn't specify a type, the compiler assumes int
, just as it assumes double
when you don't specify a type for 2.5.
The assignment
long x = 12;
compiles just fine because there is no loss of precision when the compiler implicitly upcasts the literal int
value 12 to a long
.
I always try to use uppercase type specifiers like 2.5F and 12L, simply because they're easier to read. 1 and l look much the same in the monospaced font that I prefer.
Upvotes: 3