• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

String objects

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How many String objects will be created when we will run this code.

String s1 = "abc";
String s2 = new String("xyz");
s2 = s1;
s1.toUpperCase();
String s3 = "abc";
String s4 = s3.replace('a','A');


My answer is 5 but mock exam says it is 4.
1 more simple question
Will it make any difference if we will ask
How many String objects ? or
How many objects?

Thanks
Gagan.
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you assign 'abc' to s3, it doesn't create a new object because there's already an 'abc' string.
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi gagan,

if we say "how many objects" the answer might be not so clear... probably we don't know how the methods we call are implemented.
for example, in toUpperCase() or replace(), there might be other objects created
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

Isnt the answer going to be 3 cause s1, s2 and s4 are new objects created whereas s3 points to "abc" which is already in the pool.

Can someone clarify this , please?

Thanks
Faqeer
 
Brandon Tom
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings are immutable. They can't be changed, so when toUpperCase () is executed, a new objected is created. After that s1 points to "ABC" and not "abc".
[ January 26, 2006: Message edited by: Brandon Tom ]
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi faqeer,

String s1 = "abc"; // first
String s2 = new String("xyz"); // second
s2 = s1; // none, only reference copy
s1.toUpperCase(); // third (strings are immutable, so it must be new)
String s3 = "abc"; // none, "abc" is in the pool
String s4 = s3.replace('a','A'); // fourth


if s1 would only consist of upper case letters (eg. first line s1 = "ABC") then s1.toUpperCase() would return the original object, but i guess we don't need to know this, because it is implementation specific.

greetings
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Brandon Tom:
Strings are immutable. They can't be changed, so when toUpperCase () is executed, a new objected is created. After that s1 points to "ABC" and not "abc".

[ January 26, 2006: Message edited by: Brandon Tom ]



s1 would still point to "abc" since s1.toUpperCase() was never assigned to anything.
 
Brandon Tom
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah, indeed you are correct.

hmmm.. but, the question does ask how many String objects are created.. does it count the String returned by s1.toUpperCase ()?
[ January 26, 2006: Message edited by: Brandon Tom ]
 
Craig Tyler
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Brandon Tom:
Ah, indeed you are correct.

hmmm.. but, the question does ask how many String objects are created.. does it count the String returned by s1.toUpperCase ()?

[ January 26, 2006: Message edited by: Brandon Tom ]



Yes, it will count, but it will also be immediately eligible for garbage collection since there is no reference to the "ABC" string object.

Just to add a little fun, here's another:



Now, how many objects are created?
[ January 26, 2006: Message edited by: Craig Tyler ]
 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I read in K & B book(page 360, heading Creating New Strings) it is written that when we create String object usign new operator, java creates two object. Following code creates two object, one in non pool memory & one literal in pool memory

String s3 = new String("xyz");

In this way answer of the above question should be 5.

Any clarifications??
or am i understanding it wrong way??? please clarify...

Thanks
Gagan
 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Gagan,
yes, K &B book says that the statement,
String s3 = new String("xyz");
creates two String objects.Even my answer is 5. Can u please tell me in which mock exam u hv got this question? is it K&B mocktest itself??
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
gagan,

i don't have an explanation, but to confuse things further:

in the language specification, they say:

Each string literal is a reference to an instance of class String



So the answer should be 5.

But in the javadoc for String, they say:

For example:

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};
String str = new String(data);



I understand "equivalent" that the underlying mechanism is meant.

Then it is unclear what the answer would be, because it does not say anything about String str = new String("abc"). But i can't imagine that both hold, because then (if i am not mistaken) the long form of the javadoc example would be:

char data[] = "abc".toCharArray();
String str = (new String(data)).intern();



[ January 26, 2006: Message edited by: Tilo Hemp ]
[ January 26, 2006: Message edited by: Tilo Hemp ]
 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Now, how many objects are created?

[ January 26, 2006: Message edited by: Craig Tyler ][/qb]<hr></blockquote>

Correct me if I am wrong. The answer is 4
Both s1 and s2 refer to the same String object "abc". The new String("xyz") will create ONLY one new object and s3 will refer to it. "unome" will be another literal object that will be soon lost. s2 is then reassigned to refer to a String object "abcxyzunome".

