This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Objects created...

 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How many objects are created with this statement..?

String a=new String("AA");

Someone gave the answer as 2..but am not happy with the xplanation..

Can any of u provide the answer for this..?

Tx
 
shekar march chandra
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi kumar,

Yes, the answer is right. It creates two objects from the following statement.

String a = new String("AA"); --------------1

First you should be aware that there is something called as Heap(where

objects live) and String Constant pool(especially for string literals

eg:String a = "abc", this will be placed into String constant pool).

Since you have used new keyword in equation 1, it will definitely create

one object in Heap and a will refer to it.

In addition, the literal "AA" will be placed into String Constant Pool.

so u have created two objects

1. one in heap 2. one in String constant pool.

But only one reference variable. i,e : a

I think this will clear ur doubt.

Thanks,
Chandra
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The above is untrue. You will have two String instances on the heap. One will be created at class load time (pulled from the String literal pool, which exists in the class bytecode), and the other at the time 'new' is used.

I truly hope all misconception will be abandoned regarding this topic some day. Please read this: http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tx Chandra!!!

Tx Toni.... : ) I will have a look at the link...
[ August 22, 2005: Message edited by: A Kumar ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic