引用传递和值传递分析

值传递

当调用方法进行值传递时,方法内部会产生一个局部变量,在方法内部使用局部变量的值,并不影响传入原来数据的值,包括在使用基本数据类型的包装类。

public class Assc
{
public static void main(String[] args)
{
int x1=1;
add(x1);
       System.out.println("最终"+x1);//1
Integer x2=new Integer(1);
sub(x2);
System.out.println("最终"+x2);//1
}
public static void add(int x) {
x++;
System.out.println(x); //2
}
public static void sub(Integer x) {
x--;
System.out.println(x);//0
}

}

 

引用传递

当调用方法时使用引用类型参数时,使用的是与传入参数同一地址的数据,在方法内部进行参数的修改,会造成原来数据的改变(String 类型除外)

String类型数据在传入时,进行的操作是在字符串常量池中新建一个字符串,并不影响原先字符串的值

public class Assc
{
public static void main(String[] args)
{
String str="hello";
combine(str);
System.out.println("最终"+str);//hello
StringBuilder sb=new StringBuilder("nihao");
combine2(sb);
System.out.println("最终"+sb);//nihaoworld
}

public static void combine(String str) {
str+="world";
System.out.println(str);//helloworld
}
public static void combine2(StringBuilder str) {
str.append("world");
System.out.println(str);//nihaoworld
}
}

 

版权声明:本文为leohost原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/leohost/p/14388853.html