What is the output of the following code snippet, and why?

Description:

System.out.println("asd"=="asd");
System.out.println(new String("asd")==new String("asd"));
System.out.println(new String("asd").equals(new String("asd")));

Solution:

The output is:

true,
false,
true

The reason for this result is the String constant pool that Java maintains. In the first case each string is treated as a constant and stored at the String constant pool. When defining a string like this, the JVM first tries to find an item with the same value in the pool, so that's why the 2 references are the same (the constants are reused from the pool).

In the second case a new instance is created for each string, so they are different by reference.

In the third case, the 2 strings are compared by value (not reference) and by value they are equal.

0 answers