• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

stack memory

 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In java ,parameters inside methods are in stack ,all instance variable exist in heap memory.so whatever things written inside a method not affected when many threads access the class.

my question is as follow

1)
if create a object which has instance variable, inside a method then it will exist in heap memory or stack?
 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if create a object which has instance variable, inside a method then it will exist in heap memory or stack?


You need to understand the difference between an object and a reference to an object. An object is always on the heap (there is an exception, but let's not get into that ... ). A reference, can be on the heap, if it is part of the object, such as an instance variable. Or it can be on the stack, when it is declared locally, such as a local variable or a parameter.

Now as for your question...

There is no such thing as an instance variable inside a method. Variables declared inside a method are local variables.

Henry
 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if object reference variable inside a method,if many thread access the object
then

local object state is not distributed by other threads because object reference variable is local ?
or
local object state is distributed by other threads because object is in heap ?
 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
local object state is not distributed by other threads because object reference variable is local ?
or
local object state is distributed by other threads because object is in heap ?


Again, you need to understand the difference between an object and a reference to an object.

Each method will have a local variable which will have there own copy of the reference. This reference will point to an object on the heap. Now... this reference can point to a privat copy of the object -- if it is instantiated in the method. Or it can point to a object, that all objects refer to.

Just because an object is on the heap, doesn't mean that it is shared. It depends on how you coded your application.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic