Working of String

According to Oracle String in Java are sequence of characters and are represented by a class java.lang.String.
So in simple words String in Java are objects.

Declaration for String class looks like this

public final class String extends Object

String in Java are of nature Immutable as they are declared as final.
String can be declared in multiple ways in java
For example

String str="Java";

In this case str is a String literal as it is declared directly using = sign.
While execution JVM creates a String object and store it in Object Heap.

Other way of Declaration 

String s=new String("Hello");

char[] charArray=new char[]{'s','u','c','c','e','s','s'};

String s1=new String(charArray);

An important concept which many people don't take notice of is the following situation.

String str="java";

String is of nature final and final objects can change their reference. 
So what happens when we print this and how many String objects are created in this process.

String Reference Management

On the very first line.
String str="java";
JVM created a new object with value "java".

When we concat other String "withz.in" in the original String str. 
But as String is of nature final it cannot make changes in the same object reference, hence it first creates a new object "withz.in" and then concat the other two Strings and create a new String "javawithz.in" and we have used assignment operator 


Now str points at the third object created and first two objects lies unidentified in Heap and when we print we print it we get output as "javawithz.in"

Now let us take another example for understanding the same concept

String str="java";

String Reference 

Now in this case when the first line got executed JVM created a new String object "java" and str was pointing at the same object.
Then we did


This created a new Object with value "JAVA" but as we haven't used any assignment operator str is still pointing at old reference and not the new.

So when we print it we will get "java".


Post a Comment