DEV Community

Amit Mishra
Amit Mishra

Posted on

How to force jvm to share same memory pool between two string object? intern() in java.

 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

https://www.javaoneworld.com/2021/07/java-amazing-interesting-and-cool-tricks.html?m=1

code #codechallenge

coders

coderlife

CodeIgniter

java

javadevelopment

javadeveloper

javacode

javatricks

Top comments (0)