LucasSeveryn
LucasSeveryn

Reputation: 6272

Java (Stack&Heap) - what happens memory wise in this simple example

Anyone could explain what happens memory wise (Stack & Heap) in this example? If I understand it correctly, java stores objects on the heap, so i1 will be on the heap... same with string? But what about i2, considering it is a class field declaration.

public ExampleClass {
   Integer i1=new Integer(1);
   int i2 = 2;
   String str = "abc";
}

Upvotes: 0

Views: 732

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533820

All the initialised values are set in the constructor. While in the constructor, the references are placed on the stack and then the fields on the heap. Once the constructor returns, the reference to the object itself is still on the stack, but all the fields are only on the heap.

Upvotes: 0

Stanislav Levental
Stanislav Levental

Reputation: 2235

public ExampleClass {
   Integer i1=new Integer(1); //heap
   int i2 = 2; //heap
   String str = "abc"; //permGen
}

In stack stores only local instances/primitives available only to one thread, heap is a shared place (available to any number of threads), permGen is an another part of java memory used to store interned string and loaded classes.

Upvotes: 0

Dave
Dave

Reputation: 5173

Nothing happens until you have some code like new ExampleClass(). Once you do that, a new object is allocated on the heap. Included in that will be references to i1, i2, and str. I'm guessing that since you're not in a method, that i2 will be automatically converted behind the scenes to the equivalent of Integer i2 = new Integer(0). All 3 of these references will be pointing to objects also allocated on the heap. Note that strings are immutable so if there is already a String with the value "abc", then the reference may point to that.

Upvotes: 0

korifey
korifey

Reputation: 3519

Very concise: Stack: [i1-addr, 2, str-addr] Heap : [i1-addr : 1, str-addr : 'a','b','c']. For heap I use notation [addres: value]. Of course, heap apart of value heap contains some object information (e.g. link to .class object) also.

Upvotes: 0

Jon Egeland
Jon Egeland

Reputation: 12623

All of them are stored in the heap.

As the SO tag says:

The heap is process memory set aside for dynamic allocation.

So any variable will be placed on the heap.

However, any primitive types (int, float, etc) will be stored on the stack **Only if they are allocated locally inside a method).

Look here for more info.

Upvotes: 1

Related Questions