DEV Community

Amit Mishra
Amit Mishra

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay