String Class in Java

Price: INR 1,299.00
Was: INR 1,799.00

The String class in java is the most popular class in the Java library. The string is a sequence of characters. i.e “Java” is 4 character string.
String class encapsulates under the java.lang package. The string is immutable it means once a string object is created it cannot be changed.

String class is used to create the object of the string.


Immutable Objects :

An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper class’s objects are immutable in Java.


How to Create String in Java

We have two ways to create the String in Java.

  • Using String literal

  • Using new keyword


Using String Literal :

Java has the shortest way to create String. We can create the string by assigning a string literal to the string object. Like this –

String msg = “Hello, Friend” ;

As we all knows String is an object in Java. When we use String literal compiler creates a string object having the string literal and assigns it to the provided string instances. Suppose you are doing this –

String msg = “Hello, Friend” ;

String msg1 = “Hello, Friend” ;

In the above case compiler will create the object for the string literal “Hello, Friend” and assign the “msg” reference to this object. As compiler switch to next line  it will find the same string literal but the object already exists for the String so compiler does not create a new Object rather it assigns the same old object to the new instance, that means even though we have two string instances above(msg and msg1) compiler only created on string object (having the value “Hello, friend”) and assigned the same to both the instances.

If you want to have two different objects with the same string then you would need to create strings using the new keyword.

But we use prefer String Literals because it is more memory efficient.


Using new Keyword:

We know String is a class in Java so we can create the object of the class. To overcome the problem with Java Literals we can use the new keyword to create the String objects.

  String msg = new String(“Hello, firend”);


Automation Testing Video Tutorial:


How String Objects Stored in the Memory

When you create a string object using string literal that string literal is added to the string pool, if it is not present there already

     String msg = “Hello, Friend” ;

Java String

And, when we create another object with the same string, then a reference of the string literal already present in string pool is returned.

   String msg = “Hello, Friend” ;

   String msg1 = “Hello, Friend” ;

Java String

And, when we create objects using the new keyword. The compiler creates the new object for the new reference.

    String msg = new String(“Hello, firend”);

    String msg1 = new String(“Hello, firend”);

Java String

0 Comment

Leave a Reply