Memory heap and stack

All objects are stored on the heap (including their attributes).1

Local variables (including arguments) always contain primitive values or references and are stored on the stack.

String one = "abc";
String two = new String("abc");
You'll have two objects on the heap (two String objects containing "abc") and two references, one for each object, on the stack (provided one and two are local variables).

There are two storage areas involved: the stack and the heap. The stack is where the current stateof a method call is kept (ie local variables and references), and the heap is where objects are stored. The Hotspot documentation says that on Linux 64-bit each thread has a stack of 1024kB by default. The heap can be made arbitrary big, and today it's in the order of GB.
A recursive method uses both the stack and the heap. Which one you run out of first depends on the implementation. As an example, consider a method which needs thousands of integers: if they are declared as local variables, ie:
public void stackOverflow() { int a_1; int a_2; int a_3; // ... int a_10_000_000;}

your program will crask with a StackOverflowError
. On the other hand, if you organize your integers in an array, like:
public void outOfMemory() { int[] integers = new int[10 * 1000 * 1000];}

the heap will be filled soon, and the program will end with an OutOfMemoryError
. In neither case the memory is corrupted or data overridden. However, in both cases the code is wrong and must be fixed somehow - but to tell you how we'd need to know more about your program.

Deque (Stack) as object is stored on the heap

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 好久沒有翻看QQ上的好友動態(tài),今天隨意瀏覽了那么幾頁。一個個萌娃照浮現(xiàn),頓時嫉妒心起,偶又在腦海中把那個不知在哪兒...
    魚琪兒閱讀 229評論 0 1
  • 野水笑談錄 (一) 二十多年前。 離城八十里有個鄉(xiāng),叫野水鄉(xiāng)。鄉(xiāng)里有所中學(xué),叫野水鄉(xiāng)中。野水鄉(xiāng)中的校長姓吳名虛,四...
    獨(dú)行的老雕蟲閱讀 483評論 0 3
  • 在剛剛送走的2016年,我決定從年初就開始寫日記,而且要堅(jiān)持一年?,F(xiàn)在一年過去了,除了6、7月沒有天天記,其他時間...
    奔跑的馬齒莧閱讀 189評論 0 0

友情鏈接更多精彩內(nèi)容