0

How String instance methods such as isEmpty and toUpperCase being called without creation of String Object.

"myString".toUpperCase();

since toUpperCase is not static method, how its being called without creation of new String()?

sea29ram
  • 23
  • 4
  • 1
    Does this answer your question? [Strings are objects in Java, so why don't we use 'new' to create them?](https://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them) – Ayush Aug 11 '20 at 06:54

1 Answers1

0

A string literal like "myString" does create a String object¹, even if you don't explicitly see a new String() call in the code. Consider String s = "myString"; which couldn't work otherwise! So you can call any method on it as usual.


¹ Or reuses an existing one, see string pooling.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • https://meta.stackoverflow.com/questions/357021/reputable-people-keep-answering-duplicates-whats-the-solution – Ayush Aug 11 '20 at 07:22
  • @Ayush I believe this is a different question than [the one marked as duplicate](https://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them), although they are strongly related: "why do I seem to get a String object even though I didn't write new" shows that the asker did _not_ know that a literal creates a String, whereas "why do we not use new to create String objects" shows that the asker _did_ know that fact. – Thomas Aug 11 '20 at 07:27
  • @Ayush That said, I may have been guilty of answering duplicates and will be more careful about it in the future, thanks for bringing it up. – Thomas Aug 11 '20 at 07:31
  • That's alright, although regardless of the OP knowing it or not, they would have, after reading the dup. It's marked as a dup now anyway so it's all good. – Ayush Aug 11 '20 at 07:49