java - Different resuls when multiplying -


i have following code , output:

public static void main(string[] args) {     long lon = 1000;     lon = lon * 3600;     lon = lon * 24;     lon = lon * 365;      system.out.println("lon:  " + lon);      long lon2 = 1000 * 3600 * 24 * 365;     system.out.println("lon2: " + lon2); } lon:  31536000000 lon2: 1471228928 

i guess kind of overflow occurring lon2, can't seem figure out. result way below long.max_value. idea?

java isn't smart enough guess intent here.

your problem you're multiplying ints overflow occurs. every number in calculation int, result of int. on assignment resulting int converted long, it's late.

so use like

long lon2 = 1000l * 3600 * 24 * 365; 

to make sure whole calculation done in longs. or, safe, affix l on every literal there. makes intent clear :-)


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -