对于基本数据类型,可以记住是值传递,即传进去的参数做任何修改不会影响外面。
对于类,是引用传递,传进函数的对象,在函数中做的任何动作都会一直生效,能带到外面来。
有个特殊情况:字符串,它是类但它的现象又是值传递,一般人考试就爱考这个!不得不说,有些人就喜欢问茴香的茴字有多少种写法,屁用没有!
-
public class Test {
-
-
public int a = 0;
-
-
public static void testForValue(int i) {
-
i++;
-
}
-
-
public static void testForReferenceTest(Test test) {
-
test.a = 10;
-
}
-
-
public static void testForReferenceString(String str) {
-
str = "abc";
-
}
-
-
public static void main(String[] args) {
-
// test value
-
int i = 0;
-
System.out.println("before value test: i=" + i);
-
Test.testForValue(i);
-
System.out.println("after value test: i=" + i);
-
-
System.out.println("===================================================");
-
-
// test reference
-
Test test = new Test();
-
System.out.println("before normal reference test: test.a=" + test.a);
-
Test.testForReferenceTest(test);
-
System.out.println("after normal reference test: test.a=" + test.a);
-
-
System.out.println("===================================================");
-
// test String reference
-
String str = "123";
-
System.out.println("before String reference test: str=" + str);
-
Test.testForReferenceString(str);
-
System.out.println("after String reference test: str=" + str);
-
-
}
-
-
}
输出结果
-
before value test: i=0
-
after value test: i=0
-
===================================================
-
before normal reference test: test.a=0
-
after normal reference test: test.a=10
-
===================================================
-
before String reference test: str=123
-
after String reference test: str=123
阅读(1472) | 评论(0) | 转发(0) |