Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

No. of string instances

 
Ravinder Rana
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:



Now, suppose 10 threads are concurrently executing this method. How many instances of String "Teacher", "Prof", and "Lecturer" will get created - 3 or 10*3??
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Three; it doesn't matter how many threads call this at the same time or how many times you execute the code. String literals are pooled.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper Young:
Three; it doesn't matter how many threads call this at the same time or how many times you execute the code. String literals are pooled.


And even if String literals weren't pooled, it would still be three, because every literal exists only once in the byte code.
 
Sidd Kulk
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what about non-String objects? Say, for example, StringBuffer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic