Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How Many String Object?

 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Just want to know one thing:

How many String Object are created when this method is invoked?

public void stringObject()
{
String str = "Java";
str = str + "Ranch";
}
If we see the question :: It is asking "When the method is invoked ?"

So it means that at the run time ..!!
So i think answer should be 1..as
"Java" and "Ranch" object will be created at compile time..!!
only Java Ranch will be created on the run time..!!

Please correct me..!!
 
Sid Robin
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think they are very particular about run time creation or compile time . In general three string objects are created in the pool. Correct me if am wrong

Regards
Sid
 
m prabhu
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2 objects is created in pool

1 is 'java' and assigned to 'str' refernce
2 is 'java ranch' assigned to 'str' refernce

==>the 'java' will be now abandoned in the string pool without any refernce.

i 2 not sure abot compile time and run time object creation.

prabhu
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but i think that..they consider run time and compile time..because this is the only thing that can make a string question little tricky..!!!
 
Serg Masow
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I agree with Sid there are three string objects "Java", "Ranch" and "JavaRanch". I think the question isn't about the creation of string at runtime.

regards
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously, there are three String objects getting created. But the question asks about when it gets created depends on the type of String being created.

First two string constants (literals) "Java" and "Ranch" are getting created during the class loading operation and the concatenated string (the + operator returns a new String object) causes a brand new string to be generated at the runtime.

You may have a look at these threads for further exposure in this regard.

  • String Concatenation
  • How many are objects are eligible for GC?


  • Hope this helps!
    [ January 31, 2008: Message edited by: Raghavan Muthu ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic