3
int x;
int y=10;

What type of memory is allocated in Java? I heard that everything in Java is allocated dynamic memory. That is true for objects, but does the same rule follow for primitive data types also (like int, float, etc.)?

2
  • I'm more used to terminology of on "the stack" and "the heap" Commented Oct 14, 2013 at 13:57
  • 1
    Once you get the answer you are looking for, you have to select the answer that you think was best as accepted. Commented Oct 14, 2013 at 19:17

6 Answers 6

7

In one line it depends on where the variable is declared.

Local variables (variables declared in method) are stored on the stack while instance and static variables are stored on the heap.*

NOTE: Type of the variable does not matter.

class A{
  private int a = 10;  ---> Will be allocated in heap

  public void method(){
     int b = 4; ----> Will be allocated in stack
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

primitive variables and function calls are stored in the stack. objects are stored in the heap.

1 Comment

that clarifies my doubt...nice
1
  1. The JVM stack stores local variables.
  2. All class instances and arrays are allocated on the JVM heap.
  3. The Method area stores per class structure
  4. The runtime constants pool stores constants

Comments

0

Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.

Read more: http://javarevisited.blogspot.com/2013/01/difference-between-stack-and-heap-java.html#ixzz2hhlHV13c

Comments

0

The stack is where memory is allocated to primitives, and where local variables are stored; also references are passed around on the stack.

The heap is where memory is allocated for objects, which in turn is referred to as heap memory. Static variables are stored on the heap along with instance variables.

Comments

0

This is the best article I ever read about java memory https://blog.codecentric.de/en/2010/01/the-java-memory-architecture-1-act/ - you should that a look how its managed. Also there is another post regarding to this topic Memory allocation for primitive and reference variables

And, as answer to your question: Local variables are stored on the stack while instance and static variables are stored on the heap.

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.