Java - heap (JVM Memory)

All objects are stored on the heap.

Stack is used for local primitive variables such as ints and doubles. But all objects such as strings, customers or integer objects will be store on the heap.

For the objects on the heap there'll be a pointer to the object which is the variable reference stored on the stack.

Java Memory - The Rules

  • Objects are stored on the heap.
  • Variables are a reference to the object.
  • Local variables are stored on the stack.

Objects are stored physically on the heap. The variable holding the object is just a reference to that object, and the reference if it's held as a local variable will be stored on the stack. Primitives are entirely local variables, there are no objects for these to reference,so these live entirely on the stack.

age is an int type and is stored in the stack.

The name is the reference of the object (String), the name value is stored in the stack, and the object value is stored in the heap.

myList is stored in the stack as the reference of the object List, and the value of the object is stored in the heap.

So when we're in printList the stack will now look like this a new local variable is created called data, and this variable points to the same object as the myList variable, it's a copy of the myList variable and the reference from myList is copied into data.

Because we're now in the printList method, the myList variable is now however out of scope. We can't access it.

Data is just a reference, and the actual object pointed to is unchanged.

The method was working on a copy of the reference to the list, but not a copy of the actual list object itself.

import java.util.ArrayList;
import java.util.List;

public class Heap {
	public static void main(String[] args) {
		List<String> myList = new ArrayList<String>();
		myList.add("one");
		myList.add("two");
		myList.add("three");
		System.out.println(myList);
		printList(myList);
		System.out.println(myList);
	}

	public static void printList(List<String> data) {
		String value = data.get(1);
		data.add("four");
		System.out.println(data);
	}
}

After running, the console outputs the result:

[one, two, three]
[one, two, three, four]
[one, two, three, four]

The object pointed to by reference1 (MyList) and reference2 (data) are the same, so the final printed value is also the same.

DEMO 2

The first address of the new object (that is, the address of the first element) is new, and the addresses of other elements are the same as before.

Question: Why are all objects stored in the heap.

Answer: Because objects need to allocate memory, memory allocation is generally done in the heap.

 

Guess you like

Origin blog.csdn.net/A_bad_horse/article/details/114150757