String Constant pool

String Constant pool:

String constant pool is a separate block of memory where the string objects are held by the JVM.If String object created directly, using assignment operator as : String s1="hello" ,then it is stored in string constant pool.

public class Constpool {    
    public static void main(String[] args) {        
        String str1="hello";
        String str2=new String("hello");
        if(str1==str2)
            System.out.println("Both are same");
        else System.out.println("Both are not same");
    }
}




The above program is executed, then the results will "both are not same" because of  these reasons.

String str1="hello";

When the JVM executes the above statement, it creates an object on the heap and stores "hello"  in its memory. A reference number, say 23e45b4 is allotted for this

object.

String str2=new String("hello");

Similarly, when the following statement is executed, the JVM will create another object and hence allots another reference number to it, say 21r343f. So the if

condition like if (str1==str2) will compare reference numbers, that is  23e45b4 and 21r343f.Both are not same and hence the if condition gives us false value.
To achieve this problem we have to use "equals()" instead of "==" or we create both string using the "=" sign then you compare the strings using the if condition. 
public class Constpool {    
    public static void main(String[] args) {        
        String str1="hello";
        String str2=new String("hello");
        if(str1.equals(str2))
            System.out.println("Both are same");
        else System.out.println("Both are not same");

    }
}