1//This expression is true if str1 and str2 are equal, and false if they're not
2str1.equals(str2)
3
4//example use case:
5String location = "London";
6String destination = "London";
7if (location.equals(destination)) {
8 System.out.println("You have arrived!");
9}
1System.out.println("hey".equals("hey")); //prints true
2
3/*
4 always use .equals() instead of ==,
5 because == does the compare the string content but
6 loosely where the string is stored in.
7*/
1// compare two strings in java using String.equals() method in java
2public class EqualsMethodDemo
3{
4 public static void main(String[] args)
5 {
6 String str1 = new String("HelloWorld");
7 String str2 = new String("Flower");
8 String str3 = new String("Hello");
9 String str4 = new String("Hello");
10 String str5 = new String("hello");
11 // compare str1 != str2
12 System.out.println("Compare " + str1 + " and " + str2 + ": " + str1.equals(str2));
13 // compare str3 = str4
14 System.out.println("Compare " + str3 + " and " + str4 + ": " + str3.equals(str4));
15 // compare str4 != str5
16 System.out.println("Compare " + str4 + " and " + str5 + ": " + str4.equals(str5));
17 // compare str1 != str4
18 System.out.println("Compare " + str1 + " and " + str4 + ": " + str1.equals(str4));
19 }
20}
1public class EqualsMethodDemo
2{
3 public static void main(String[] args)
4 {
5 String str1 = new String("HelloWorld");
6 String str2 = new String("Flower");
7 String str3 = new String("Hello");
8 String str4 = new String("Hello");
9 String str5 = new String("hello");
10 // compare str1 != str2
11 System.out.println("Compare " + str1 + " and " + str2 + ": " + str1.equals(str2));
12 // compare str3 = str4
13 System.out.println("Compare " + str3 + " and " + str4 + ": " + str3.equals(str4));
14 // compare str4 != str5
15 System.out.println("Compare " + str4 + " and " + str5 + ": " + str4.equals(str5));
16 // compare str1 != str4
17 System.out.println("Compare " + str1 + " and " + str4 + ": " + str1.equals(str4));
18 }
19}