Menu
Topics Index
...
`

Stringlilteral Demo - Java Example Program


Stringlilteral Demo
class StringlliteralDemo
{
    public static void main(String arg[])
    {
        String literalone = "abc"; // LINE A
        String literaltwo = "abc"; // LINE B
        String obj_ref = new String("abc"); // LINE C
        //obj_ref = literaltwo; // LINE D
        if (literalone == literaltwo)
        {
            System.out.println("literalone and literaltwo are refering to same object."); // LINE E
        }
        else
        {
            System.out.println("literalone and literaltwo are not refering to same object.");
        }
        if (literaltwo == obj_ref)
        {
            System.out.println("literaltwo and obj_ref are refering to same object."); // LINE F
        }
        else
        {
            System.out.println("literaltwo and obj_ref are not refering to same object."); // LINE G
        }
        /*if (literaltwo.equals(s2)) // LINE H
        {
            System.out.println("literaltwo and obj_ref are having same content.");
        }
        else
        {
            System.out.println("literaltwo and obj_ref are having different content.");
        }*/    
    }
}
OUTPUT

literalone and literaltwo are refering to same object.
literaltwo and obj_ref are not refering to same object.

DESCRIPTION

In the above program we have created two String literals one String object. Whenever we create a string literal JVM checks for the created String in the string-pool if it is not found it will add that string to String-pool that is what happened at LINE A and when we created the same string at LINE B internally no object is created just the reference is changed i.e. an extra reference literaltwo is created for already existing object in String-pool that is the reason why LINE E is executed and at LINE C we created a new String object which resides in heap memory that is reason why LINE G is executed.

THINGS TO TRY
  • Uncomment code at LINE D to get LINE F executed.
    The output will be literaltwo and obj_ref are refering to same object. because we have assigned reference literaltwo to obj_ref at LINE D.
  • Uncomment code at LINE H.
    The output will be literaltwo and obj_ref are having same content. Since both literaltwo and obj_ref are having same content.

© meritcampus 2019

All Rights Reserved.

Open In App