permaculture playing cards*
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
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

pooja jain
greenhorn
Ranch Hand

Joined: Jan 12, 2005
Posts: 213
I have very simple but debatable questions :

Count the number of objects :

1]

String s1 = "a";
String s2 = new String("b");

------

2]

String s1 = "a";
String s2 = new String("a");


Thanks .


:d
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
Hi, Pooja -

I don't see a question here. What are you asking? What are your own observations about the conditions that confuse you?


Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
pooja jain
greenhorn
Ranch Hand

Joined: Jan 12, 2005
Posts: 213
In first case : 3

In second case : 2
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
IMO you are right .
But in this fourm only , I read that String Literals Pool doesn't contains objects , it contents reference to objects ...
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
There are two objects in each case.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[rathi]: But in this fourm only , I read that String Literals Pool doesn't contains objects , it contents reference to objects ...

Yes, and...? The string pool contains references to objects, and the objects themselves exist on the heap. But the objects do exist somewhere. The question wasn't about where the objects exist; the question was how many objects exist.

[Steven]: There are two objects in each case.

I disagree; I say in case 1 there are three. There's one object created for the literal "a", one for the literal "b", and one for the new String(). The first two are created when the class is loaded (unless they were previously created and pooled by some other class, and not GC'd). The third is created when the new String() is executed. Which part(s) of this do you disagree with?


"I'm not back." - Bill Harding, Twister
kiennjal shah
Ranch Hand

Joined: Jun 17, 2004
Posts: 31


There are only two objects created on the heap in both the cases: s1 and s2.

Your code will not create two String objects for: String s2 = new String("b");
Kay Liew
Ranch Hand

Joined: Dec 26, 2003
Posts: 112
I see 3 for each case. I might wearing my grandma's glasses.


Unity can only be manifested by the Binary. Unity itself and the idea of Unity are already two.
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
Hi,

I have also been wrestling with this...and now I am losing sleep (hair went ages ago).

I thought that any time you see a String literal in your code, i.e something between double quotes, that has NOT appeared previously in the code, that is ONE new object created.

Moreover, when you concat two String literals together, to make something that has NOT appeared previously that is ONE new object created.

Whenever you use new that is ANOTHER ONE String object created.

Ergo:
//total of String objects = 0
String a1 = "a"; //Creates 1. Total of String objects = 1
String a2 = "a"; //Creates 0 ("a" exists). Total of String objects = 1
String b1 = "b"; //Creates 1. Total of String objects = 2
String a3 = new String "a"; // Creates 1. Total of String objects = 3
String a4 = new String "x"; // Creates 2. Total of String objects = 5
String a5 = "Q" + "Z"; // Creates 3 ("Q", "Z" & "QZ". Total of String objects = 8

Right!

Right?

:-)

Cheers,

Si.


SCJP 1.4 (93%)<br />SCJD (In progress. It can run, but it can't hide...)
Kay Liew
Ranch Hand

Joined: Dec 26, 2003
Posts: 112
//total of String objects = 0
String a1 = "a"; //Creates 1. Total of String objects = 1
String a2 = "a"; //Creates 0 ("a" exists). Total of String objects = 1
String b1 = "b"; //Creates 1. Total of String objects = 2
String a3 = new String "a"; // Creates 1. Total of String objects = 3
String a4 = new String "x"; // Creates 2. Total of String objects = 5

That's exactly what I see from my grandma's glasses.

String a5 = "Q" + "Z"; // Creates 3 ("Q", "Z" & "QZ". Total of String objects = 8

I think it should be 1 object created. I thought this should be the same concept as String a1 = "a";"
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
Hi,

I feel I am on shaky ground...I look to the sky for the big hitters on the forum to make their judgement. They know who they are...


Si.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
I didn't consider that the "b" on line two of the first section was an object seperate from the one created by new.
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
Which "b"?
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
...and while we're at it:

On its own...this makes four new objects, right?

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

1) "E"
2) "EF"
3) "EFG"

4) ANDthe object referenced by the String referenec four, which has a value "EFG".

I reckon.

Simon.
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
By the by...

