• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt: Strings

 
Bunty Mann
Greenhorn
Posts: 10
Android C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I've been preparing for OCAJP 8 and I reading about strings and how they are immutable.
Now, I know the difference between the two below:



String class also has a toString() method. So when I write:



What will actually happen here? Output will be as expected: "Hello". But my doubt is, how many String objects will be here(referenced or not)?
Does this work in the same way as String literals do, like they just refer to same String in the String Constant Pool, or would a new String object be created when we call toString() method?

Thanks.

 
Tapas Chand
Ranch Hand
Posts: 583
8
BSD Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to have a look at the source code of String class.
In the source code have a look at the definition of toString() method.
Are you able to answer your question now?
 
Bunty Mann
Greenhorn
Posts: 10
Android C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Oracle Docs says:
This object (which is already a string!) is itself returned.


So, no new String object is made and the object itself is returned.

Thanks Tapas, silly of me din't check Docs before.
 
Narayana Bojja
Ranch Hand
Posts: 135
4
Hibernate Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi Bunty Mann,



The above code is the  toString() method implementation in String . By looking at the code , you can understand its functionality. It simply returns the current object without doing any action.
Go through the below example to understand clearly.



Hope this helps !
 
Bunty Mann
Greenhorn
Posts: 10
Android C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Narayana, the toString() method returns the object itself it's called upon(in case of String). and hence, result of your code will be:

true
true


because, they the toString() method returned the object itself.

Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic