Ask your own question, for FREE!
Computer Science 14 Online
OpenStudy (harsha19111999):

I have a question about strings in JAVA

OpenStudy (harsha19111999):

I have this program: .......... String One = "Hi"; String Two = "Hi"; if(One == Two) {System.out.println("String 1 is equal to String 2"); So, this works. Then why do we use equals() method for finding the equality of strings?

OpenStudy (harsha19111999):

@Abhisar @texaschic101 @ganeshie8 @Zale101

OpenStudy (harsha19111999):

@Zarkon @Destinymasha @sammixboo

OpenStudy (harsha19111999):

@Compassionate @kirbykirby @LolGoCryAboutIt

OpenStudy (lyrae):

This is only true in some cases, and is caused by of something called string interning. It's a method used to save space and speed up certain operations. At compile time each declared string will be created as a constant. After the string constant is created java tries to add the string to a string pool. If there's a string with exactly the same value already present in the pool, the new string won't be added. By doing this we avoid having duplicate string constants. Interning works because the string object is immutable (a pooled value cannot change). It's possible to perform interning on other immutable as well (although I'm unsure if java does this automatically). The problem is that interning isn't performed on objects created during runtime, which is why you have to use .equals() and not reference comparison. Consider the following case: ``` import java.util.Scanner; class StringTest { public static void main (String[] args) { Scanner in = new Scanner(System.in); String str1 = "foo"; String str2 = "foo"; if (str1 == str2) System.out.println("Same reference because if interning."); if (str1 == in.nextLine().trim()) System.out.println("True."); else System.out.println("False."); } } ``` this returns ``` Same reference because if interning. False. ``` with std input: ``` foo ``` Runnable example: http://ideone.com/LJMxZp You can get more info on this topic at Wikipedia: http://en.wikipedia.org/wiki/String_interning

OpenStudy (harsha19111999):

Thank you Lyrae

OpenStudy (lyrae):

Yw! Anytime ^^

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!