Java parameter when the parameter is changed basic data types (including String) will not affect the rest of the original value or affect

JAVA eight basic data types

Character type char boolean value boolean type byte, short, int, long, float, double
a special type String

Proven eight basic data types and the corresponding type String and packaging are not per se affect the value of the shape parameter values ​​change.

Code

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

class Solution {
	public void test(int a){
		a=2;
	}
	public void test(int[] a){
		a[0]=5;
		a[1]=5;
	}
	public void test(ArrayList a){
		a.clear();
		a.add(new Integer(5));
	}
	public void test(Integer a){
		a=15;
	}
	public void test(String a){
		a="改变了";
	}
	public void test(animal a){
		a.ans=10;
	}
	
    public static void main(String[] args) {
		Solution a=new Solution();
		
		int exam1=1;
		a.test(exam1);
		System.out.println("int类型测试:"+exam1);
		
		int[] exam2={1,2};
		a.test(exam2);
		System.out.println("int数组类型测试:"+exam2[0]+" "+exam2[1]);
		
		ArrayList<Integer> exam3=new ArrayList<>();
		exam3.add(new Integer(1));
		a.test(exam3);
		System.out.println("List测试:"+exam3.get(0));
		
		Integer exam4=new Integer(1);
		a.test(exam4);
		System.out.println("Integer包装类测试:"+exam4);
		
		String exam5="未改变";
		a.test(exam5);
		System.out.println("String类型测试:"+exam5);
		
		animal exam6=new animal(1);
		a.test(exam6);
		System.out.println("自定义类型测试:"+exam6.ans);
	}
    
    
    //自定义类型测试
    public static class animal{
    	int ans;
    	public animal(int ans){
    		this.ans=ans;
    	}
    }
}

result

int类型测试:1
int数组类型测试:5 5
List测试:5
Integer包装类测试:1
String类型测试:未改变
自定义类型测试:10

the reason

Basic types: value is stored in the local variable table, in any case modify only modifies the value of the current stack frame, execution ends of the method will not make any changes to the methods; variable outer case needs to be changed, must return to the active assignment.

Reference data types: Pointer in a local variable table, call the method, when a copy of the reference push, only a copy of the assignment change of reference. However, if the copy directly change the reference value, the modified object reference address, this address reference objects outside of this time course method was modified.

In fact, the equivalent of basic data types and String passed is actually a copy, so the change had no effect on the parameter value. While the remaining types, including custom types actually passed a reference parameter change, argument change with it.

Published 15 original articles · won praise 0 · Views 182

Guess you like

Origin blog.csdn.net/qq_36360463/article/details/103979790