Fundamentals Of Strings

A String is nothing but just a sequence of characters. A Character may be an alphabet, a digit or any other character. Strings in Java are reference-type objects, that are immutable. An immutable object cannot be changed once it has been initialized. We can still perform operations on the String object. Each time we are need an altered String, we will be returned a new String object.

If we need modifiable string, then Java provides 2 options — StringBuffer and StringBuilder. All of the String classes are defined in java.lang package. All of them are declared as final that means none of them can be subclassed. (discussed in OOPs section).

All of the 3 String classes implements CharSequence interface. Strings are immutable but the variable that is holding the reference to the String object can be changed.

String str = "abc";
str = "xyz"; // valid

In Java, Strings should be surrounded by "double quotes". There are 2 ways to create a String using String Literal or using String Object.

String Literal

String str = "Hello World";

In the above statement, we have created a String called str with the value "Hello World" in it. While evaluating this statement, Java would first evaluate the right part of the statement and creates a String literal with the value "Hello World". This string literal is created in a special place in memory called the “String Constant Pool” or SCP. Once the string literal has been created, then it will create a variable with the name str in the stack memory that will hold the address of the newly created string literal.

Let's say, If we create another string with the same value,

String anotherStr = "Hello World";

Since the string "Hello World" already exists in the string constant pool, Java would not create another string literal, but will directly create a variable named “anotherStr” that would point to the same String literal. This is done for effective memory utilization.

If we were to compare Strings using the equality operator str == anotherStr then, it would return us true, Since both the strings are holding the same memory address.

Note - It is not the correct way to check the equality of strings using the equality operator.

String Object