Home > Misc > The ‘==’ operator for hard coded Strings in Java

The ‘==’ operator for hard coded Strings in Java

I’m pretty sure everybody who knows Java has seen something similar to the following snippet in his/her Java programming lessons:

		String a1 = new String("bla");
		String a2 = new String("bla");
		System.out.println(a1 == a2); 		// false
		System.out.println(a1.equals(a2)); 	// true

So what to expect for the following in Java?

		String a2 = "bla";
		String b2 = "bla";
		System.out.println(a2 == b2);

Of course it’s not false. Strings are a special case in Java: they have a special constructor no other class has, and creating a hard coded String via = "..."; does not just create another normal String. Hard coded Strings are known from compile time on: all hard coded Strings with the same content get stored at the same place. Therefore there is only one instance of "bla", and "bla" == "bla" will deliver true. If you don’t like this effect try the following:

		String a3 = "bla";
		String b3 = new String("bla");
		System.out.println(a3 == b3);	//false

There is a nice and short article about what the String’s copy constructor actually does, and about side effects that can occur using it (more stuff you probably wouldn’t expect).

  1. No comments yet.
  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: