3

I'm curious to know how Integer and Integer Array are stored on the stack/heap in java, is there a link someone could point me to? Or could someone explain it to me please.

Update 1: and how does this affect the way an integer and an integer array are passed as arguments to methods in Java.

Thank You

3 Answers 3

1

Whenever you declare a variable within a local scope(a method) it gets put on the stack.

That is: Type myVariable will push space for a new variable onto that methods stack frame, but it's not usable yet as it's uninitialized.

When you assign a value to the variable, that value is put into the reserved space on the stack.

Now here's the tricky part. If the type is primitive, the value contains the value you assigned. For example, int a = 55 will literally put the value 55 into that space.
However, if the type is non primitive, that is some subclass of Object, then the value put onto the stack is actually a memory address. This memory address points to a place on the heap, which is where the actual Object is stored.

The object is put into the heap on creation.

An Example

private void myMethod()
{
    Object myObject = new Object();
}

We're declaring a variable, so we get space on the stack frame. The type is an Object, so this value is going to be a pointer to the space on the heap that was allocated when the Object was created.

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

Comments

0

Variables contains only references to this objects and this references stored in stack in case of local variables, but data of objects the point to stored in heap.

You can read more, for example, here: link

enter image description here

Comments

0

method variables are stored in Stack. Objects , in the other hand are stored in the Heap as the image below demonstrates it. That's why if you get StackOverFlowException, that means you have declared too many variables in a method or you are calling too many methods in a recursive call. And if you get Java Heap Space Error, that means you are creating more objects than you do. For Stack and Heap explanation, I recommend this link

enter image description here

Comments

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.