Java reference mechanism (stack and heap)

I had the opportunity to explain the Java reference mechanism to my juniors using the stack area and Java heap area. I remember being confused about Java references when I didn't know the relationship between these areas. It's a good opportunity, so I'll summarize it in an article.

Mechanism to realize Java reference

The JVM has a stack area and a Java heap area to realize Java reference. Java references are realized by these two areas.

Area name Overview
Stack area It mainly holds reference information to the heap area. It also holds the value of the primitive type.
JAVA heap area The actual value of the object is kept in this memory.

Differences in how objects and primitive type values are retained

Java objects (Class, array, etc.) have heap area reference information in the stack area. The actual value is stored in the heap area. オブジェクトの参照イメージ

Primitive types have different memory management than objects. When you create a variable of primitive type, the value is held in the stack area.

Behavior when passing to method arguments

When passing an object or primitive type variable to a method argument The contents of the stack area are copied to another stack area. 引数へ渡した時の挙動.png In the above case, the reference of argA is the same as the variable a. Changing the referenced value inside method1 also affects the variable a.

Source code sample

In order to confirm that the contents described so far are correct, we will explain by comparing the source code with the output result.

Example 1

Source code


package test;

class Class1 {
	String id;
	int value;
}

public class Test {
	public static void main(String[] args) {

		Class1 a = new Class1();
		a.id = "ID1";
		a.value = 1;

		//Operation [1]
		Class1 b = a;
		//Operation [2]
		b.id = "ID2";
		b.value = 2;

		//Operation [3]
		b = null;
		//What is the value output here?
		System.out.println("id:" + a.id);
		System.out.println("value:" + a.value);
	}
}

[Operation details] 例1.png

By operation [2], the value of the reference destination of variable a is also rewritten. Operation [3] deletes the reference to variable b, but it does not affect variable a with a different stack. Therefore, the output contents are as follows.

Output result


id:ID2
value:2

Example 2

Source code


package test;

class Class1 {
	String id;
	int value;
}

public class Test {
	public static void main(String[] args) {

		Class1 a = new Class1();
		a.id = "ID1";
		a.value = 1;

		//Operation [1]
		method1(a);
		//What is the value output here?
		System.out.println("id:" + a.id);
		System.out.println("value:" + a.value);
	}

	private static void method1(Class1 argA) {
		//Operation [2]
		argA.id = "ID2";
		argA.value = 2;
	}
}

[Operation details] 例2.png By operation [2], the value of the reference destination of variable a is also rewritten. Therefore, the output contents are as follows.

Output result


id:ID2
value:2

Example 3

Source code


package test;

class Class1 {
	String id;
	int value;
}

public class Test {
	public static void main(String[] args) {

		Class1 a = new Class1();
		a.id = "ID1";
		a.value = 1;

		//Operation [1]
		method1(a);
		//What is the value output here?
		System.out.println("1st time =========");
		System.out.println("id:" + a.id);
		System.out.println("value:" + a.value);

		//Operation [2]
		method2(a);
		//What is the value output here?
		System.out.println("Second time =========");
		System.out.println("id:" + a.id);
		System.out.println("value:" + a.value);
	}

	private static void method1(Class1 argA) {
		argA = null;
	}

	private static void method2(Class1 argA) {
		argA = new Class1();
		argA.id = "ID2";
		argA.value = 2;
	}
}

[Operation details] As in Example 2, we are passing the variable a as a method argument. The method of operation [1] assigns null and deletes the reference of argA, but it does not affect the variable a with a different stack. Since the method of operation [2] is new to Class1, the reference destination has changed to the variable a. Setting the id and value values after the reference has changed does not affect the variable a. Therefore, the output contents are as follows.

Output result


1st time =========
id:ID1
value:1
Second time =========
id:ID1
value:1

Example 4

Source code


package test;

public class Test {
	public static void main(String[] args) {

		int a = 1;

		//Operation [1]
		int b = a;
		//Operation [2]
		b = 99;

		//What is the value output here?
		System.out.println("1st time =========");
		System.out.println("a:" + a);
		System.out.println("b:" + b);

		//Operation [3]
		method1(a);

		//What is the value output here?
		System.out.println("Second time =========");
		System.out.println("a:" + a);
	}

	private static void method1(int argA) {
		//Operation [4]
		argA = 99;
	}
}

[Operation details] スクリーンショット 2020-06-02 0.58.52.png Each primitive type variable holds its value in the stack area independently. Each operation does not affect another variable. Therefore, the output contents are as follows.

Output result


1st time =========
a:1
b:99
Second time =========
a:1

Example 5

Source code


package test;

public class Test {
	public static void main(String[] args) {

		int a = 0;

		//Operation [1]
		int[] b = {a};

		//Operation [2]
		method1(b);

		//What is the value output here?
		System.out.println("a:" + a);
		System.out.println("b[0]:" + b[0]);
	}

	private static void method1(int[] argB) {
		//Operation [3]
		argB[0] = 99;
	}
}

[Operation details] 例5.png Even if it is a primitive type, if you keep it as an array, its value will be saved in the heap area. If you change the array argB in operation [3], it will affect the array b that has the same reference destination. Therefore, the output contents are as follows.

Output result


a:0
b[0]:99

Recommended Posts

Java reference mechanism (stack and heap)
[Java] Stack area and static area
Java pass by value and pass by reference
About Java primitive types and reference types
Java basic data types and reference types
java core: HotSpot compiler and C heap
[Java] Calculation mechanism, operators and type conversion
Page number logic and reference code (java)
Java and JavaScript
XXE and Java
java8 method reference
JAVA reference materials
My Java reference
[Java] Filter stack traces
Getters and setters (Java)
[Java] Thread and Runnable
Java true and false
Organize Java GC mechanism
[Java] String comparison and && and ||
Java --Serialization and Deserialization
[Java] Arguments and parameters
About Java basic data types and reference type memory
timedatectl and Java TimeZone
[Java] Branch and repeat
[Java] Variables and types
java (classes and instances)
[Java] Overload and override
Solving in Ruby, Perl and Java AtCoder ABC 113 C Reference
[Java] Difference between assignment of basic type variable and assignment of reference type variable
[Java] Difference between Stack Overflow Error and Out Of Memory Error
Study Java # 2 (\ mark and operator)
[Java] Integer wrapper class reference
Java version 8 and later features
Basic data type and reference type
Java VB.net service reference halfway
[Java] Difference between == and equals
Pony and reference capability closure
Command mechanism and management tools
[Java] Generics classes and generics methods
Java programming (variables and data)
Java encryption and decryption PDF
Java and Iterator Part 1 External Iterator
Java if and switch statements
Java class definition and instantiation
Apache Hadoop and Java 9 (Part 1)
[Java] About String and StringBuilder
[Java] HashCode and equals overrides
☾ Java / Iterative statement and iterative control statement
Java methods and method overloads
java Generics T and? Difference
Advantages and disadvantages of Java
java (conditional branching and repetition)
About Java Packages and imports
Log Java NullPointerException stack trace
[Java] Upload images and base64
C # and Java Overrides Story
Java abstract methods and classes
Java while and for statements
Java encapsulation and getters and setters
Mechanism and characteristics of Collection implementation class often used in Java