1

I'm new to this site and didn't realize there were other questions that answered what I'm asking. I've figured it out and I will delete this post as soon as it lets me. Thank you.

I just started learning java again and I have a quick question.

Usually, using == to compare strings would not work and you would have to use .equals instead.

But now while coding, I found they are doing the same thing when they are not supposed too and I'm trying to figure out why.

Here's the code.

String s = "Hello";
   String x = "Hello";

   if (x == s){
       System.out.println("It is working!");
   }//end if
   else {
       System.out.println("It is not working");
   }//end else

   if (x.equals(s)){
       System.out.println("Match");
   }//end if
   else {
       System.out.println("No match");
   }//end else
MrTimotheos
  • 937
  • 1
  • 10
  • 18
  • 3
    Well done, OP, you've posed the most frequently asked question on this site. It's listed on the [java](http://stackoverflow.com/tags/java/info) tag itself, under Frequently Asked Questions (the first entry, of course). – Marko Topolnik Feb 11 '13 at 17:07
  • Sorry. I didn't realize there were all these other questions that answered mine. I just joined this site, I'll be deleting this post as soon as it lets me. Thank you though. – MrTimotheos Feb 11 '13 at 17:23

3 Answers3

4

Basically you're seeing the result of string interning. From section 15.28 of the JLS:

Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.

So your two variable values actually refer to the same strings. If you use:

String s = new String("Hello");
String x = new String("Hello");

... then you'll see the behaviour you expect.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Reason is that your vars x and s have the same reference hence == behaves same as .equals.

When Java compiler optimizes your string values (literals), it determines that both x and s have same value and hence you need only one String object. As result, both x and s point to the same String object and some little memory is saved. It's safe operation since String is an immutable object in Java.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

well, In this particular case there is only one string object created and cached in the string constant pool and both of the reference variables refer to the same string object which is stored in the string constant pool . thus you == test passes

String s = "Hello"; Line 1 String x = "Hello"; Line 2

When line 1 is executed one string object (Hello) is created and cached in String Constant pool .

**String Constant Pool:** {s--->"Hello"}

when line 2 is executed, it first checks if there is any object with the same value in string constant pool, if there exists one. it simply points the reference to the already created object in the pool.

**String Constant Pool:** {s,x--->"Hello"}
PermGenError
  • 45,977
  • 8
  • 87
  • 106