This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes count the number of objects 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 "count the number of objects" Watch "count the number of objects" New topic
Author

count the number of objects

Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
Originally posted by Jim Yingst:
We could clear it again, I suppose, but that would just be followed by another round of people asking questions without reading and understanding the preceding posts...

[ April 04, 2005: Message edited by: Jim Yingst ]



Jim, please clear our doubts. I got confused with the different answers that I'm getting here. Sorry.


Be Afraid...Be very Afraid...
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The answer is 3, 2 respectively.
Don't believe it? Get out the JVM Specification and have a read.
Still don't believe it? Get out the JLS and read some more.
Still not? Read the VM Spec again - it's clearer on this issue.
Still? Get out a profiler and *look* at it for yourself (yes that's right - you can *see* it with your own eyes).
Still? Well, what can I say? Sucks to be you

Seriously, can we please put this issue to rest?

I should clarify that in both cases, it is assumed that the same class loader was used in each case to execute both lines of code. If this assumption is false, then the answer is 3, 3 respectively.

There happy? Glad that's all sorted out and finished and put to bed and not to brought up again because it's done and finished for now.
*sigh of relief*

I am currently moving my Java FAQ and Trivia documents into a database where I can update them easier. Guess what repeatedly asked question is going in the FAQ?! Yes, that's right, will full explanation and references to the definitive source.
http://www.xdweb.net/~dibblego/java/faq/
http://www.xdweb.net/~dibblego/java/trivia/
I will be putting a 302 redirect at those URLs when I go live.
[ April 04, 2005: Message edited by: Tony Morris ]

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

Joined: Apr 29, 2002
Posts: 200
I'll summarize the answer to the numerous codes that were posted here:


Number of Objects: 3
Creates 3 objects (2 from the String pool and 1 from the constructor)


**********************************


Number of Objects: 2
Creates 2 objects (1 from the String pool and 1 from the constructor)

**********************************



Number of objects: 6
makes

"E"
"F"
"G"
"EF"
"EFG"

AND the object created by new...which is SIX not four.


**********************************



Number of objects: 2
"aa" and "a"

**********************************


Number of objects: 8

spring
spring summer
summer
fall
spring fall
spring summer spring
winter
spring winter


**********************************



Number of objects: ???
What are those objects?

I was hoping to get the answer to this question. Thanks. Anyway, if I made some mistakes in summarizing the concept that we've learned in this thread just let me know so I can edit it. I just want this thread to be a learning experience to other SCJP wannabees. Thanks again.
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
T
e
s
t
Te
Tes
Test

8 objects
am i correct
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[B][Paulo]:

Number of objects: 6

quote: makes

"E"
"F"
"G"
"EF"
"EFG"

AND the object created by new...which is SIX not four. [/B]

No, there are actually only two. One EFG for the compile-time constant expression, and one for the new String constructor. A Java compiler could include additional pooled Strings (E, F, G, maybe more) and according to a strict reading of the JLS, it should - however Sun's JDK 1.5, at least, does not include any literals whose only role is as part of a larger constant expression. Thus, EFG is the only constant expression that is actually needed in the final program, so the others are omitted.

To verify this, compile the code, then decompile it with javap -c as dicussed on the previous page. The class file does not contain any mention of E, F, or G as individual constants. It only has one constant, EFG. Thus, there's no reason for the JVM to ever create objects for E, F, or G individually.

[Parameswaran]:

T
e
s
t
Te
Tes
Test

8 objects
am i correct


No (for the same reasons just explained). There are only two objects needed here. One "Test" for the literal, which is used for variables one, two, and three - plus one for the new String() constructor, used by variable four.

Again, compile this code, and then decompile it using javap -c, and you will see that only one constant is used.
[ April 04, 2005: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
The following is a further digression into a topic that will not be asked on the exam. If you are not sure you understand all of the preceding conversation, then please do not even think about this post, as it will be too confusing.

[Tony]: I should clarify that in both cases, it is assumed that the same class loader was used in each case to execute both lines of code. If this assumption is false, then the answer is 3, 3 respectively.

The clarification is unnecessary, as the code example clearly showed the two lines of code were right next to one another. There's no way you could load one without loading the other in the same classloader. (You could load the same single class twice using two loaders, but that would give different numbers than you specify.) Also, even if the code lines were in two different classes loaded by two different loaders, it's still entirely possible (even probable) that the answers would be 3, 2 rather than 3, 3. The only way the two literal a's would not share the same instance is if the first class were unloaded, and garbage collection fully run after that, before the second class was loaded. And it seems the only way such unloading will occur is if there are no hard references anywhere to the original class. Which also seems to require that the classloader that loaded the original class must itself be available for GC. Unless all these conditions are met, the original "a" object will still be on the heap, and the string pool will still contain a reference to it, when the second class is loaded.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
As to the "E" + "F" + "G" making several objects.

the JLS says in part (emphasis mine):

String literals-or, more generally, strings that are the values of constant expressions (�15.28)-are "interned" so as to share unique instances, using the method String.intern.


Who is to say that the whole expression ("E" + "F" + "G") is not a constant expression. It is completly resolvable at compile time. It is incapable of changing during runtime. Why should it not simply equal "EFG" as it appears to do in practice, creating one object.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Steven Bell]: Who is to say that the whole expression ("E" + "F" + "G") is not a constant expression.

No one, I hope, since they would be incorrect. The whole expression is a constant expression. Within that expression, however, are three literals.

It is completly resolvable at compile time. It is incapable of changing during runtime. Why should it not simply equal "EFG" as it appears to do in practice, creating one object.

It does. As is required by the JLS. However this does not in any way contradict other parts of the JLS and API, which I've already quoted, indicating that all literals are references to interned objects. That is, EFG should be interned, but so should E, F, and G individually, according to the specs. Which again, does not really matter; I just wanted to acknowledge this deviation from what the spec says. I'm not sure what else there is to discuss on this point; I fear this conversation is in several endless loops.
[ April 04, 2005: Message edited by: Jim Yingst ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

String four = new String("E" +"F" + "G");System.out.println(four);

--------------------------------------------------------------------------------



Number of objects: 6
quote:
--------------------------------------------------------------------------------
makes

"E"
"F"
"G"
"EF"
"EFG"

AND the object created by new...which is SIX not four.
--------------------------------------------------------------------------------



**********************************


code:
--------------------------------------------------------------------------------

String s1 = "aa";String s2 = "a" + "a";

--------------------------------------------------------------------------------



Number of objects: 2
"aa" and "a"


Wrong
The answer in this case, is 2 and 1 respectively.
JLS 15.28, if I remember rightly, will tell you what a constant expression is.
"E" + "F" + "G" is a constant expression.
Still don't believe me? Grab the VM Spec. and open the resulting class file with a hex editor.
Sill don't?
Read this: http://forum.jtiger.org/posts/list/1.page
(Note that the trivia page on that forum is soon to be deprecated).
Gah, this never stops!
/me gives up.
Soni Prasad
Ranch Hand

Joined: Mar 09, 2005
Posts: 97
I think in case of

String s1 = "aa";
String s2 = "a" + "a";

only one object is created and that is "aa" in pool.

but for this case:

String temp = "A";
String five = temp + "B" + "C";

4 objects are created "A", "B", "C" and "ABC".


SCJP 1.4, SCBCD 1.3
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi

can i say that if the expression is not constant then the string object will be created for each "".
i.e

1)

String s="asdf"
String f=s+"as"

no of objects
asdf
as
asdfas

=======================
2)

