Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Objects created... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Objects created..." Watch "Objects created..." New topic

Objects created...

A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 980

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..?

shekar march chandra

Joined: Jul 07, 2005
Posts: 25
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.

Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
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:

Tony Morris
Java Q&A (FAQ, Trivia)
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 980
Tx Chandra!!!

Tx Toni.... : ) I will have a look at the link...
[ August 22, 2005: Message edited by: A Kumar ]
I agree. Here's the link:
subject: Objects created...
It's not a secret anymore!