Code Ranch has this question:
28) If we have 256 MB RAM then what is the maximum length of double array we can create? (Ignore the jvm memory occupied and everything
else)Ans:
Integer.MAX_VALUE as the length() method must return correct ‘int’ length.
I’m not sure if I understand the answer which they had provided. From what I know, most implementations uses 64-bit for a double which means we can fit roughly 4 194 304 doubles (minus overhead) in 256 MB RAM.
So how could the maximum length of a double array be 2147483647 in a 256 MB RAM environment ?
Surely the test code below would give us OOM right?:
public class test {
public static void main(String[] args) {
double[] d = new double[java.lang.Integer.MAX_VALUE - 8];
}
}
EDIT: The answer below assumes that the question is asking about the size of array which can be allocated within the 256MB specified in the question. If that isn’t the point of the question, then there is no definitive answer – because the maximum length will entirely depend on how much memory has been allocated to the JVM, how the JVM is able to use the memory etc. We may have 256MB of memory, but run a Sun JVM with -Xmx64M, so have even less than 256MB available.
So either the question is bad, or the answer is wrong – or quite possibly both.
The Code Ranch answer is definitely incorrect: 256MB is 28 * 220 bytes – i.e. 228 bytes. Each
doublevalue takes 8 bytes, so even leaving aside any overhead for the object and the length, the maximum number ofdoublevalues you can store in 256MB is 223.Integer.MAX_VALUEis 231 – 1, which is clearly much bigger.(It’s not a matter of “most implementations” using 64 bits for
double, by the way – it’s required by the spec.)So yes, your test code would indeed give an OOM if you only had 256MB of memory available.
Given that some of the questions on that page don’t even have answers, this answer is definitely incorrect, and others are badly written, I would just ignore the page completely.