好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java参数传递之值传递和引用传递

值传递

 

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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类型数据在传入时,进行的操作是在字符串常量池中新建一个字符串,并不影响原先字符串的值

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

  }

}

到此这篇关于java参数传递之值传递和引用传递的文章就介绍到这了,更多相关值传递和引用传递内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestcnblogs测试数据/leohost/p/14388853.html

查看更多关于java参数传递之值传递和引用传递的详细内容...

  阅读:13次