---恢復內容開始---this
第一個引用傳遞案例:spa
class Message{ private int num; public Message(int num){ this.num=num; } public void setNum(int num){ this.num=num; } public int getNum(){ return this.num; } } public class Test{ public static void main(String args[]){ Message msg = new Message(10); change(msg);//引用傳遞 System.out.println(msg.getNum());//輸出100 } public static void change(Message temp){ msg.setNum(100); } }
對該代碼進行內存分析,值類型不會獨自佔有一塊堆內存,必需要有實例化對象,而String類的匿名對象會獨自佔用一塊堆內存,不須要對象3d
第二道引用傳遞案例code
public class Test{ public static void main(String args[]){ String msg = "hello"; change(msg); System.out.println(msg);//輸出hello } public static void change(String temp){ temp="word"; } }
String的匿名對象有獨立的堆內存空間,此外字符串一旦聲明則不能夠被改變,若想改變只有改變其對象地址,內存分析:對象
第三個引用傳遞案例blog
class Message{ private String str; public Message(String str){ this.str=str; } public void setStr(String str){ this.str=str; } public String getStr(){ return this.str; } } public class Test{ public static void main(String args[]){ Message msg = new Message("hello"); change(msg); System.out.println(msg.getStr()); //輸出word } public static void change(Message temp){ temp.setStr("word"); } }
---恢復內容結束---內存
第一個引用傳遞案例:字符串
class Message{ private int num; public Message(int num){ this.num=num; } public void setNum(int num){ this.num=num; } public int getNum(){ return this.num; } } public class Test{ public static void main(String args[]){ Message msg = new Message(10); change(msg);//引用傳遞 System.out.println(msg.getNum());//輸出100 } public static void change(Message temp){ msg.setNum(100); } }
對該代碼進行內存分析,值類型不會獨自佔有一塊堆內存,必需要有實例化對象,而String類的匿名對象會獨自佔用一塊堆內存,不須要對象get
第二道引用傳遞案例class
public class Test{ public static void main(String args[]){ String msg = "hello"; change(msg); System.out.println(msg);//輸出hello } public static void change(String temp){ temp="word"; } }
String的匿名對象有獨立的堆內存空間,此外字符串一旦聲明則不能夠被改變,若想改變只有改變其對象地址,內存分析:
第三個引用傳遞案例
class Message{ private String str; public Message(String str){ this.str=str; } public void setStr(String str){ this.str=str; } public String getStr(){ return this.str; } } public class Test{ public static void main(String args[]){ Message msg = new Message("hello"); change(msg); System.out.println(msg.getStr()); //輸出word } public static void change(Message temp){ temp.setStr("word"); } }