views:

152

answers:

4
class Main {  
   public static void main (String[] args){  
     long value = 1024 * 1024 * 1024 * 80;  
     System.out.println(Long.MAX_VALUE);  
     System.out.println(value);  
  }  
}

Output is:

9223372036854775807
0

It's correct if long value = 1024 * 1024 * 1024 * 80L;!

+1  A: 

The integer literals are ints. The ints overflow. Use the L suffix.

long value = 1024L * 1024L * 1024L * 80L;

If the data came from variables either case or assign to longs beforehand.

long value = (long)a * (long)b;

long aL = a;
long bL = b;
long value = aL*bL

Strictly speaking you can get away with less suffices, but it's probably better to be clear.

Also not the lowercase l as a suffix can be confused as a 1.

Tom Hawtin - tackline
+12  A: 

In Java, all math is done in the largest data type required to handle all of the current values. So, if you have int * int, it will always do the math as an integer, but int * long is done as a long.

In this case, the 1024*1024*1024*80 is done as an Int, which overflows int.

The "L" of course forces one of the operands to be an Int-64 (long), therefore all the math is done storing the values as a Long, thus no overflow occurs.

Erich
Arithmetic on, say, `short`s isn't done as `short`s, it's done as `int`s.
Tom Hawtin - tackline
Tom- That is very interesting, I'd never known that. I just tested it with two shorts (in C#, but similar action), and it DID do the math as an Integer...It must be just using an Int as the default value for plain numeric types.
Erich
i.e.short x = 0;short y = 0;x = x + y;would give a type mismatch error.
prateek urmaliya
Prateek- It doesn't though, the compiler is smart enough to make the differentiation.
Erich
Prattek: There's a bit of target typing going on there. You can also do `myShort += anotherShort;` but not `myShort = myShort + anotherShort;`. I like aribtrary precision integers...
Tom Hawtin - tackline
Erich: Integer arithmetic without `long` is done as `int`. Floating point arithmetic without `double` is done as `float` (I think I forget what happens you do `long+float`). I still like arbitrary precision arithmetic.
Tom Hawtin - tackline
That actually sounds familiar, and is a pretty reliable rule, it makes sense that would be the way it happens.long+float is done as a double I think, which is why you can do 5/3.0 and have it work.
Erich
+1  A: 

I suspect it's because by default java treats literals as integers, not longs. So, without the L on 80 the multiplication overflows.

developmentalinsanity
+1  A: 

This code:

long value = 1024 * 1024 * 1024 * 80;

multiplies some integers together, converts it to a long and then assigns the result to a variable. The actual multiplication will be done by javac rather than when it runs.

Since int is 32 bits, the value is wrapped and results in a zero.

As you say, using long values in the right hand side will give a result which only wraps if it exceeds 64 bits.

Pete Kirkham