Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in creating strings... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in creating strings..." Watch "Doubt in creating strings..." New topic

Doubt in creating strings...

thambi durai

Joined: Jan 30, 2008
Posts: 6
can any one explain the two way of String creation ...

String s="hello";
String s=new String("hello");
how many object and reference is created in heap and pool.


public String makinStrings()
String s = �Fred�;
s = s + �47�;
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
How many String objects will be created when this method is invoked?
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
Ian Edwards
Ranch Hand

Joined: Aug 14, 2006
Posts: 107
Okay, if we go through the code line by line:

We are creating a String object here and giving s a reference to it.

"47" is a String object, and we are creating a new string object by concatenating "47" to "Fred". We lose the reference to "Fred" and point s to "Fred47".

In this line we are creating a new String object, "ed4", and assign it to s.

Here we create a new String object, "ED4", and assign it to s.

Lastly, we create a new String object using the toString() method.

In total we are creating 6 string objects.
thambi durai

Joined: Jan 30, 2008
Posts: 6
but the answer is 3...
how it's possible..
Dean Jones
Ranch Hand

Joined: Dec 29, 2007
Posts: 129
Dear Thambi,

please see the link

Joined: Sep 20, 2007
Posts: 8
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Doubt in creating strings...
Similar Threads
How many String objects will be created?
What the output related to string
please provide the explanation regarding string objects............
How many String objects are created?
how many String objects created??