Java Stack and Heap: Java Memory Allocation Tutorial - Guru99

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?