【发布时间】:2012-08-01 20:18:53
【问题描述】:
初学者 java 问题,但我无法理解在下面的示例中按值调用(或引用)是如何工作的 -
我的自定义字符串对象在退出方法后,为什么字符串值没有被修改。 ?与 Date 等其他类相同。
public class StringMadness {
public static void main(String[] args) {
String s = "Native String";
CustomStringObject cs = new CustomStringObject();
System.out.println("Custom String Before: " + cs.str);
hello(cs);
System.out.println("Custom String After: " + cs.str);
System.out.println("Native String Before: " + s);
hello(s);
System.out.println("Native String After: " + s);
}
private static void hello(String t) {
t = "hello " + t;
}
private static void hello(CustomStringObject o) {
o.str = "hello " + o.str;
}
}
class CustomStringObject {
String str = "Custom String";
}
【问题讨论】:
标签: java pass-by-reference pass-by-value