• Post Reply Bookmark Topic Watch Topic
  • New Topic

string interning  RSS feed

 
V Parameswaran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class White
{
public static void main(String[] args)
{
String a = "A";
String b = "B";
String c = a+b;
System.out.print(((a+b)==(a+b)) + ","); System.out.print(c.intern()==("A"+"B"));
}
}
What should be the output of the above code snippet? Please explain with reasons.
 
V Parameswaran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's my understanding of the following line of code.

System.out.print(((a+b)==(a+b)) + ",");

First, a chunk of memory is allocated for the operand on left hand side of the equality operator and the value of (a+b) is stored in it. Next the operand on the right hand side is evaluated and checked whether the resultant values aleady exists in the memory using the intern table.

Since it exists, just a reference is maintained to the same chunk of memory.

And the equality operator eventually evaluates to true because both the operands result in the same memory location.

Kindly tell me if am right or wrong.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button to maintain indentation and to make the code easier to read.

You are correct that the intern() method puts the String into the String pool and sees whether it exists already. The compiler can predict the contents of a String if it is a compile-time constant. "A" is a compile-time constant for example. Try declaring your Strings as final and see what difference that makes.

By the way, this looks like an SJCP question: where did you get it from?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!