Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final's Puzzle

 
yu yong
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final String str1 = "1";
final String str2 = "1";
System.out.println(str1==str2);

Result is true.

Why? final variable is a clone in stack. So str1 != str2 ?
 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this has something to do with Strings being immutable.

Like when you declare a String, str1 = "1";, a String object "1" will be placed in the String pool on the heap.

When you declare another with the same string value, str2 = "1";, str2 will refer to the same String object, "1", in the String pool. That's why it's equal.

[ June 25, 2008: Message edited by: Denise Saulon ]

[ June 25, 2008: Message edited by: Denise Saulon ]
[ June 25, 2008: Message edited by: Denise Saulon ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15359
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This does not have anything to do with 'final'. If you would remove the 'final', you would see that the result is also 'true'.

String literals, such as the "1" in your example, are managed in an internal string pool. If you use the same string literal in your source code more than once (as you have "1" two times), then Java is smart enough to make only one String object, and re-use that object.

So your str1 and str2 both refer to the same String object. The == operator returns true when two variables refer to the same object.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to what Jesper has told, they are treated as compile time constants as the contents of Strings are well determined during the compile time itself. That's where there are being a part of String Literal pool referring the single String object.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic