String in Java

Spread the love

In Java String is an object containing a sequence of characters. Probably the most important and the most used class in java.

How we instantiate it?

String s = “Java”; //#1

String s1 = new String(“Java”); //#2

So what is the difference between the two?

#1 will create a string with value java in the string pool if a string with the same value as Java is not present in the pool.

String Pool in java is a pool of Strings stored in Java Heap Memory. It is used for memory optmization. So for example if another string as String a = “Java”; is created, it will check in string pool if a string with same value exists or not. If it exists, the new string a would point to the same string reference.

#2 would create an separate instance of string object not inside the string pool. It would create in the heap space.

String Intern:

Intern is a method in the string class. It’s objective is to return the string created in the java heap space into string pool.

String s1 = new String(“Java”);

So in the above case, string object s1 created in the heap if called with intern method would return the reference from the string pool.

Now, when we are calling s1.intern()JVM checks if there is any string in the pool with value “java” present? Since there is a string object in the pool with value “java”, its reference is returned.

s1 = s1.intern();

So here s1 is pointing to the value Java present in string pool.

Is String immutable?

Yes, string in java is immutable.

For example if String s = ‘Test’; It would be added into string pool and will have a particular memory reference there.

then we update the value as s = ‘Test2’;

Here the value ‘Test’ and the memory and also the reference which was allocated to it will stay as it is. Another memory allocation would be done for value Test2 and s will point to that.

Hence it is said string is immutable because we couldn’t change the value Test.

If it was immutable, the value would have been updated in the same memory allocation itself and Test would have been replaced with Test2.

Now lt’s look at an example to clear the things finally.

 public class StringTest {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = new String("Java");
        String s3 = "Java";
        if (s1 == s2) {
            System.out.println("s1 and s2 equal");
        } else {
            System.out.println("s1 and s2 not equal");
        }
        if (s1 == s3) {
            System.out.println("s1 and s3 equal");
        } else {
            System.out.println("s1 and s3 not equal");
        }
    }
}

O/p:
s1 and s2 not equal 
s1 and s3 equal

These are the basics of String class. Read the java documentation.