java multiplying two numbers giving a negative

on
Hello,

I get a negative number (-838967296) when I  run the below Java statement.  When I use a calculator I get a positive.  I'm expecting a positive, why is it negative?  Thanks!

long test1 = 40 * 86400000;
Comment
Watch Question

Do more with

EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
try
long test1 = 40 * 86400000L;

Commented:
If that doesn't work, which is should try
long test1 = 86400000;
test1 *= 40;

Commented:
double test1 = 40 * 8640000;
try this

Commented:
As to why you are getting a negative number, the largest value of a java.lang.Integer object is 2^31 -1 or 2147483647. As you certainly know by now, 86400000 * 40 = 3456000000.

When java tries to generate that number using a scale that only goes up to 2147483647 and only goes down to -2^31 or -2147483648, it first goes as high as it can go, then it turns around and heads back down, past zero and all the way down to 2(2147483648) - 3456000000 = -838967296.

A java.lang.Long object has a max value of 2^64, which gives you quite enough room for a puny sum like 3456000000. You can indicate that you want the answer to be treated as a long by putting an l after any of the factors. That is, java will give the answer in the largest Number type of all the elements in an expression.

So,
86400000l * 40
and
86400000 * 40l
will both give you the correct answer.

Do more with