您的位置:首页 > 编程语言 > Java开发

java中值传递和引用传递

2015-10-18 15:15 141 查看
最近去面试,笔试考这个的相当多,也比较基础,就总结一下。

1.值传递

在方法调用时,传递的参数是按值的拷贝传递。重要特点:传递的是值的拷贝,也就是说传递后就互不相关了。

class test {
public static class TempTest {
private void test1(int a) {
a = 5;
System.out.println("test1方法中的a=" + a);
}
}
public static void main(String[] args) {
TempTest t = new TempTest();
int a = 3;
t.test1(a);// 传递后,test1方法对变量值的改变不影响这里的a
System.out.println("main方法中的a="+a);
}
}

结果:

test1方法中的a=5
main方法中的a=3

2.引用的传递

在方法调用时,传递的参数是按引用进行传递,其实传递的引用的地址,也就是变量所对应的内存空间的地址,这样当我们改变地址指向的值的时候,原来的指向内存地址中的值自然就改变了。 传递的是值的引用,也就是说传递前和传递后都指向同一个引用(也就是同一个内存空间)

class Ref2{
String temp = "hello";
}
public class RefDemo03 {
public static void main(String args[]){
Ref2  r1 = new Ref2();
r1.temp="main:nihao";
System.out.println(r1.temp);
tell(r1);
System.out.println(r1.temp);
}
public static void tell(Ref2  r2){
r2.temp="tell:hi";
}
}

结果:

main:nihao
tell:hi

3.特别的,在java中String类是字符串常量,是不可更改的常量,而StringBuffer是字符串变量,它的对象时可以扩充和修改的。所以会出现下面这种情况

public class RefDemo02 {
public static void main(String args[]) {
String str1 = "Hello";
//  String str1 = new String("hello");
System.out.println(str1);
tell(str1);
System.out.println(str1);
}
public static void tell(String str2){
str2+="tell";
}
}

结果:

Hello
Hello

这里创建了二个String对象,所以原来的引用并没有改变,还是hello。但是对于StringBuffer确不一样

public class RefDemo02 {

public static void main(String args[]) {
StringBuffer sb = new StringBuffer("hello");
System.out.println(sb);
tell(sb);
System.out.println(sb);
}
public static void tell(StringBuffer str2){
str2.append("tell");
}
}

结果:

hello
hellotell

这里只不过创建了一个StringBuffer的变量,二个都指向同一个,改变了自然就能生效。

String为什么会出现这种情况,我的猜想是因为String是通过char[]来实现的,类似与Integer是int的包装类,String 也相当于是char[]的包装类,包装类在对其值操作时会出现对其对应基本类型的性质 ,传递参数的时候就是这样体现的。同样Integer,Float等这些包装类和String表现是一样的,看代码

public class test2 {
public static void main(String[] arg) {
// Integer i = 9;
Integer i = new Integer(9);
System.out.println(i);
test(i);
System.out.println(i);
}
public static void test(Integer i) {
i = 11;
}
}

结果:

9

9

我还是新手,所有代码都是实际运行后的,结果没有问题。不过不知道后面这样猜想对不对,这方面有了解的求指导,博客里面有任何有错误请指出,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: