Home > Uncategorized > When == return true in String comparison?

When == return true in String comparison?

In java String objects are pooled for performance issue. There are two different moments during which new strings are inserted into the pool. During compile time, literals are inserted into the pool so you could(but you must not) use == to compare two literals. At runtime, strings aren’t pull back from the pool… So e comparison between a literal value and a runtime value MUST use equals(). To decrease the memory footprint we can use the intern() method, which returns the string from the pool if it exists otherwise it will be inserted.

public class Test {
//to run with a a
public static void main(String[] args) throws Exception{

String literal1 = "a";
System.out.println("arg[0] = " + args[0]);
System.out.println("arg[1] = " + args[1]);
String runtime1 = args[0];
String intern1 = args[1].intern(); //retrieved from pool
String literal2 = "a";
System.out.println("literal1==runtime1: "+(literal1==runtime1)); //false
System.out.println("literal1==literal2: "+(literal1==literal2)); //true
System.out.println("runtime1==intern1: "+(runtime1==intern1)); //false
System.out.println("literal1==intern1: "+(literal1==intern1)); //true
System.out.println("literal1.equals(runtime1): "+(literal1.equals(runtime1))); //true



Categories: Uncategorized
  1. hifly81
    November 16, 2009 at 11:12 am

    change you wordpress theme anyway!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: