*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How many objects created? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How many objects created?" Watch "How many objects created?" New topic
Author

How many objects created?

Invincible Tux
Greenhorn

Joined: Mar 12, 2005
Posts: 6
1. StringBuffer s1 = new StringBuffer("abc");

2. StringBuffer s2 = s1;

3. StringBuffer s3 = new StringBuffer("abc");

How many objects are created ?

1. 0

2. 1

3. 2

4. 3

Answer : 4



Only 2 objects will be created, ryt? how come 3?
Jay Pawar
Ranch Hand

Joined: Aug 27, 2004
Posts: 411
There will be three objects created viz: 2 StringBuffer objects s1 and s3 and 1 String object "abc" in string constant pool.
Hope that helps.


Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
Originally posted by Jay Pawar:
There will be three objects created viz: 2 StringBuffer objects s1 and s3 and 1 String object "abc" in string constant pool.
Hope that helps.


where its written that "abc" will also be created in string pool ?

pls give any link ? hearing first time...

why "abc" will be created in string pool ? as
Stringbuffer object are already created in heap ?


Thanks and Regards, Amit Taneja
Invincible Tux
Greenhorn

Joined: Mar 12, 2005
Posts: 6
There will be only 2 StringBuffer objects, right?
samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160
hey how string object "abc " can be created
i think only 2 object will be created
Amol Deshmukh
Greenhorn

Joined: Jun 05, 2005
Posts: 12
I think the question is a little contentious since it is a code snippet. Hence if the string "abc" is already in constant pool, no new object will be created. However, assuming that "abc" is not already in the constant pool at runtime (due to execution of some other code not shown in the snippet), the given code will result in creation of one string object in addition to the 2 stringbuffer objects.

I have seen similar questions on different tests and my opinion is that for the purpose of the test, "abc" should be considered as "creating" an object the first time it appears in code.

Any thoughts?
Abdulla Mamuwala
Ranch Hand

Joined: Jan 09, 2004
Posts: 225
Lets see what the code does step by step


The above code can be shown as:

s1------------------------------------------>abc
(Reference StringBuffer)--------------------->(heap)



s1------------------------->abc
|
|
s2---------------------------|

Therefore we have one object on the heap and two reference variables pointing to the same object. Then,



s1-------------------------->abc
|
|
s2---------------------------|

s3------------------------------------------->abc
(Reference StringBuffer)--------------------->(heap)

This gives us two "abc" objects of type StringBuffer on the heap.

[ June 12, 2005: Message edited by: Abdulla Mamuwala ]

