Java - String intern() Method

String Intern method returns an individual representation for the given String object. When the intern() method get invoked on a String object, it will look up the other interned strings, and if a String object exists in the memory with the same content, it will return the existing reference. Otherwise, it will return a new reference.

Example usage of String intern:

Think about a web application with a caching layer. If cache got missed, it would go to the Database. When the application is running with the high level of concurrency, we should not send all the request to the database. Such a situation we can check whether, multiple calls coming to the same reference by checking String intern.

Code: 

String name1 = "Value";
String name2 = "Value";
String name3 = new String("Value");
String name4 = new String("Value").intern();

if ( name1 == name2 ){
    System.out.println("name1 and name2 are same");
}
if ( name1 == name3 ){
    System.out.println("name1 and name3 are same" );
}
if ( name1 == name4 ){
    System.out.println("name1 and name4 are same" );
}
if ( name3 == name4 ){
    System.out.println("name1 and name4 are same" );
}

output:

name1 and name2 are same
name1 and name4 are same



You can see that name1, name2 and name4, objects have the same reference and name3 reference is different.

Comments

Popular posts from this blog

XSLT - Modify Date and DateTime value

Integrate With Mutual Certificate Authentication based Service

Yield Price Sri Lanka - Android Application