how to cast long value to int
This is just memo about how to cast long value to int.
From JavaSE8 you can use Math.toIntExact to avoid overflows while you do not know.
Sample.java
public class Sample { public static void main(String... args) { Sample sample = new Sample(); sample.cast(); sample.intExact(); } void cast() { System.out.println("----- cast -----"); int i; long l = Long.MAX_VALUE; i = (int) l; System.out.println(String.format("i=%d", i)); System.out.println(String.format("l=%d", l)); } void intExact() { System.out.println("----- intExact -----"); int i; long l = Long.MAX_VALUE; i = Math.toIntExact(l); // <--- This method was added from JavaSE8 System.out.println(String.format("i=%d", i)); System.out.println(String.format("l=%d", l)); } }
The result
The following result shows the difference between cast and Math.toIntExact.