Strings

String

A. Creation

Strings are formed from 1 or more number of characters and are enclosed in ” from both sides.

Example:

String stringVariable = “Ramesh”;

Strings are stored as object in the memory.

There are two ways of creating a String

Method 1. String myString =”Hello”;

In the Method 1 , if the String “Hello” is not in the String constant/literal pool, then JVM creates a String object with value “Hello” and places it in the String constant pool .  The reference variable “myString”  gets the reference of the newly created object in the String constant pool.

Number of objects created = 1;

String

 

 

However, if the   String value “Hello”  is in the String constant pool, then no new object is created and the variable points to existing object in  the String constant pool.

Number of objects created = 0;

String2

Method 2. String myString = new String(“Hello”);

In the Method 2, it creates an object on the heap memory  with String value “Hello” and the reference variable points to the object on the heap memory.

Now if a String with same value exists in the String constant pool, it will not create an object in the String constant pool.

Number of objects created = 1;

String

 

However , if a String with same value doesnt exist in the String constant pool, it will create a String object to be placed in the String constant pool also.

Number of objects created =  2

String

 

B. Immutability & Operations

Strings are immutable. It means that when a String with a given value is created, its value cannot be changed.

String

StringHence, as can be seem from the figure, the String objects once created cannot be changed in their value.

 

Leave a comment