2

While i was writing code for an accounting application , i observed unusual behavior of List in java. After executing below code,

List<String> accountsList = new ArrayList<String>();

    for(int i=0; i< (Integer.MAX_VALUE+2) ;i++){
        accountsList.add("Account #"+i);
    }

    System.out.println("# of accounts in list : "+accountsList.size());

got output as - # of accounts in list : 0 , which was very interesting. Also code ran correctly without throwing any exception. If this is because of value overflow of int, why did not java throw warning/ exception.

Then i modified condition in for loop as, for(int i=0; i< Integer.MAX_VALUE ;i++) and code worked as expected.

Is this behavior has to do anything with Max value of int, as ArrayList can hold values till count of Integer.MAX_VALUE ( accountsList.size() returns value of type int, and int has max value defined).

Dark Knight
  • 8,218
  • 4
  • 39
  • 58
  • 10
    There's a reason it's called `MAX_VALUE`. – Matt Ball Oct 30 '13 at 14:50
  • 3
    `(Integer.MAX_VALUE + 2) == (Integer.MIN_VALUE + 1)` due to integer overflow... There's nothing unusual about your result. – Harald K Oct 30 '13 at 14:50
  • 2
    http://stackoverflow.com/questions/9397475/why-integer-max-value-1-integer-min-value – kosa Oct 30 '13 at 14:51
  • 1
    Which means `0 < (Integer.MAX_VALUE+2)` returns `false` and you get zero iterations on your `for` loop. Put a `System.out.print` in your loop to really see how many times the loop is executed. – nhgrif Oct 30 '13 at 14:51
  • Ok, that i understood. But my concern here is why did not java throw any warning/exception meantime. – Dark Knight Oct 30 '13 at 14:53
  • I thought Java throws exception when integer overflows, no? – user2520968 Oct 30 '13 at 14:55
  • [Relevant question](http://stackoverflow.com/questions/15998008/why-do-integer-datatypes-overflow-silently-rather-than-throwing-exception) for Java behavior during integer overflow. – ajp15243 Oct 30 '13 at 14:56
  • @user2520968 Please read the JLS. – Ingo Oct 30 '13 at 15:26

2 Answers2

3

You try this one

System.out.println((Integer.MAX_VALUE+2));

The output is -2147483647 that is less than 0 so no values will be added to your list.

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

When you try to go above MAX_VALUE, you'll get a large negative number due to overflow. Technically, there is nothing illegal about this code and the compiler/java will not throw a warning/exception before or at run time.

Alex
  • 1,100
  • 1
  • 9
  • 23