This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why would this print true?" Watch "Why would this print true?" New topic
Author

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why would this print true?