String In Java

The string is one of the very important concepts in JAVA, which everyone should know.

Now, what is a string?

The string is nothing but a collection of characters. In java, we have multiple ways to create strings, some of which are as follows.

public class MyString {
    String str1 = "Amol";
    String str2 = new String("Amol");
    char[] c = {'A','m','o','l'} ;
    String str3 = new String(c);
}

What happens internally when we create String In JAVA?

Whenever we create a String, Memory will get created in the heap area. Inside the heap, we have something called a String Constant Pool(SCP). Whenever we create an Object with literal it gets into SCP.

This SCP does not allow Duplicate values.

String str1 = "Amol";

String str2 = "Amol";

SCP will get a scan by JVM , if there is the same value there then it will not allow duplicate values in SCP.

what happens if we create an object with the new keyword,

String str = new String("Amol")

Here, Memory will get allocated in the heap and One copy of the string will get updated in SCP, but it will not be considered. It means two objects will get created once we create an Object with a new keyword.

Now, let's try to compare strings with a few predefined methods.

With (==)

public class MyString {
    public static void main(String[] args) {
        String fName = "Amol";
        String lName = "Amol";
        String name = new String("Amol");
        String name1 = new String("Amol");
        System.out.println(lName == fName);

        System.out.println(fName == name);
        System.out.println(name == name1);
        System.out.println(fName.equals(lName));
    }
}

here will give the result as true. as I am comparing objects which are created literal.

I compared a literal Object and an object which is created with a new keyword, it gives the result as false. hence literal object and object which is created with a new keyword both are different.

if I compare two objects which is created with a new keyword, it will give false

As (==) -> compares the reference address of variables.

with (.equals())

if we compare two literal objects with .equals() method it will give true as values assigned to them are the same.

if we compare object two which is created with a new keyword that contains same string values with .equals() method then it will give same value.

.equals() method comapares the values of string

Concatenation

String name = "Amol";
System.out.println(name.concat("Nagose"));

here it will not get concrete but instead, a new string will get created as AmolNagose and it will get updated in SCP As the string is not unmutable.

but if we do

String fullName = name.concat("Nagose")

here, a new string will get created and will point to the full name. and it will get stored in heap.

Whenever reference variables involve in concatenation, memory will get allocated in the heap area.