Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how many objects are created

 
Praveen palukuri
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
here is the porblem

String s1 = "aaaaaaaa";
String s2 = s1;

now tell me howmany objects are created.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An assignment question perhaps?

How many do you think are created? Tell us and someone will tell you if you are right.
 
jaspal singh
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
srings are actually immutable, i.e. once allocated memory they cannot be change.and this feature is actually used to share string contents with other variables.so s2 can point to s1 and ultimately only one object is created.

infact if we have string s1="hello world";
and s2 as a substring of s1 then to only 1 instance is created.

i hope ur not confused now...or more confused...
 
Andyjr Robinson
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am happy that in the first example only 1 object is created but I am interested in the later comment that substrings share the same object as the orginal.

I could see why they might as strings are immutable, but would this actually happen or would another object consisting of the substring be created ??
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a fan of checking out the source code to see what happens,
rather than resorting to idle speculation. Here is some code
from String:

Now the poster's comment "s2 as a substring of s1 then to only 1 instance is created."
is confusing. I certainly don't know what he was trying to say, But if
I let code do the talking:

In this code snippet, that are two distinct string objects (referred to by s1 and s2)
but that share the same char[]. The fact that substring can result in char[] sharing
can either be a good thing or a bad thing. It's good if sharing gains you efficiency,
but what if you've got a big String and all you want to do is refer to a bit of it
and throw away the rest? String sometimes maligned constructor String(String original)
can help. For why it can be useful, check out its source code, too:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic