Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible values of int from the smallest to the largest, using Java

Tags:

java

Write a program to print out all possible values of int data type from the smallest to the largest, using Java.

Some notable solutions as of 8th of May 2009, 10:44 GMT:

1) Daniel Lew was the first to post correctly working code.

2) Kris has provided the simplest solution for the given problem.

3) Tom Hawtin - tackline, came up arguably with the most elegant solution.

4) mmyers pointed out that printing is likely to become a bottleneck and can be improved through buffering.

5) Jay's brute force approach is notable since, besides defying the core point of programming, the resulting source code takes about 128 GB and will blow compiler limits.

As a side note I believe that the answers do demonstrate that it could be a good interview question, as long as the emphasis is not on the ability to remember trivia about the data type overflow and its implications (that can be easily spotted during unit testing), or the way of obtaining MAX and MIN limits (can easily be looked up in the documentation) but rather on the analysis of various ways of dealing with the problem.

like image 754
Vlad Gudim Avatar asked May 07 '09 16:05

Vlad Gudim


People also ask

What is the smallest integer value in Java?

The Integer. MIN_VALUE is a constant in the Integer class that represents the minimum or least integer value that can be represented in 32 bits, which is -2147483648, -231. This is the lowest value that any integer variable in Java can hold.

What is the max int value in Java?

The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers?

What happens when 1 is added to the maximum possible value in an int variable?

Overflow in int In numerical terms, it means that after incrementing 1 on Integer. MAX_VALUE (2147483647), the returned value will be -2147483648. In fact you don't need to remember these values and the constants Integer.

How big of a number can an int store?

The INTEGER data type stores whole numbers that range from -2,147,483,647 to 2,147,483,647 for 9 or 10 digits of precision. The number 2,147,483,648 is a reserved value and cannot be used.


1 Answers

class Test {
    public static void main(String[] args) {
        for (int a = Integer.MIN_VALUE; a < Integer.MAX_VALUE; a++) {
            System.out.println(a);
        }
        System.out.println(Integer.MAX_VALUE);
    }
}

Am I hired?

like image 139
Dan Lew Avatar answered Apr 29 '23 13:04

Dan Lew