1

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
  • The syntax allows you to omit new int[][][] in this case, but that's really what you're doing: creating a new object. It's on the heap. Commented Aug 25, 2020 at 10:42
  • @RobertoCaboni The variable may be on the stack, but the array is on the heap. Commented Aug 25, 2020 at 10:45
  • Array initializer syntax is just syntactic sugar. int[][][] arr = new int[][][] { ... } and int[][][] arr = { ... } are identical. Commented Aug 25, 2020 at 10:45

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Array object always store in the heap memory.

Comments

0

Array is an object so

Variable + pointer goes in stack

Actual value goes in heap

4 Comments

“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.
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
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.