String Class

String is not a primitive data type in java. It is a class that can store sequence of characters. String class have a number of methods to operate on string. String class object can be created using 'new' keyword or values can be assigned directly to string variable. In java all strings are stored in constant pool, that is managed by JVM.

Syntax :

	String obj =  new String("hello");
	

obj is a reference variable, which is pointing string "hello". For every string variable one object of String class will be created.

java ease creation of string object by allowing following declaration.

Syntax :

	String obj =  "hello";
	

New object is created, String hello will be stored in object and that object is referred by obj reference variable. There is a difference in these two ways of creating string object.


Program :


class str
{
public static void main(String arg[]))
{
String obj1=new String("hello");
String obj2=new String("hello");
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:Different object

This scenario can be explained better with help of diagram

'new' keyword always create new object, since both object having same values but still both object allocated in separate memory."==" operator don't check that both object having same value of not, it checks whether both object having reference of same object or not.



Now if we will see direct string object creation without using 'new' keyword. It will first check is there any existing string object if it is, then instead of creating new string object. It simply assign that object reference to new reference variable.

Program :


class str
{
public static void main(String arg[]))
{
String obj1="hello";
String obj2="hello";
if(obj1==obj2) // "==" operator checks that both reference variables are pointing to same object or not.
System.out.println("same object");
else
System.out.println("Different object");
}
}
//output:same object

When obj2 is created, in memory already one object with same value was there. java simply assigned that object reference to obj2.



both reference variable are pointing to same object, that's why output of program is same object.