Convert an int to a long and Vice Versa in Java

OK, first is to discuss the difference between an int and a long. A long is basically a longer version of an int. Or in other words, it can be bigger or smaller than int and consumes more memory. The following code shows how you can find the maximum values for these. The long class can hold substantially larger (or smaller) numbers.

System.out.println(Long.MAX_VALUE); // 9223372036854775807
System.out.println(Integer.MAX_VALUE); // 2147483647

So if you have an int object, you should easily be able to convert that to a long and then the same number back to an int.

int x = 10000;
System.out.println(x); // 10000
long y = (long)x;
System.out.println(y); // 10000
int z = (int)y;
System.out.println(z); // 10000

However, let’s say you started with a long with a value that is larger than the max value for an int and then tried to convert it to an int.

long l = Long.MAX_VALUE;
System.out.println(l); // 9223372036854775807
int i = (int)l;
System.out.println(i); // -1

You would get -1. I’m not sure how that makes sense, but it’s what you get, so it’s something to be aware of. However, unless you need to be really careful on memory consumption or performance or have a particular requirement for your code, you should be fine to stay with longs in this case.

2 Responses to “Convert an int to a long and Vice Versa in Java”

  1. It totally makes sense: converting to int just drops the unneeded upper bits from long. Now Long.MAX_VALUE is 01111…111 in binary representation (should be 64 bits, IIRC). I.e. the lower 32 bits are all ones, which happens to be -1 as an int. (All ones is always -1 in 2’s complement.) That’s it.

  2. yes but sometimes no

Leave a Reply