Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

Multiplication operation in Java is resulting in negative value

Why does the below calculation produce a negative value?

long interval = 0;

interval = ((60000 * 60) * 24) * 30;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Every expression in there is being evaluated (at compile-time, of course; it's a constant) as int * int instead of long * long. The result overflows at some point. So just use L to make all the operand literals long:

interval = ((60000L * 60L) * 24L) * 30L;

Of course you could get away with only making some of the operands longs, but I tend to find it's easier to just change everything.

Having said all of this, if you're looking for "30 days-worth of milliseconds" it would be better to use:

long interval = TimeUnit.DAYS.toMillis(30);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...