The answer for the original question is also 4. Refer
http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html
People tend to get confused about the String Literal pool

What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects.

[ January 26, 2006: Message edited by: Abid Sami ]
[ January 26, 2006: Message edited by: Abid Sami ]
 
Craig Tyler
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've been thinking about similar things since, according to Khalid Mughal, "The compiler uses a string buffer to avoid the overhead of temporary String objects when applying the concatenation operator(+)." The same could be done whenever you make a new string by calling new String("some string").

And I have a great way to test all these things, if I could only recompile the String class. However, I keep getting errors if I either try to remove "final" from the class modifier list or if I try to add a finalize method. My first idea was to put a System.out.print in the finalize method and see what came out to know exactly how many string objects were created. So, if anyone has any ideas on how to do this, I'd appreciate it.
 
Abid Sami
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The correct answer is 4. When you use the keyword "new," the JVM is obliged to create a new String object at run-time but there is no "String literal pool object" created.

http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html
People tend to get confused about the String Literal pool

What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects.
 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Me lost after like the fifth reply for the question
 
Abid Sami
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are 4 obj created.

String s1 = "abc";
This will create obj 1 refered by s1 and there will be a reference for it in the String literal pool as well.


String s2 = new String("xyz");
This will create a new object obj 2, (There won't be a "String Literal object")

s2 = s1;
No new object created. s2 now simply referes to the obj referenced by s1. The original object refered by s2 is eligible for gc, but the question is how many objects are created?


s1.toUpperCase();
This will create an obj 3 which will be immediately lost since it is not assigned.

String s3 = "abc";
This will not create a new obj because of the String Literal pool. s3 will simply point to the obj referenced by s1.


String s4 = s3.replace('a','A');

This will create the obj 4 referenced by s4.
[ January 26, 2006: Message edited by: Abid Sami ]
 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are 4 objects created.
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
excuse me for insisting

in the meantime, i am quite sure that the correct answer is five. here are my reasons:

- the reported k&b book entry (not in the 5.0 book on page 360)
- the java language specification cited above (the entry in the String javadoc seems to be too ambiguous to invalidate this)
- and last but not least this situation is explicitly stated in the article cited by abid:

In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time (...)


So as there is no serious contraposition visible, the final explanation for me is the following:

The string literal "xyz" is converted to a string object during class loading (which belongs to the pool), and a second string object is created when execution reaches the new String("xyz").

Of course there might be discussions like "we can't know if the literal "xyz" appears already earlier in the code", or "it is unclear if class loading is included in 'when we will run this code'" But i assume that in the real exam, such points would be clarified in the question.
[ January 27, 2006: Message edited by: Tilo Hemp ]
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can the author of this question, make it little more clear or post the exact text... which will be helpful
 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer is 5 objects, just do the math.
 
ven kaar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I actually intended a request, may be my English was poor... would love to insert 'Please' into my request...

Generally i try hard to understand the question first...

Thanks Micheal...
 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ven kaar,

I have posted whole text what i got in the mock test. Answer was 4 in the mock test. Still, I am not clear what is the exact answer. Even we cant test it how many objects will be created. Please, Let me know what else you want to know about post.

Naresh Kumar,
I got this question in Wizlabs simulator.

Abid Sami,
In K & B book(page 360, heading Creating New Strings) it is written that when we create String object using new operator, java creates two object. What about this statement? Also, we cant test it ... do any way to test it?


Kaithy Or Bert
Can you please throw some light on this ?



Thanks
Gagan
 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It seems to me that the main problem here is to understand what happens when creating a String object with the new keyword. To be honest before reading this topic I thought I had some basic understanding about Strings, now I�m not sure!
First, Abid Sami said:


This will create a new object obj 2, There won't be a "String Literal object") (



Sorry. I don�t think so. Creating a String object using new creates two objects and puts the representation of the String literal in the literal pool. Philip Heller and Simon Roberts in Complete Java� 2 Certification: Study Guide, Fifth Edition, pages 255-256

[You can also construct a String by explicitly calling the constructor� however, doing so causes extra memory allocation...At runtime, the new String() statement is executed and a fresh instance of String is constructed, duplicating the String in the literal pool.


And K&B in Sun Certified Programmer Java version 1.4 on page 360:

�because we used the new keyword, Java will create a new String object in normal (nonpool) memory�In addition, the literal� will be placed in the pool.


For that reason you should avoid the unnecessary duplication of String objects in memory creating String objects without new.

Bert Bates, where are you...it's time to give us a hand, please!
Looking forward for comments,

Enrique Villamizar
P.S. English isn�t my first language.
 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I found similar question in Kaithy & Bert Book's Self Test.

Chapter 6 (java.lang)
Seft Test Question Number Q 3.

Q3.
how many string objects have been created

String x = new String("xyz");
y = "abc";
x = x+y;

Choices
A. 2
B. 3
C. 4
D. 5

answer here is C. It means 4 objects have been created.
Also in explanation it is given that when we use new operator to create string object it creates 2 Objects. So i am assuming that answer to my original question is 5. Luckily today i did not get this type of quesion in my real exam . FYI TOday, i have cleared exam with 95% score.. Yuppie

Thanks
Gagan
CCNA & SCJP(95%)
 
ven kaar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First my congrats to Gagan, also would request him to be active on this forum so as it be will be helpful for guys like me and others.

String s1 = "abc";
one object is created at compile time, resides in pool

String s2 = new String("xyz");
two objects are created at compile time, resides in pool and nonpool

s2 = s1;
as the reference is changes , the nonpool reference is eligible for gc

s1.toUpperCase();
one object is created at runtime, is in pool

String s3 = "abc";
already object is in pool

String s4 = s3.replace('a','A');
one object is created at runtime, is in pool

so my answer is 5 is created and one is gc, so finally 4.

there is a lot of discussion on the same subject, i have provided a link already discussed.


https://coderanch.com/t/252556/java-programmer-SCJP/certification/string-function


really it is still unclear, may be the person(Ernest Friedman-Hill) involved in the previous discussion can provide more details, and as requested K&B also ??

are u guys hearing, it would be of good help if someone of u answers

thanks in advance
 
Abid Sami
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer is 4 as explained before by me.

I think most of you guys seem to have misunderstood the concept of String Literal pool. Refer to the article for a better understanding
http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects. Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

When you say
String s = new String ("abc");

This will create only one object on the heap with s referencing it. At the same time there will be a reference for it created in the String Literal pool. All Objects live on the heap. There is no String Literal pool heap as most of the people seem to be suggesting on the forum
I am not saying Kathy and Bates are wrong, but they need to clarify this point.
[ January 31, 2006: Message edited by: Abid Sami ]
 
Enrique Villamizar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What about using a tool for simulating objects in memory. I know there is one called ObjectTool but I don't have it. Maybe JProfiler.

I also found this:

"Creating a String object using the new keyword creates two String Objects in memory and puts the character representation of the String literal in an area of heap memory reserved for literals called the literal pool."

Boldface two written by me. Taken from Fundamentals of the Java Programming Language, Sun Mycrosystem 2005. SL-110, Student Guide, Page 5-20.

Enrique Villamizar
P.S. English isn't my first language.
 
Abid Sami
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Enrique Villamizar:
[QB]What about using a tool for simulating objects in memory. I know there is one called ObjectTool but I don't have it. Maybe JProfiler.

I also found this: Boldface two written by me. Taken from Fundamentals of the Java Programming Language, Sun Mycrosystem 2005. SL-110, Student Guide, Page 5-20.
QB]



Thanks Enrique. Maybe that explicitly explains about the creation of two objects. It does say that using the new keyword for the creation of Strings, does create two objects after all. I haven't really used a tool for simulating objs in memory before but thats a very good way of verifying it. Anyways, the correct answer would then be 5.
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i assume you might be interested in my latest discovery

with the eclipse debugger, it is possible to watch the execution of
String s = new String("s");
in detail.
just set a breakpoint in the code, and when execution reaches it, use F5 to step into the execution of this command. (maybe it is necessary to have the source.zip decompressed for debugging inside the String constructor)

the glorious point is: when inside the constructor of String, this.value (which is a char array that holds the string's content) is still null, while arg0 is already a full-featured object of type String.

so for me this issue is finally clear now. and thank you gagan for the question!
[ January 31, 2006: Message edited by: Tilo Hemp ]
 
Forget Steve. Look at this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic