This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes No. of string instances Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "No. of string instances" Watch "No. of string instances" New topic
Author

No. of string instances

Ravinder Rana
Greenhorn

Joined: Dec 07, 2006
Posts: 19
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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Sidd Kulk
Ranch Hand

Joined: Feb 20, 2007
Posts: 152
And what about non-String objects? Say, for example, StringBuffer.
 
jQuery in Action, 2nd edition
 
subject: No. of string instances
 
Similar Threads
Equals Method, greatherThan lessThan methods
Converting Infix to Postfix Expressions
Flow Control
How to sort a Map with Enums
[Hibernate] One-to-many batch updating?