K&B book (page 400, self test answer 3, which I am sure they won't mind me referring to, right guys?), says...

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

...Creates four String objects.


Cheers,

Si.
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
I was wrong earlier.

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

makes

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

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

Sorry for all the posts...

Si.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Simon, in that case I think it gets a little more questionable because the compiler can optimize away some of those objects, or use a StringBuffer in the intermediate steps.

Mainly the "EF" and "EFG" could go away.

Or a good compiler would slap you for writing code like that.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
In practice Simon, that code seems to create 2 objects: one "EFG" created for the constant expression, and another created by new String(). The individual literals "E", "F", "G" are not pooled, although technically they should be according to the JLS. ("EF" isn't pooled either, but I don't think the JLS says one way or another about whether it should be pooled.) You can see this by compiling the code and then using javap to decompile it - there are no constant entries for "E", "F", "G", only one for "EFG". At least that seems to be the case for Sun's current compiler implementation; it may be different in past or future.
[ March 31, 2005: Message edited by: Jim Yingst ]
Rahul Bhosale
Ranch Hand

Joined: Mar 10, 2005
Posts: 77
Jim,
You are the man. Thanks for the direction.
I also ran through the original example and though i knew the answer, i did run thru the javap and got a more insight into whats happening..

From the original example.

String s1 = "a";
String s2 = new String("b");

Creates 3 objects (2 from the String pool and 1 from the constructor)

String s1 = "a";
String s2 = new String("a");

Creates 2 objects (1 from the String pool and 1 from the constructor)

right?


RB
Rahul Bhosale
Ranch Hand

Joined: Mar 10, 2005
Posts: 77
also,

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

creates only 1 object and not 3.
thanks to javap and Jim.
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi ragul

String s1 = "aa";//creates one object in string pool
String s2 = "a" + "a"; //creates one more for 'a' in string pool

creates only 1 object and not 3.
thanks to javap and Jim.
--------------------
to my knowledge the number of objects should be 'two' not 'one'
Jeff Jetton
Ranch Hand

Joined: Mar 29, 2005
Posts: 71
Originally posted by Parameswaran Thangavel:
hi ragul

String s1 = "aa";//creates one object in string pool
String s2 = "a" + "a"; //creates one more for 'a' in string pool

creates only 1 object and not 3.
thanks to javap and Jim.
--------------------
to my knowledge the number of objects should be 'two' not 'one'


Yes, the number of objects should be two, in theory. But, if you scroll up and read the comments by Steven Bell and Jim Yingst, you'll see that, in practice, that's not always the case.

Apparently, a smart compiler will realize that those two "a" strings are being concatenated in a non-dynamic way. In other words, they cannot be changed by the running code, and the fact that they are being concatenated cannot be changed by the running code, so there's no reason to "hold off" the concatenation until run-time. So the compiler will do some optimization by actually doing the concatenation at compile time--without ever creating an "a" string object.

Voila! Just one string object.

- Jeff
Rahul Bhosale
Ranch Hand

Joined: Mar 10, 2005
Posts: 77
Parameswaran Thangavel,
look for yourself by running javap with the lines of code you have a surprise in store for you!
BTW, its Rahul and not Ragul.
kiennjal shah
Ranch Hand

Joined: Jun 17, 2004
Posts: 31
So according to Jim's explanation, I feel that both cases: # of objects: 2

Is that correct or not?



-Kiennjal
Rupak Khurana
Ranch Hand

Joined: Mar 01, 2005
Posts: 89
Using javap, how do I find out the number of objects created?


SCJP 1.5<br />SCWCD 1.4
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Jim: The individual literals "E", "F", "G" are not pooled, although technically they should be according to the JLS.

Jim, could you please point out which section in JLS that mentions this? I couldn't find it. Thanks. Anyway, I think in this case, they're not pooled because the whole expression is constant and hence is evaluated to "EFG" during compilation.



However, if a variable is inserted into the expression like this:



By running javap -c ClassFilename, you can see that "E", "F" and "G" are pooled.

Here is another example from Kathy and Bert's SCJP book, pg 359. The total number of String objects created is 8.


[ April 01, 2005: Message edited by: Joyce Lee ]
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Hello Tantric,

Using javap, how do I find out the number of objects created?


Corey McGlone wrote an article on javap: here.

Joyce
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Jim]: The individual literals "E", "F", "G" are not pooled, although technically they should be according to the JLS.

[Joyce]: Jim, could you please point out which section in JLS that mentions this?


From JLS 3.10.5:
Each string literal is a reference (�4.3) to an instance (�4.3.1, �12.5) of class String (�4.3.3). [...] 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.


And from the API for String's intern() method:
All literal strings and string-valued constant expressions are interned.


Not to make a big deal about this - there would be no real benefit to interning literals which are never used except as part of a larger constant expression. It's a perfectly sensible thing to omit. I'm just noting the spec and API state otherwise.
[ April 01, 2005: Message edited by: Jim Yingst ]
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Jim: there would be no real benefit to interning literals which are never used except as part of a larger constant expression. It's a perfectly sensible thing to omit.

I agree with you.
Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
So when I encounter this kind of code in the exam



and Im asked to state how many objects were created...the answer would be 2? right?


Be Afraid...Be very Afraid...
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830


and Im asked to state how many objects were created...the answer would be 2? right?[/qb]<hr></blockquote>

No , In total 8 object is getting created . I forgot "Te" & "Tes"
[ April 04, 2005: Message edited by: rathi ji ]
Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
Uh oh...I'm confused again...The 2 objects that I'm sure that will be created are:

- "Test" object from String one = "Test";
- the object that will be created when new String() from String four = new String("Test") is invoked.

where are the other four?
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
I learnt somewhere that One,Two,Three are string literals. There is only one object created in the above code it's "String four" ?
Please correct me if i'm wrong .


Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
i am using the comment to explain the no of objects(obj) created

public class StringLiterals
{
public static void main(String[] args)
{
String one = "Test";//1
String two = "Test";//2
String three = "T" + "e" + "s" + "t";//3
String four = new String("Test");
}
}


at 1) Test created in string pool.obj=1

at 2) the string created in string pool is referred.obj=1

at 3) here comes the problem.
the string objects created for T,E,S,T,TE,TES not for TEST which is reference from the heap created before.
at 4)one more object is created for new keyword.



the rule is whenever we are giving the string with in the double quotes the string objects is created,unless there exist the one previously,
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
So do you mean to say 8 objects are created ??
Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
ok, so whats the final verdict here? string immutability is really a tricky subject
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi srini

to my knowledge its eight.

Test
T
e
s
t
Te
Tes
Test(by new keyword)


any comments???
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
I dont think so . but really confused ..
As far as i know there is only one object ( may be i'm wrong ).
[ April 04, 2005: Message edited by: Srinivasa Raghavan ]
Parameswaran Thangavel
Ranch Hand

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

Joined: Jan 30, 2000
Posts: 18671
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 ]
 
Don't get me started about those stupid light bulbs.
 
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