Core Java Tutorial

Core Java Tutorial

What is String literal and String Object in Java

Table of Contents

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.
  1. String s1=new String(“Candid”);

String Literal

In String literal the referance will be directly refered to String Pool, refer the below diagram.
  1. String s2=“Candid”;
                
To verify s1 and s2 are refering two different places use == to check it.
  1. System.out.println(s1==s2); // returns false
To verify s1 and s2 are refering same value “Candid” use their hashcode function
  1. System.out.println(s1.hashCode());
  2. 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