When you convert an integer to a long, you must convert the integer to a long before any calculations, or it will give the wrong result.
$ cat Test.java
public class Test {
public static void main(String[] args) {
int io = Integer.MAX_VALUE;
int ir = io + 1;
long la = io + 1;
long lb = ((long)io) + 1;
System.out.println("Value of int variable io is: " + io);
System.out.println("Value of int variable ir is: " + ir);
System.out.println("Value of long variable la is: " + la);
System.out.println("Value of long variable lb is: " + lb);
}
}
$ javac Test.java
$ java Test
Value of int variable io is: 2147483647
Value of int variable ir is: -2147483648
Value of long variable la is: -2147483648
Value of long variable lb is: 2147483648
So only the 3rd form (lb) gives the right result.