首页 > 编程开发 > Java    日期:2021-02-08 / 来自互联网 / 浏览

值传递

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

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
 }
}

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章