Java creating string object

In the last Chapter we have seen String literal in java programming. In this chapter we are looking one step forward to create String Object in Java Programming.

In Java we can create String in two ways – One by using String Literals and another using new operator.

Way 1 : Creating String Objects using Literals

Consider the following Code Statement –

class FirstProgram {
public static void main(String[] args) {

   String myName = "PRASHAN";
   System.out.println("Hello " + myName);

   myName = "PRABHU";
   System.out.println("Hello " + myName);

Explanation :

String myName = "PRASHAN";

The above Statement will be pictorially represented below –
String Literal Assignment
Now when we assign another string literal to String Object then earlier string will be discarded.

myName = "PRABHU";

Assigning New String Literals to Object
Actual String can be stored anywhere in the heap but String Object – “myName” will locate the position of the String – “PRABHU” and stores the reference to that actual string.

Way 2 : Using new Operator

String name = new String("AKASH");

Consider the above code line –

EntityObject/VariableMemory Location
AKASHObjectString Constant Pool
new String("AKASH")ObjectNon Heap Memory
myNameReference Variable-

*Reference Variable is Pointing to a String Object – new String(“AKASH”)