The Range of Int in Java

Why java int type has valid value in range -2,147,483,648 to 2,147,483,647?

The primary representation of numbers in modern computers is some form of binary representation. It consists of a fixed number of bits that take the values 0 or 1. In Java, an int is specified to use a binary representation with 32 bits.

A 32 bit binary representation can have 2^32 states. (This is a mathematical fact. It can be proven from first principles.)

Consider the mathematical integers from -2^31 to +2^31:

  • There are 2^31 numbers in the range 1 to 2^31 (inclusive)

  • There are 2^31 numbers in the range -1 down to -(2^31) (inclusive)

  • The value zero is not in either of the above ranges.

So counting the numbers from -2^31 to +2^31, we get a total of 2^31 + 2^31 + 1 values. That is 2^32 + 1 which is more values than can be represented in 2^32 states.

What you are suggesting is not mathematically possible.

Java: Equivalent of Python's range(int, int)?

Guava also provides something similar to Python's range:

Range.closed(1, 5).asSet(DiscreteDomains.integers());

You can also implement a fairly simple iterator to do the same sort of thing using Guava's AbstractIterator:

return new AbstractIterator<Integer>() {
int next = getStart();

@Override protected Integer computeNext() {
if (isBeyondEnd(next)) {
return endOfData();
}
Integer result = next;
next = next + getStep();
return result;
}
};

How to get a range of values in Java

You can use a stream to generate the range and collect it to a list

IntStream.range(0, 10)
.collect(Collectors.toList());

Note that the first number is inclusive and the second is exclusive. You can use the rangeClosed method to include the second argument.
http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-

There are other types of streams for other primitives (e.g. see DoubleStream.iterate for example).

Java int vs Integer - different ranges

No. int and Integer have exactly same range.

Your program runs infinitely because when you add 1 to Integer.MAX_VALUE you get numeric overflow and result will be Integer.MIN_VALUE. Which in turn less than Integer.MAX_VALUE.

If this is practical problem, I suggest you to use long and Long instead of int and Integer



Related Topics



Leave a reply



Submit