public static void main(String[] args) {
String name = null;
String s = test(name);
System.out.println(name);
System.out.println(s);
}
private static String test(String name) {
String s = "ssssss";
name = "hello";
return s;
}
output
null
ssssss
更新代码
public static void main(String[] args) {
Map<String, String> map = test();
String name = map.get("name");
System.out.println(name);
}
private static Map<String, String> test() {
Map<String, String> map = new HashMap();
String name = "hello";
map.put("name", name);
return map;
}
output
hello
根本原因在于String类型的变量是常量,变量是引用,实际值存储在堆中的常量池中。