java check equality of strings code example

Example 1: java how to compare strings

System.out.println("hey".equals("hey")); //prints true

/*
	always use .equals() instead of ==,
    because == does the compare the string content but
    loosely where the string is stored in.
*/

Example 2: java test if strings are equal

//This expression is true if str1 and str2 are equal, and false if they're not
str1.equals(str2)

//example use case:
String location = "London";
String destination = "London";
if (location.equals(destination)) {
	System.out.println("You have arrived!");
}

Tags:

Java Example