SSJX.CO.UK
Content

Java String Equals

String Equals

The String equals method compares if two strings are the same, returning true if they are.

Comparing Strings

Comparing Strings the wrong way with '=='

When comparing Strings in Java, it is easy to think that you do the following:

String name="bob";
String another="bob";
if (name==another){
	System.out.println("Hi Bob!");
}

The problem with this is that it does not compare the String but the 'object' the String points to. There is a good chance the above will work fine as both variables will likely point to a object called "bob" but in more complex programs, it will most likely lead to errors.

Comparing Strings the correct way with the equals() method

Fortunately, comparing String is easy using the equals() method:

String name="bob";
if (name.equals("bob")==true){
	System.out.println("Hi Bob!");
}

In the above block, the '==true' part is not necessary but included for clarity. The program can be shortened to:

String name="bob";
if (name.equals("bob")){
	System.out.println("Hi Bob!");
}

Full Program

With the Java JDK installed, from a command line:

class Hello{
	public static void main(String[] args){	
		String name="bob";
		
		if (name.equals("bob")){
			System.out.println("Hello Bob!");
		}
		
	}
}

Created (10/05/2025)