Comparing Strings in Java

A common mistake by new Java programers is usingĀ == for comparing Strings. Often the results are correct when using the == comparison with Strings.

String s1 = "my string";
String s2 = "my string";

if ( s1 == s2) {
	// this comparison evaluates to true
	System.out.println("Why not use =='s ?");
}

After all, == works for comparing ints. Not only does it work, but it is the correct way to do primitive comparisons.

Continue reading “Comparing Strings in Java”