• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object query

 
Prasun Howlader
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How many Object are created following this line?

StringBuilder ob = new StringBuilder("Java");

I think 2 is it true? One for Java literal and others for StringBuilder.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Prasun Howlader:
How many Object are created following this line?

StringBuilder ob = new StringBuilder("Java");

I think 2 is it true? One for Java literal and others for StringBuilder.


Yes. That is for String literal and NOT Java literal.

You may further refer to a very good article about String Literals and objects by Corey McGlone here.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tell you in Detail from memory point of View :

StringBuilder s = new StringBuilder("Kathy");

Now compile will create 2 Objects :
>> a String Object "kathy" and put it into "String constant Pool"

>> A StringBuilder Object on the heap which will reference to "kathy" Object on SCP.

>> so Overall s (this one on stack) ---> StringBuilder (on Heap) ---->"kathy" ( on SCP)

Now what is SCP (String Constant Pool) :
Generally when a java program runs, We create a lots of string object that waste a lot of memory, So in order to make JAVA Memory Efficient, JVM set aside some area of Heap called String Constant pool, in which all object of String literals aside.

Please reply again if you need some more light on SCP.
 
Dean Jones
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> so Overall s (this one on stack) ---> StringBuilder (on Heap) ---->"kathy" ( on SCP)
---------------------------------------------------------------------------
Dear Sunny, I have few doubts:

Where do object reference variables live? On the stack or on the heap? What happens if the object reference variable is a method local variable?

Please clarify.
[ January 14, 2008: Message edited by: Dean Jones ]
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,



I know the syntax is wrong, but concept is right !!!

Cheers!
Sunny
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Ranchers,

yes, the instance variables live along with the instances in *heap* memory. Whereas the local variables do live in *stack* memory.

For a better clarification, you may refer this thread
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic