String str1 = new String ("javaoneworld");
String str2 = new String ("javaoneworld");
System.out.println(str1 == str2); //false but it can be true also 🤔
/*
* as we initializing str1 and
str2 with new keyword so they
will not share the
* same memory pool
*/
System.out.println(str1 == str2); //false
But what if I want true for the above statement?
How ?
So the only way to get this is ,if somehow we force jvm to share the same memory pool to both the variable.
So is it possible?
Yes absolutely, it's possible, click on below to see how.
/*
* using the intern() method we can force both the string to share same memory
* pool
*/
str1 = str1.intern();
str2 = str2.intern();
System.out.println(str1 == str2); //true
https://www.javaoneworld.com/2021/07/java-amazing-interesting-and-cool-tricks.html?m=1
Top comments (0)