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 int
s 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 long
s. or, safe, affix l
on every literal there. makes intent clear :-)