容易混淆的面试题
复习基础,发现两个容易混淆的地方,观点不正确,欢迎指正!
public class Test { public static void changStr(Letter y) { //存在方法区 y.str = "welcome"; } public static void main(String[] args) { Letter x = new Letter(); //存在堆中 x.str = "1234"; System.out.println(x.str); // print: "1234" 输出完成,x 会被释放掉; changStr(x); // System.out.println(x.str); // print: "welcome"
}
}
class Letter { //始终存在
String str;
}
y 和 x 都是Letter 类的实例, y.str 和 x.str 都是Letter 类的属性, 只是不同作用域,赋值的内容不一样;
前者在方法区中赋值的"welcome" , 后者在main方法中赋值的"1234" ;
public class Test { public static void changStr(String str){ //存放在方法区中 str ="welcome"; //参数的作用域仅限于括号内 } public static void main(String[] args) { String str = "1234"; changStr(str); System.out.println(str); // 输出"1234" }
str = welcome 是方法区的参数,作用域仅限于本括号内,在main方法中,无法被引用.
所以才会输出1234.