Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (19k points)
What is the maximum number of elements that an array in Java can contain?

1 Answer

0 votes
by (33.1k points)

You can check it by using Integer.MAX_VALUE - 5.

public class Foo {

  public static void main(String[] args) {

    Object[] arr = new Object[Integer.MAX_VALUE - 4];

  }

}

It will throw an exception saying:

Exception in thread "main" java.lang.OutOfMemoryError:

  Requested array size exceeds VM limit

Hope this answer helps you!

Related questions

0 votes
1 answer
asked Sep 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 15, 2021 in Java by Jake (7k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...