aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why would this print true? 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 "Why would this print true?" Watch "Why would this print true?" New topic

Why would this print true?

Ronnie Phelps
Ranch Hand

Joined: Mar 12, 2001
Posts: 329
public class Myclass{
public static void main(String[] args){
String str = "abc;"
Sring str1 = "";

System.out.println(str == (str1 + str2).intern());
lee dalais
Ranch Hand

Joined: Feb 28, 2001
Posts: 67
hi Ronnie
this is from the java string API:
"When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true."
Ishaan Mohan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
String str = "abc;"
Sring str1 = "";
str1+str2 : Constructs a new string on heap(Not string Pool)
(str1+str2).intern() : Put this string in a string Pool not on heap.
System.out.println(str == (str1 + str2).intern());
As they are pointed to same string in string pool therefore it prints true.
If you remove intern() it will print false.
It is sorta covered in the JavaRanch Style Guide.
subject: Why would this print true?