Java - stack

The characteristics of the stack: last in, first out.

Demo 1

public class Main {
	public static void main(String[] args) {
		int value = 7;
		value = calculate(value);
	}

	public static int calculate(int data) {
		int temValue = data + 3;
		int newValue = temValue * 2;
		return newValue;
	}

}

The final result of the above code value is 20.

method

Method running order: main() -> calculate()

Method exit order: calculate() -> main()

Variables ( local local variables )

The execution order of variables in the calculate method: data -> temValue -> newValue

The return order of variables in the calculate method: newValue -> temValue -> data

Demo 2

pass variables by value - possible

main()-localValue is pushed onto the stack, and when calculate() is called, calcValue is a copy of localValue.

calculate-calcValue is pushed onto the stack, the last calculated is calcValue, but the original value localValue has not changed.

Final print result: 5

pass variables by reference - impossible

Java does not support passing values ​​by reference. For objects, Java passes the reference of the object, not the actual value of the object.

For objects passed into methods, the REFERENCE to the object is passed BY VALUE.

Demo 3

Variables of the String type cannot be changed, so the String value "Diane" will be recreated, and the original "Sally" will be garbage collected.

Finally, when the method is exited, cust is released, the reference c points to the object, and the final output is "Diane".

Demo 4

Final modifies c, and c points to the object Customer.

Change the object pointed to by c. At this time, the compiler reports an error, and final does not allow variables to point to another object.

But you can change the value of the object.

The name value is changed to "Susan", but c still points to the same object.

Final Keyword means that a variable can only be assigned once, which means that when the variable in this stack is assigned to an object in the heap, then we can't change which object in the heap this variable points to. 

Demo 5

public class Test01 {
    public static void main(String[] args) {
        User u = new User("John");

        System.out.println(u.getName());
        System.out.println(u.getName());
    }
}
public class User {
    String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        String temp = this.name;
        this.name = "xxx";
        return temp;
    }
}

Print result:

John
xxx

Therefore, the stack frame range can be understood as shown in the figure below.

Guess you like

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