Java String literal vs String Object



String Object
In string object new keyword will be used to create an object, the object will be created in Heap memory and its reference will be pointed to String pool.
String s1=new String("Candid");


String Literal
In String literal the referance will be directly refered to String Pool, refer the below diagram.
String s2="Candid";

                

To verify s1 and s2 are refering two different places use == to check it.
System.out.println(s1==s2); // returns false

To verify s1 and s2 are refering same value "Candid" use their hashcode function
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
the above code gives you a same result.

Complete Code
package stat;

public class SampleString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String s1=new String("Candid");
		
		String s2="Candid";
		
		System.out.println("value of s1  " + s1);
		System.out.println("value of s2  " + s2);
		
		System.out.println("s1==s2  "+(s1==s2)); 
		
		System.out.println(s1.hashCode()  + "   " + s2.hashCode());

	}

}
Output:
value of s1  Candid
value of s2  Candid
s1==s2  false
2011111119   2011111119



Comments


©candidjava.com