String Class


String  is a final class which is available in java.lang package  we can create string class in the ways

  • With new operator
  • Without new operator

Only string class has the facility to create the object without new operator.
v  String s1=new string(“Hello”);            //with new operator
v  String s2=”Hai”;                                  //without new operator



class St
{
public static void main(String as[])
{
String s1=new String("Hello");
String s2=new String("Hello");
String s3="Hai";
String s4="Hai";
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s2.toString());
System.out.println(s4.toString());

if(s1==s2)
{
System.out.println("s1==s2");
}
else
{
System.out.println("s1!=s2");
}

if(s1.equals(s2))
{
System.out.println("s1==s2");
}
else
{
System.out.println("s1!=s2");
}

if(s1==s2)
{
System.out.println("s3==s4");
}
else
{
System.out.println("s3!=s4");
}

if(s1.equals(s2))
{
System.out.println("s3==s4");
}
else
{
System.out.println("s3!=s4");
}
}
}

Output:


Hello
Hello
Hai
Hai
Hello
Hai
s1!=s2
s1==s2
s3!=s4
s3==s4


Difference between object creation with and without new operator: ----------------------------
When you create the string object with new operator then following things will happened: -------------

  •    String constant will be taken and will be verified in the constant pool.
  •    If the string constant is available in the pool, JVM wouldn’t place the object in the pool.
  •     When string constant is not available in the pool then string object is created and will be placed in the pool.
  •    One more string object will be created and place outside the pool.
  •    Address of the string object which is outside of the pool will be assigned to the reference variable.
When you create the string object without new operator then following things will happened: -------------

  •    String constant will be taken and will be verified in the pool.
  •    String constant is available in the pool then same address will be assign to the reference variable.
  •    If the string constant is not available in the pool then new object will be placed in the pool and its address is assign to the reference variable s1.
  •    If you want to point the reference variable s1 to the string object inside the pool call intern()method on s1                                            
  

2 comments :

  1. informative post indeed... I was looking for such post... I'm all new to this world and being enrolled in a core java course at http://www.wiziq.com/course/1617-core-java-for-beginners-icse-students was looking for such valuable insights.. thanks :)

    ReplyDelete
  2. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we are Java training institutes in Chennai who also provide placement services to our students.

    ReplyDelete