generally, in java new keyword is used to make an array but this is also a way to do it so I am curious where would this array be stored in java would it be in a stack or in heap memory
3 Answers
As explained in the comments:
int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Is syntactic sugar for
int[][][] arr = new int[][][] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
In both cases, the variable arr is allocated on the stack (if it is a local variable); but the actual array object which arr references is allocated on the heap.
Comments
Array is an object so
Variable + pointer goes in stack
Actual value goes in heap
4 Comments
Konrad Rudolph
“Variable + pointer goes in stack” — this makes it sound like there are two things on the stack. However, there’s only one object on the stack.
JoshiRaez
Is actually two entities. The variable name is stored in memory in the map for the variables inside the context. That variable, later, has a value associated, which is stored in another word (aka, 32/64 byte block) So yeah, is both
Konrad Rudolph
That is incredibly misleading, bordering on wrong. Local variable names are generally not preserved by the Java compiler. They can be made available separately, but then they form part of the debug information. The stack, on which the pointer sits, has no variable names. There’s only one object, the memory address itself, stored in a 64 bit word on x64 architectures. Having more than that would be unnecessary and wasteful.
JoshiRaez
You are right, I just checked this out. I might have been mistaken with another language. Sorry I thought it was |STACK| VarDict[arr] -> arrInHeapLocation -> ///// |HEAP| arrayValue But there is no varDict in java it seems. It gets removed in compile time and the only thing left is the arrayValueLocation pointer
new int[][][]in this case, but that's really what you're doing: creating a new object. It's on the heap.int[][][] arr = new int[][][] { ... }andint[][][] arr = { ... }are identical.