1 Stack And Heap Flashcards

Points to remember

1
Q

Where are local variables and Objects kept?

A
  1. Local variables are always kept on the stack. Objects are always stored in the heap
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Stack Semantics (threads)

A

JVM may have several threads. Each thread is given a fixed amount of stack space that is dedicated completely and exclusively to that thread. No one but that thread can access its stack space. This is called ”stack semantics”. A thread accesses its stack space by creating and using variables. There is no other special way of accessing the stack space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

”heap semantics”

A

Heap space is shared among all threads. Any thread can use space on a heap by creating objects. Since heap space is shared, it is possible for one thread to access objects created by another if it has a reference to that object. This is called ”heap semantics”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Stack snd Heap space

A

Stack space is limited for a program. So if you have a huge chain of method calls where each method creates a lot of temporary variables (recursion is a good example), it is possible to run out of stack space. In Java, the default stack space size is 64KB but it can be changed at the time of executing the program using command line option -Xss . Heap space is unlimited from the program’s perspective. It is limited only by the amount of space available on your machine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which variables are stored in the stack space?

A

Only temporary variables i.e. variable created in a method (also known as local variables and automatic variables) are created on the stack space. Everything else is created on the heap space. If you have any doubt, ask yourself this question -is this a temporary variable created in a method? Yes? Then it is created on the stack. No? Then it is on the heap. Actual objects are ALWAYS created on the heap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When a method is invoked by a thread, it uses………..to keep its temporary variables.

A

When a method is invoked by a thread, it uses the thread’s stack space to keep its temporary variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which variables are removed and from where when a method ends?

A

Variables added to the stack space by a method are removed from the stack when that method ends. Everything else created by a method is left on the heap even after the method ends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly