Java Stack and Heap: Java Memory Allocation Tutorial - Guru99
文章推薦指數: 80 %
The code section contains your bytecode. · The Stack section of memory contains methods, local variables, and reference variables. · The Heap ... Skiptocontent WhatisStackMemory? Stackinjavaisasectionofmemorywhichcontainsmethods,localvariables,andreferencevariables.StackmemoryisalwaysreferencedinLast-In-First-Outorder.Localvariablesarecreatedinthestack. WhatisHeapMemory? HeapisasectionofmemorywhichcontainsObjectsandmayalsocontainreferencevariables.Instancevariablesarecreatedintheheap MemoryAllocationinJava MemoryAllocationinJavaistheprocessinwhichthevirtualmemorysectionsaresetasideinaprogramforstoringthevariablesandinstancesofstructuresandclasses.However,thememoryisn’tallocatedtoanobjectatdeclarationbutonlyareferenceiscreated.Forthememoryallocationoftheobject,new()methodisused,sotheobjectisalwaysallocatedmemoryontheheap. TheJavaMemoryAllocationisdividedintofollowingsections: Heap Stack Code Static Thisdivisionofmemoryisrequiredforitseffectivemanagement. Thecodesectioncontainsyourbytecode. TheStacksectionofmemorycontainsmethods,localvariables,andreferencevariables. TheHeapsectioncontainsObjects(mayalsocontainreferencevariables). TheStaticsectioncontainsStaticdata/methods. DifferencebetweenLocalandInstanceVariable Instancevariableisdeclaredinsideaclassbutnotinsideamethod classStudent{ intnum;//numisinstancevariable publicvoidshowData{} Localvariablearedeclaredinsideamethodincludingmethodarguments. publicvoidsum(inta){ intx=inta+3; //a,xarelocalvariables; } DifferencebetweenStackandHeap Clickhereifthevideoisnotaccessible Let’stakeanexampletounderstandthisbetter. Considerthatyourmainmethodcallingmethodm1 publicvoidm1{ intx=20 } Inthestackjava,aframewillbecreatedfrommethodm1. ThevariableXinm1willalsobecreatedintheframeform1inthestack.(Seeimagebelow). Methodm1iscallingmethodm2.Inthestackjava,anewframeiscreatedform2ontopoftheframem1. Variablebandcwillalsobecreatedinaframem2inastack. publicvoidm2(intb){ booleanc; } Samemethodm2iscallingmethodm3.Againaframem3iscreatedonthetopofthestack(seeimagebelow). Nowletsayourmethodm3iscreatinganobjectforclass“Account,”whichhastwoinstancesvariableintpandintq. Account{ Intp; Intq; } Hereisthecodeformethodm3 publicvoidm3(){ Accountref=newAccount(); //morecode } ThestatementnewAccount()willcreateanobjectofaccountinheap. Thereferencevariable“ref”willbecreatedinastackjava. Theassignment“=”operatorwillmakeareferencevariabletopointtotheobjectintheHeap. Oncethemethodhascompleteditsexecution.Theflowofcontrolwillgobacktothecallingmethod.Whichinthiscaseismethodm2. Thestackfrommethodm3willbeflushedout. Sincethereferencevariablewillnolongerbepointingtotheobjectintheheap,itwouldbeeligibleforgarbagecollection. Oncemethodm2hascompleteditsexecution.Itwillbepoppedoutofthestack,andallitsvariablewillbeflushedandnolongerbeavailableforuse. Likewiseformethodm1. Eventually,theflowofcontrolwillreturntothestartpointoftheprogram.Whichusually,isthe“main”method. WhatifObjecthasareferenceasitsinstancevariable? publicstaticvoidmain(Stringargs[]){ Aparent=newA();//morecode}classA{Bchild=newB();inte;//morecode}classB{intc;intd;//morecode} Inthiscase,thereferencevariable“child”willbecreatedinheap,whichinturnwillbepointingtoitsobject,somethinglikethediagramshownbelow. Summary: Whenamethodiscalled,aframeiscreatedonthetopofthestack. Onceamethodhascompletedexecution,theflowofcontrolreturnstothecallingmethodanditscorrespondingstackframeisflushed. Localvariablesarecreatedinthestack Instancevariablesarecreatedintheheap&arepartoftheobjecttheybelongto. Referencevariablesarecreatedinthestack. YouMightLike: JavaDate&Time:SimpleDateFormat,CurrentDate&Compare JavaStringendsWith()MethodwithExample ScalaTutorial:ScalaProgrammingLanguageExample&Code SelectionSortinginJavaProgramwithExample JavavsScala:WhatistheDifference? Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search
延伸文章資訊
- 1Java Heap Space vs Stack - Memory Allocation in Java
Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever w...
- 2Heap vs. Stack: Code Examples, Tutorials & More - Stackify
What is Java Heap Space ... It is created by the Java Virtual Machine when it starts. The memory ...
- 3JVM stack and heap | 方格子
使用intelliJ IDE 開發工具的話, 建議可以安裝java-visualizer 來觀察。 首先關注a, b 這2 個變數, ... JVM 什麼時候使用stack 什麼時候使用heap ?
- 4Java 面試- JVM 的Stack 和Heap - Laugh Now
JVM 記憶體的Stack 和Heap 絕對不要和其他同名的東西搞混,在這裡是做為JVM 儲存資料或指令的區域,和其他同名的東西無關,請把它當作平行宇宙看待。
- 5stack 和heap | 新手Java 工程師的學習筆記 - - 點部落