4 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
我們不能一概而論的說(shuō),基本類型數(shù)據(jù)都是放在棧中的!當(dāng)某個(gè) 類實(shí)例 中具有基本類型時(shí),基本類型就放在堆中!

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
內(nèi)存分為堆和棧,這你已經(jīng)知道了。
堆內(nèi)存是屬于JVM的,棧內(nèi)存是屬于方法的,方法結(jié)束了,棧內(nèi)存也就沒(méi)了。
程序運(yùn)行main函數(shù)時(shí),有一個(gè)堆內(nèi)存,一個(gè)main的棧內(nèi)存
int var3 = 0;
這個(gè)var3,是放在main函數(shù)的棧內(nèi)存中的,是一個(gè)值。
之后
demo obj1 = new demo();
main函數(shù)的棧內(nèi)存中有了一個(gè)引用變量,obj1,指向了堆內(nèi)存中new出來(lái)的這個(gè)實(shí)例。
我們?cè)倏炊褍?nèi)存中的這個(gè)實(shí)例,他有2個(gè)字段,他們都是存放在堆中的。
等到main函數(shù)運(yùn)行結(jié)束時(shí),假如還有別的線程在運(yùn)行,JVM還沒(méi)有結(jié)束,此時(shí),main函數(shù)的棧內(nèi)存被清除,var3,不在了,obj1這個(gè)引用變量也不在了,但是堆內(nèi)存中的那個(gè)實(shí)例依然在,如果沒(méi)有別的引用變量 指向它 ,那么它將在稍后被清除。

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
是翻譯錯(cuò)誤,原文中用的是stack,即棧,而不是堆棧。以下是原文:
Special case: primitive types
One 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.
添加回答
舉報(bào)