String s="asdf"
String f="asdf"+"as"

no of objects

asdf
asdfas


am i correct now?
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
any one please clear my confusion???
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes, correct.
Jack Gold
Ranch Hand

Joined: Feb 04, 2005
Posts: 85
This discussion is confusing so I checked K&B, p360

Basically, when you use new to create a string, a new String object is created on the heap and another String object is placed in the object pool.

String s = new String("abc"); //2 created


The better approach is to use the following syntax. Only a String object is created in the object pool.

String s = "abc"

I cant think of a valid use for the first syntax.


SCJP 1.4<br />SCJD <br />SCWCD (Studying)
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[C]: I cant think of a valid use for the first syntax.

Such syntax is generally only used in order to construct Garbage Collection problems, in order to bypass the issue of sting pooling. (Sometimes successfully, sometimes not.) Other than that, there is only one good reason to ever use a new String(String) constructor, and it's extremely rare. So rare that it will never ever appear on any SCJP exam, and I will leave it as an excercise for any interested parties to discover.
[ April 07, 2005: Message edited by: Jim Yingst ]
Jack Gold
Ranch Hand

Joined: Feb 04, 2005
Posts: 85
Originally posted by Jim Yingst:
[C]: I cant think of a valid use for the first syntax.

Such syntax is generally only used in order to construct Garbage Collection problems, in order to bypass the issue of sting pooling. (Sometimes successfully, sometimes not.) Other than that, there is only one good reason to ever use a new String(String) constructor, and it's extremely rare. So rare that it will never ever appear on any SCJP exam, and I will leave it as an excercise for any interested parties to discover.

[ April 07, 2005: Message edited by: Jim Yingst ]


Oh, c'mon, give it up!
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
There are hundreds of justifiable reasons to use the String(String) constructor.
Granted, they are all obscure cases.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Well, this may depend on what we consider "justifiable". The one I was thinking of was resizing the backing array - e.g. if you took a substring() of a String and you're only interested in saving that substring, not the original, it may be useful to create a new String() that uses only the amount of memory required for the substring. Other than that - well I suppose when I referred to "Garbage Collection problems" I was really thinking of educational purposes in general. I should have stated that a bit more generally. E.g. it may be useful in order to discuss the difference between == and .equals(). Other than educational uses, what uses are there? I suppose you might want to use it in a test suite in order to expose a problem in which a programmer had incorrectly depended on == rather than .equals(). Or maybe to test certain details about how the compiler or JVM handle certain situations (like the infamous string pool). Any particularly interesting ones I missed?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: count the number of objects
 
Similar Threads
Strings in java.
String Concatination
how many objects will create
Objects created in memory
Reference Assignment Question