user3364498
user3364498

Reputation: 489

Integer and Integer Array storage on stack/heap

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

Upvotes: 3

Views: 4387

Answers (3)

Cruncher
Cruncher

Reputation: 7796

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.

Upvotes: 1

javadev
javadev

Reputation: 1669

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

Upvotes: 0

Filipp Voronov
Filipp Voronov

Reputation: 4197

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

Upvotes: 0

Related Questions