A String literal is a sequence of characters between quotation marks, such as "string" or "literal".
Why do we need String literals?
As Strings are immutable(unchangeable) they can be shared i.e. referencing one object with many references so that we can use the memory effectively.Storage of String literals and String objects : String literals are stored in String-pool(Collection of Strings) and the String objects are stored in the heap memory. Each time when you create a String literal JVM first checks whether the String is available in String-pool if the same String exists in String-pool then no new String object is created just the reference is changed. But it is not the case with String objects each time when you create Sting object using new key word each time a new object of type String is created.Creating String literal and String objects : String literals : String s = "MeritCampus"; String s1 = new String("MeritCampus"); s and s1 are having same content they are not equal because s is referring to a String literal and s1 is referring to a String object.
Stringlilteral Demo CODE class StringlliteralDemo OUTPUT literalone and literaltwo are 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 THINGS TO TRY
|