Learn about the String object in Java

The String object, defined in the java.lang package, is a basic object in Java. You will use it often and it is an indispensable object for all of us when programming with Java. In this tutorial, I will present to you more depth on this String object so that you can know more about it!


Initialize the String object

We have several ways to initialize a String object:

– Use the new operator

For example:

– Use the assignment operator (“=”).

For example:

– Declare in quotation marks

For example:

The difference between these declarations is:

If you declare a String object using the new operator, Java will create separate Java objects, stored in different locations in memory.

Therefore, when you compare these objects using the relational operator (“==”), the result will be false. Let’s look at the following example:

Result

Learn about the String object in Java

If you initialize the String object using the assignment operator (“=”), then when comparing these objects using the relational operator (“==”), the result will be true.

Consider the following example:

Result

Learn about the String object in Java

What is the reason? That is because when you initialize a variable of String with the text “Khanh” using the assignment operator (“=”), Java will create a “Khanh” string stored at a specific location in the memory, called String pool. When you create other String variables with the same content as “Khanh”, Java returns the string “Khanh” that was created earlier in the String pool. And so, when you compare objects like this, the result will always be true.

For the third case, like the second case, when comparing String objects declared in quotation marks with a relational operator (“==”), the result will always be true.

Consider the following example:

Result

Learn about the String object in Java


The Immutable concept in String

Working with String, you will meet the concept: Immutable. What is Immutable? I can say: Immutable is a concept that refers to objects whose content or state cannot be altered by any other object.

The String object is an immutable object like that!

So how can the String be an Immutable object, I would like to present the following:

– String stores its value in an array variable with the char data type. This array variable is defined with the access modifier private.

– This array variable is declared with the final keyword. As you know, if a variable is defined with the final keyword, it is initialized only once.

– No method in the String object manipulates this array variable.

Details, you can see more here.

Add Comment