java 基本數據類型各種情況下在內存中存儲位置?
問題描述
問題:如何理解《Java編程思想-第四版》P23 中,這個變量直接存儲“值”,并置于堆棧中,因此更加高效一句中的 “堆棧” 兩字,到底是堆還是棧?情況如下:
class demo { private int var1; // 字段1 private Integer var2; // 字段2 public static void main(String[] args) {int var3 = 0; // 變量1demo obj1 = new demo(); // 實例1 }}我的理解
參考《Java編程思想-第四版》P23 和 《深入理解Java虛擬機:JVM高級特性與最佳實踐 第2版》P39-P43,對于該 demo
實例1:存儲在堆內存中
變量1:存儲在方法棧中
實例1中的字段1:存儲在堆中
實例1中的字段2:存儲在堆中
如果是存儲在堆中的話,何來高效一說?
問題解答
回答1:我們不能一概而論的說,基本類型數據都是放在棧中的!當某個 類實例 中具有基本類型時,基本類型就放在堆中!
回答2:內存分為堆和棧,這你已經知道了。
堆內存是屬于JVM的,棧內存是屬于方法的,方法結束了,棧內存也就沒了。
程序運行main函數時,有一個堆內存,一個main的棧內存
int var3 = 0;這個var3,是放在main函數的棧內存中的,是一個值。
之后demo obj1 = new demo();main函數的棧內存中有了一個引用變量,obj1,指向了堆內存中new出來的這個實例。
我們再看堆內存中的這個實例,他有2個字段,他們都是存放在堆中的。
等到main函數運行結束時,假如還有別的線程在運行,JVM還沒有結束,此時,main函數的棧內存被清除,var3,不在了,obj1這個引用變量也不在了,但是堆內存中的那個實例依然在,如果沒有別的引用變量 指向它 ,那么它將在稍后被清除。
回答3:是翻譯錯誤,原文中用的是stack,即棧,而不是堆棧。以下是原文:
Special case: primitive typesOne group of types, which you’ll use quite often in your programming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap. For these types Java falls back on the approach taken by C and C++. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and it’s placed on the stack, so it’s much more efficient.
回答4:p22,堆棧指的是stack,堆指的是heap
相關文章:
1. javascript - 數組原聲方法中的一段代碼2. python小白的基礎問題 關于while循環的嵌套3. MySQL客戶端吃掉了SQL注解?4. javascript - JS設置Video視頻對象的currentTime時出現了問題,IE,Edge,火狐,都可以設置,反而chrom卻...5. 求大神幫我看看是哪里寫錯了 感謝細心解答6. javascript - 百度echarts series數據更新問題7. python - Django分頁和查詢參數的問題8. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)9. php自學從哪里開始?10. phpstady在win10上運行
