-3

Someone kindly clear my doubt on memory management in Java with the below-mentioned scenario.

When we assign value for the primitive data type variable the value will be stored in stack memory. Please do correct me if I understood the concept wrong.

As same like how the memory will allocate when do assign a value of a non-primitive data type as mentioned below.

Integer a = 3;

Will create a memory in stack or heap?

user207421
  • 305,947
  • 44
  • 307
  • 483
Bhuvanesh Waran
  • 593
  • 12
  • 28
  • Either. It depends whether it is method-local or a class member. – user207421 Aug 02 '19 at 06:11
  • Possible duplicate of https://stackoverflow.com/questions/8419860/integer-vs-int-with-regard-to-memory – Ashwani Aug 02 '19 at 06:13
  • What happens when we declare the variable as method-local and class member? Please do clear my doubt on this. @user207421 – Bhuvanesh Waran Aug 02 '19 at 06:16
  • You *can't* declare it as both method-local *and* a class member. One or the other. Make up your mind. But I now see you wrote `Integer` instead of `int`, which means the object is on the heap. I was referring to where the *variable* `a` is located. – user207421 Aug 02 '19 at 06:18
  • Am not saying that I will declare the same variable as class member and method local. Am just asking how memory will allocate when we declare as class member and when we declare as method-local – Bhuvanesh Waran Aug 02 '19 at 06:23
  • If the variable `a` is method-local, it is on the stack. If it is a class member: on the heap. The `Integer` object it refers to is always on the heap. – user207421 Aug 02 '19 at 06:29

1 Answers1

1

The variable a will be either in heap or stack memory depending on what kind of variable it is:

  • method or constructor local variables (including parameters) - on the stack
  • instance variables (aka attributes or fields) - on the heap
  • class variables - on the heap.

(For the sake of completeness, there are couple of obscure cases where a lambda or inner class refers to an effectively final local variable in an enclosing scope. In those cases, a copy of the original variable's contents will be stored on the heap.)

The Integer object that represents the boxed value of 3 will be on the heap.

A copy of the reference to that object is stored in the variable a wherever that happens to be. There may be other copies of that reference elsewhere in the JVM.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216