How to make Strings storing identic values share the same memory allocation with the intern() method
Coding River
How to make that Strings storing identic values share the same memory allocation using the Java intern() method
In this video, we will talk about the intern() method, that we use to get a String from memory if it is already present. The method makes sure that all the same Strings share the same memory. Let me take an example to better explain this concept Let’s say that I have declared a String value String str1 = “Coding River”;
And I would like to assign the same String value to another variable by using the intern() method String str2 = str1.intern();
What has happened is that, when the intern() method executes, it searches the memory pool for the specified String variable str1. And if the given String is found then the method will return its reference and store the String value in the new variable str2.
Now, if we print the variable str2, you will see that it will return Coding River System.out.println(str2); In the console, the output is : Coding River
One important note we have to make here is that, Java automatically interns String literals. This means that whenever we create Strings using string literals instead of creating them using the "new" keyword, Java will automatically apply the intern() method
Let’s take an example to explain more about this point I will start by declaring String variables using string literals String str1 = “Hello”; String str2 = “Hello”;
And if we check whether the two Strings are equal, it will return "true" System.out.println(str1 == str2);
And also if we apply the intern() method and compare the Strings String str3 = str1.intern(); System.out.println(str1 == str3); System.out.println(str2 == str3);
The console will output : true We will still find that the Strings are equal, meaning that they are pointing to the same memory location.
But if we declare a String variable using the "new" keyword we will find out that all the above Strings will be different from the new String str4
String str4 = new String(“Coding River”); System.out.println(str1 == str4); System.out.println(str2 == str4); System.out.println(str3 == str4);
The console will output : false
This is because we have used the new keyword, and what this keyword does is that it will create a new String and store its value in a different memory location. So, that’s the raison why, when we compare the Strings they are returning false because in reality they are not stored in the same memory location.
#codingriver #java #programming ... https://www.youtube.com/watch?v=nXcScsEKiFY
11725497 Bytes