Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Don't be strung along

The String class's strange behavior explained

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 2

Remember, use == to check whether two references refer to the same object. Use equals() to check whether the contents of two objects are equal. Do not assume that == will always work for testing strings!

Question 3: How is it decided?

As for Question 3, in the case of d = "hello", d points to the same reference as that pointed to by both a and b. Before the JVM creates a string literal, the JVM checks the string literal pool first. Since "hello" already exists in that pool, d will simply be set to point to that pooled instance.

String wrap up

All three questions are related because the JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. The JVM can reuse and share string references because strings are immutable and, therefore, by definition thread-safe. That's a nice design; although a design you must be aware of and treat accordingly.

About the author

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in bridging disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer, as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).
  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources