Java中传值和传引用

来源:互联网 发布:debian和centos哪个好 编辑:程序博客网 时间:2024/05/16 09:29

原理:对于基本类型的变量,Java中时传的值的副本,而对于一切的对象型变量,Java都是传引用的副本。

代码示例:

import java.util.*;public class Test{public static void main(String[] args){StringBuffer str = new StringBuffer("hello");test(str);System.out.println(str);}public static void test(StringBuffer  str){str.append(",world!") ;}}

运行结果:
c:\Users\caopu\Desktop>java Testhello,world!
StringBuffer是产生一块内存空间,相关的增删改查都在其中进行,str始终指向该对象,但是在原来的字符串尾部进行追加新的字符串。再看下面:
-------------------------------------------------------------------------------------------------------------

import java.util.*;public class Test{public static void main(String[] args){String string = "hello";test(string);System.out.println(string);}public static void test(String str){     str = "abc";//该行语句实际上生成了一个新的为abc的字符串}}
运行结果为:
c:\Users\caopu\Desktop>java Testhello
注意:String是final类型的,不可以进行继承和修改

0 0
原创粉丝点击