值传递和引用传递

来源:互联网 发布:淘宝卖家有ipad客户端 编辑:程序博客网 时间:2024/05/18 18:15

样例 1:
下列程序的输出结果?

public class Test {    public static void test(StringBuffer str1, String str2) {        str1.append(", World!");        str2 = "World";    }    public static void main(String[] args) {        StringBuffer string1 = new StringBuffer("Hello");        String string2 = "Hello";        test(string1, string2);        System.out.println("string1: " + string1);        System.our.println("string2: " + string2);    }}//output: //string1: Hello, World!//string2: Hello

样例 2:
下列程序的输出结果?

class Value {    public int i = 15;}public class Test {    public static void main(String[] args) {        Test t = new Test();        t.first();    }    public void first() {        int i = 5;        Value v = new Value;        v.i = 25;        second(v, i);        System.out.println(v.i);    }    public void second(Value v, int i) {        i = 0;        v.i = 20;        Value val = new Value();        v = val;        System.out.println(v.i + " " + i);    }}//output://15 0//20

PS:

Java不管是值传递还是引用传递,传递的都是副本
1 0