File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Array Maximum Size? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Maximum Size?" Watch "Array Maximum Size?" New topic

Array Maximum Size?

Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191

Does anyone know if java places a maximum on the number of elements an array can potentially have?

[ June 02, 2007: Message edited by: Sam Bluesman ]

Moosey knows best
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

see here

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

Hmmmm... using the example, in the topic, that Fred referenced. It looks like there is a (slightly below) 2 gigabyte size limit for integer arrays.

For example, when I try this...

int[] j = new int[Integer.MAX_VALUE/4];

I get an out of memory condition. However, when I do this...

It works fine, even though this second case allocates more memory.

BTW, I used a "-Xmx20g" switch for the heap, so the out of memory condition is not due to the heap size.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Pravin Jain
Ranch Hand

Joined: May 20, 2007
Posts: 60
BTW there are switches when you start java to specify thay you need more
memory. eg. java -Xms<size> <main-class>

The Zen of Java Programming.
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

After playing around for a bit, it looks like the maximum array size is slightly less than 2 gigabytes -- for all array types. I can have almost twice as many elements of shorts than ints, twice as many elements of bytes than shorts, etc.

I don't have the exact number for elements, but it's close enough. And again, I used a very large heap, so the out of memory condition is not an out of heap memory condition.

I agree. Here's the link:
subject: Array Maximum Size?
It's not a secret anymore!