1String myStr1 = "Hello";
2String myStr2 = "Hello";
3String myStr3 = "Another String";
4System.out.println(myStr1.equals(myStr2)); // Returns true because they are equal
5System.out.println(myStr1.equals(myStr3)); // false
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}
1******Java String compareTo()******
2
3 The Java String class compareTo() method compares the given
4 string with the current string lexicographically.
5 It returns a positive number, negative number, or 0.
6 ___________________________________________
7 if s1 > s2, it returns positive number
8 if s1 < s2, it returns negative number
9 if s1 == s2, it returns 0
10 ___________________________________________
11
12
1if (aName.equals(anotherName))
2 {
3 System.out.println(aName + " equals " + anotherName);
4 }
5 else
6 {
7 System.out.println(aName + " does not equal " +anotherName );
8
9 }
1// These two have the same value
2new String("test").equals("test") // --> true
3
4// ... but they are not the same object
5new String("test") == "test" // --> false
6
7// ... neither are these
8new String("test") == new String("test") // --> false
9