Monday 16 January 2012

Java : What is an intern() ?

intern() is a method in java String.
JVM has a memory pool for Strings. intern() checks for a entry for the string the particular string in memory pool.
What is a memory pool then ?
When we instantiate a String as String name = "Lucky";  "Lucky" will be into memory pool.
On saying String anotherName = "Lucky", the memory pool will be scanned and the anotherName will be refered to the "Lucky" which was created early.
On saying String nextName = new String("Lucky"); we skip the memory pool scanning and we are creating new instance for the string.
So intern() ?
When we say "Lucky".intern(); the String "Lucky"  is verified with memory pool. If it exists it returns the same string, else it creates an entry in the pool for the same and returns the string.


Some Examples:

  String name1 = "Lucky";
String name2 = new String("Lucky");
System.out.println("Without intern() returns : "+( name1 == name2));
System.out.println("with intern() returns : "+ (name1 == name2.intern()));




Java : Static Import statements.

Importing the static class is use full instead using them all the time we use them to call their static methods.

E.g:

import static org.junit.Assert.*;

The above helps in using Assert methods directly into the code as below,

A sample class from Junit.

package com;

import static org.junit.Assert.*;

import org.junit.Test;

public class WelcomeTest {
@Test
public void testSayHello() {
 Welcome welcome = new Welcome();
 assertEquals("Hello", welcome.sayHello());
}
}