Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why would this print true?

 
Ronnie Phelps
Ranch Hand
Posts: 329
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic