Skip to content
October 28, 2008 / Ben Chun

Java’s == versus .equals()

I went to show this today:

class StringTest {
	public static void main( String[] args ) {
		String a = "hello";
		String b = "hello";
		if ( a == b ) {
			System.out.println( "==" );
		else {
			System.out.println( "not ==" );

And I fully expected these to be not == to each other, because == compares the values contained by the variables, which in this case are references to String objects, and these are clearly different objects. They just happen to contain the same letters. This distinction between how Java behaves with regard to primitives versus object instances is something that often trips up new programmers, because we feel like we have to express the same semantic concept (comparison) in two different ways.

So imagine my surprise when running this resulted in the output ==. I did a little digging around and found out that Java actually optimizes allocation of String literals and will indeed point two variables at the same location in memory if the Strings are identical. So I changed my example:

		String a = "AP Computer Science";
		String b = "AP ";
		b += "Computer Science";

Now we have the situation that a.equals(b) but yet it is not true that a == b. I feel like this became an even better illustration of how == means something different than .equals() and instead of just learning by rote that “when comparing Strings use .equals instead of ==” my students actually got to understand the reason why. This simple example is now a platform for them to jump off and answer all their own questions that come up, while diverting the frustration of needing to express the same idea with different syntax into an exploration of how Java’s implementation of String object creation works.


One Comment

Leave a Comment
  1. a1979shakedown / Oct 29 2008 8:22 am

    Hm. Interesting, I did not know that about Java.

Leave a Reply

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

You are commenting using your 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: