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.
*/
class scratch{
public static void main(String[] args) {
String str1 = "Nyello";
String str2 = "Hello";
String str3 = "Hello";
System.out.println( str1.equals(str2) ); //prints false
System.out.println( str2.equals(str3) ); //prints true
}
}
******Java String compareTo()******
The Java String class compareTo() method compares the given
string with the current string lexicographically.
It returns a positive number, negative number, or 0.
___________________________________________
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
___________________________________________
Collections.sort(marvelHeroes, new Comparator<String>() {
@Override
public int compare(String hero1, String hero2) {
return hero1.compareTo(hero2);
}
});
Collections.sort(marvelHeroes, (m1, m2) -> m1.compareTo(m2));
Collections.sort(marvelHeroes, Comparator.naturalOrder());
class Simpson implements Comparable<Simpson> {
String name;
Simpson(String name) {
this.name = name;
}
@Override
public int compareTo(Simpson simpson) {
return this.name.compareTo(simpson.name);
}
}
SimpsonCharacter homer = new SimpsonCharacter("Homer") {
@Override
public int compareTo(SimpsonCharacter simpson) {
return this.name.length() - (simpson.name.length());
}
};
In Java Strings, the == operator is used to check the reference of both the string objects.
Use .equals method instead:
str1.equals(str2)