容易混淆的面试题
复习基础,发现两个容易混淆的地方,观点不正确,欢迎指正!
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.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步