[ June 12, 2005: Message edited by: Abdulla Mamuwala ]
[ June 12, 2005: Message edited by: Abdulla Mamuwala ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
"Invincible", I see you've been asked before to edit your display name according to your official display name policy. This is your last warning.

As for the question - questions involving string literals generally make vary poor mock questions, because there are a number of very subtle considerations to deal with. I'm pretty sure the real SCJP exam will not ask questions that depend on this. So for most people (those of you who just want to do well on the exam), it's really not worthwhile to spend a lot of time worrying about questions like this. For this question you definitly need to understand that there are exactly two StringBuffer objects. But don't worry about how many String objects there are, unless you really want to understand details beyond what you need for the exam.

Having said that, a String with contents of "abc" will be created once (and only once, unless we use different classloaders to load and unload classes). The object will not be created when the above code is executed; rather it will be created when the class containing this literal is loaded into the JVM. I.e. generally just before any of the code in this class is executed. Unless another class has caused "abc" to be loaded (and interned) prior to htis.

For those who care, you can find many, many, many discussions of this by searching this forum for "string pool" or "intern pool".


"I'm not back." - Bill Harding, Twister
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
We (the JavaRanch forum) go through this around once per week, with the usual sprinkle of fallacy just to confuse the original poster.
Isn't it time to put it on a FAQ or something?
http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true


Tony Morris
Java Q&A (FAQ, Trivia)
alapati kirankumar
Greenhorn

Joined: Jun 13, 2005
Posts: 6
Hi
I am new to this Forum.

My answer for the above question is,
only 2 objects will be created.
vjy chin
Ranch Hand

Joined: Feb 17, 2005
Posts: 279
Hi Guys,
is there any tool which can find out the no of object created? So it will be easy to know the exact count.
Any ideas on this,
Thanks
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
http://www.jprofiler.com/
Vishnu Prakash
Ranch Hand

Joined: Nov 15, 2004
Posts: 1026
That was a wonder software tony. Thanks for posting it.


Servlet Spec 2.4/ Jsp Spec 2.0/ JSTL Spec 1.1 - JSTL Tag Documentation
Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
There will be three objects created viz: 2 StringBuffer objects s1 and s3 and 1 String object "abc" in string constant pool.

Jay,
s1,s2 & s3 are references to the object not the objects themself.The s2 will refer to the object created by the s1,then how 3 objects are created? the ans should be 3rd option 2.


Shubhada
Pulamathi Pavan Kumar
Greenhorn

Joined: May 31, 2005
Posts: 6
I think, Only 2 Objects are created. To my knowledge, objects are created using the "new" operator. But String s2 is a reference. Hence forth only 2 objects are created.

Let me know if this is not a valid reason with explanation.

Regards,
Pavan.
Shalini Chandel
Ranch Hand

Joined: May 05, 2005
Posts: 115
Line 1 created 2 objects, one referred to by s1 and the lost string "abc"
That makes 2 objects
Line 3 creates 1 more referred to by s3.
That makes total of 3 objects..

Or take it like this..2 objects would be created by new operator and 1 more the lost string "abc"


SCJP 1.4
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
hi all

For Strings i hope this link helps more

Strings
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
There are three objects created (answer: 4).
The article referred to is full of untruth.
http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true
ISLAMSAIED
Greenhorn

Joined: Apr 26, 2005
Posts: 4
of course it will be only 2 ,becuse when i use s2=s1 that mean s2 in memory is point to s1 not an new object memory to asign to a new memory location we use (new)
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
10 The answer is "3 objects are created". This includes the object created at class-load time to represent the String literal.
20 GOTO 10
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
"ISLAMSAIED", your displayed name does not conform to our JavaRanch Naming Policy. Please change it.

"Invincible Tux", the same goes for your displayed name, please change it.



Thanks
-Barry

(NR Final reminder)


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
RameshKumar MuthuKumar
Greenhorn

Joined: May 25, 2005
Posts: 8
hi all,
as i know only two objects will be created.......that was i understood how objects are dealed and managed.
can anyone pls tell me some article or online tutorial for understanding object creatin and strings

thnks
ramesh
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
No, I can't provide any more, but I can provide one that has already been provided: http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true
You have to click it.
...with your mouse.
...which is next to the keyboard.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Given the options the answer is three objects.

In fact "two or three" would be correct but they do not give that option and it seems unreasonable to assume anything about external code. Therefore three is the prudent choice.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
No, "two or three" is not correct.
Three is correct as per the Java Language Specification Second Edition.

Arguably four is a correct answer, but it is assumed that this code runs under the same class loader.
[ June 19, 2005: Message edited by: Tony Morris ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Tony]: Arguably four is a correct answer, but it is assumed that this code runs under the same class loader.

In the original post, the lines of code are numbered. It's exceedingly obvious that they occur one after another, with no other code in between (e.g. code to load and unload classes). Now you could bring in other class loaders outside this code fragment, causing it (all three consecutive lines) to be loaded and executed more than once - but in that case the number of objects created would obviously be 6, 9, 12... some multiple of 3. Not 4.

Before we bring in multiple class loaders though, why not consider something much simpler? E.g. simply executing the code more than once, with a single class loader. Assume main() is executed exactly once, as usual:

The method foo() itself creates only two StringBuffer objects. And loading the class Test creates one String "abc". (Actually more, too, behind the scenes, but we're way beyond what anyone needs to be worrying about for SCJP at this point, so nevermind.)

The original question was, quite simply, a bad question, with too many subtleties that were unknowable from the way the question was stated. Rick's "two or three" was quite sensible under the circumstances. Certainly moreso than "four". :roll: Given the vagueness of the question I don't think any one definitive answer is really possible, as there will always be someone who interprets it differently. But let's try to understand what a person is actually saying before reflexively disagreeing, eh?
[ June 19, 2005: Message edited by: Jim Yingst ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I got lost after you said that "two or three" could make sense, but I'll just nod anyway.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Originally posted by Tony Morris:
No, "two or three" is not correct.
Three is correct as per the Java Language Specification Second Edition.

Arguably four is a correct answer, but it is assumed that this code runs under the same class loader.

[ June 19, 2005: Message edited by: Tony Morris ]


I disagree. If you have the same string literal in the same class (as appears in that example) it is either already in the pool or not: two or three. Four is not possible because you cannot have two string literals referenced in the same class loaded from two different class loaders.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

I disagree. If you have the same string literal in the same class (as appears in that example) it is either already in the pool or not: two or three. Four is not possible because you cannot have two string literals referenced in the same class loaded from two different class loaders.

The String instance will exist in the pool well before that code executes (at class load time), therefore, always at least three. Two String literals may exist as different instances under two different class loaders, but as Jim points out, this 'corner case' is really irrelevant given the code line numbers (and therefore, impossible to exist under separate class loaders). Therefore, the answer is 'three', unless you want to somehow argue against Jim's reasoning, in which case, there is a potential 'four'.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Tony,

I'd love to hear what's wrong with Corey's article. I just read through it and aside from failing to mention additional complexities due to class loaders, I didn't find any "untruths."

My two cents in this debate, by the way, is that the correct answer is actually not one of the given choices -- it's six: two StringBuffers, one String, and three arrays of char. This just points out, as has already been said, how silly this kind of question is.


[Jess in Action][AskingGoodQuestions]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The "array of char" is an implementation detail; it is not specified behaviour anywhere. A loosely defined context is assumed, but ultimately, I agree, the question is poor, however, that doesn't stop it from appearing on the exam.

I have written an informal refutation of that article on this forum somewhere; I will try to relocate it.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

I will try to relocate it.

I give up. No amount of googling or using this forum's search feature revealed it.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Here (see April 29, 2005 04:21 AM). For what it's worth, the search I used was for the word "literal" in this forum, for member 57677.

Tony: feel free to follow up on the later posts, as I have yet to see any evidence you ever actually understood what I was saying. I was rather disappointed - I took your "I can prove it" literally, and was looking forward to seeing some sort of new example or test case which would expand my knowledge of how the JVM worked. Instead it seems that you never bothered to understand what I had been saying at all, and simply assumed (erroneously) that it was covered by your previous examples. Key point here - as I said, try running any of your past examples using the -verbose:gc option. You will see clear evidence when a class is unloaded. If a class is unloaded, and another class is then loaded from the same definition, those two classes are not in the JVM at the same time. Your previous examples (as far as I've seen or remember) all involved unloading a class before loading a new one (with a separate classloader). If you've got some specific counterexample (where "counter-" implies you've actually understood what I was saying, in order to counter it) then I'd love to see it.

As for the article by Corey, I'd meant to get around to further questioning some of your assertions, but was so disillusioned by the poor response to what I'd posted so far that I gave up in frustration. Corey's article may not be perfect, but it covers many aspects of literals and GC quite qell, I think. Certainly it's possible to improve upon it, but I think that would have to be done by someone capable of reading and understanding what is actually said, without filling in details from their own preconceptions.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
My apologies for not responding to your post on that thread.
I have no excuses, or those that I do, are not worth mentioning.
I do indeed recall reading your post and reasoning, and I certainly concede on the point that was at hand (that you have just paraphrased).
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Originally posted by Tony Morris:

The String instance will exist in the pool well before that code executes (at class load time), therefore, always at least three. Two String literals may exist as different instances under two different class loaders, but as Jim points out, this 'corner case' is really irrelevant given the code line numbers (and therefore, impossible to exist under separate class loaders). Therefore, the answer is 'three', unless you want to somehow argue against Jim's reasoning, in which case, there is a potential 'four'.


I understand the string literal is pooled at create time and was including that as one of three objects. That doesn't preclude the literal already being in the pool in which case two objects are created:

So, you have two or three.

In terms of 4, that's not possible as I mentioned and as you reiterated. One class is not going to have string literals in more than one class loader.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
To clarify: should have said literals are pooled at class load time, not "create" time which is ambiguous.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

One class is not going to have string literals in more than one class loader.

That's slightly ambiguous, due to the potential way of interpreting the term 'class'. If you interpret it as 'the thing that is loaded by a class loader', then certainly, only one class can exist per class loader, and therefore, only one instance of the String object that represents the literal/constant.

If you interpret it as 'the data from which a class is created by a class loader (such as a .class file)', then two, three of infinity instances representing the same String literal/constant may certainly exist.

Simply put, there is a one to one mapping of class loader to String literal/constant (if a class could be unloaded, then this assertion might not hold true, but it can't), and therefore, two or more class loaders may hold two or more String instances representing the same String literal/constant that exists in the class bytecode.

I think this topic is very very dead anyway. I attempted an explanation to hopefully put it to rest, but I now concede that it was in vain. For the record, http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How many objects created?