Java: == vs .equals

	public static void main( String[] args )
{
	    String string1 = new String( "Hello" );
       String string2 = getString();	
	    System.out.println( string1 == "Hello" );
	    System.out.println( string2 == "Hello" );
	    System.out.println( string1.equals( "Hello" ) );
	    System.out.println( string2.equals( "Hello" ) );
	}

	private static String getString()
	{
     return "Hello";
}

So this code returns false true true true
I understand that “string1” is instantiated as a string object. “string2” is instantiated as an occurrence of the “getString()” method that returns the string “Hello”, and that these two values have different locations in memory.

The == operator returns reference comparison between two objects, while the equals() method returns a value comparison. What I don’t know is where in memory is string1? Do string objects now have the same location as the string literal they represent? How come this method (getString()) has the same location in memory as the string “Hello”?

Hello!

That’s an optimization of the compiler, where every string literal is searched on the code, then pooled and, finally, searched for; if found, the reference is returned.

The same happens with the method, which is returning a string literal too.

Think of string literals as a unique list of strings; that list would be the pool.

This process is called interning.

string1 is an object, which creates a new reference every time (a new space is allocated), hence it will never be equal to a string literal.

Does it help?

1 Like

Yes, so to summarise, objects are allocated somewhere different in memory from the string pool? And this method returns a string literal, from the same string pool as simple “Hello”?

1 Like

Yes, every object has its own memory space, even strings. Just remember that String literals are pooled, whereas a new String("...") is not (that’s an object).

Yeah, it would be retrieved from the pool :slight_smile:

1 Like

Understood, thank you!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.