aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final's Puzzle Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final Watch "Final New topic
Author

Final's Puzzle

yu yong
Ranch Hand

Joined: Mar 09, 2008
Posts: 44
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 ?


Yours sincerely,<br />yuyong<br /> <br /> <br /> E-mail:yuyong22@hotmail.com<br /> msn: yuyong22@hotmail.com<br /> Skype:yuyong88
Denise Advincula
Ranch Hand

Joined: Jan 01, 2007
Posts: 160
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 ]

SCJP/OCPJP 6 | SCWCD/OCPJWCD 5 | OCMJEA in progress...
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14274
    
  21

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

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.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Final's Puzzle