• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between the way to create a variable in the memory  RSS feed

 
Raga Jana
Ranch Hand
Posts: 35
Google Web Toolkit Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

I need the clarity on the following example. Normally the primitive types use to store in the stack and the objects in the heap. When i try to do the following what will happen??



I know that st1 variable will save in the Stack memory but what about variable or Object reference st2??

 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

Strings aren't really primitive types although it's easy to think of them that way, so because they are objects they live on the heap as far as I am aware.

 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Primitives aren't always stored on the stack. They may be stored on the heap as part of an object.

Only local variables reside on the stack, and this includes reference variables.

Ernie also already noted that Strings are objects.
 
Raga Jana
Ranch Hand
Posts: 35
Google Web Toolkit Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply. Consider both of them as a class members, then wat's the difference between the exampla 1 and 2.. Or identically both are same?? Or Ex1 is the shortest of Ex2??
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mayilsamy Annamalai wrote: . . . I know that st1 variable will save in the Stack memory but what about variable or Object reference st2??
Why is st1 on the stack? How do you know it's on the stack? Doesn't that vary if it's a local variable or a field? And where is the object created that st1 or st2 points to?

Have you read the String() constructors? Have you been through the Ranch and searched for threads like this one? Or the JavaRanch Journal?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


And there is also another monkey wrench in the works. With Java 6/7, the compiler can do "escape analysis". And depending whether an instance can escape a method, the optimizer may decide to place certain instances on the stack too.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!