Link to home
Start Free TrialLog in
Avatar of sudhakar_koundinya
sudhakar_koundinya

asked on

String related question

Hello All,

Have a look on following code. I know that for comparision of Strings, we need to use equals() method. But When I test following code, it is always prints "Hello". How come this is possible??


class String_Test       
{
      public static void main(String[] args)
      {

            String str="Hello";
            String str1="Hello";
            if(str==str1)
            {
                  System.err.println("Hello");
            }
            else
            {
                  System.err.println("Hi");
            }

      }
}
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> so any strings you will create with the same literal "Hello"

to make it clear, any Strings that you will create *without* using the "new" keyword.
If you want to have different memory addresses of course you use the following:

String str= new String("Hello");
String str1= new String("Hello");

Any String you create using the "" will be put in a string of pools, so any subsequent string you create with the same value and in the same way (using the double quotes) is taken from and put in the pool of strings.

So if the string "Hello" exists in the string pool and you craet another string with the same value then the same memory address is returned to the new string (that's why comparison with == will give true), otherwise a new string is created and is put in the pool.
Avatar of bhpr
bhpr

aggred with <girionis >
For further reading:
http://www.janeg.ca/scjp/lang/strLiteral.html

Summary

    * if String objects having the same data are created using a constant expression, a string literal, a reference to an existing string, or by explicitly using the intern() method, their references will be the same

    * if String objects having the same data are created explicitly with the new operator or their values are computed at runtime, their references will be different