The golden rule
To check if two strings have the same text, use .equals():
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String password = sc.nextLine();
System.out.println(password.equals("secret123"));
System.out.println(password == "secret123");
}
}Input (what the user types)
secret123
Output
true false
The text matches, but == said false!
Think of it like this:
==asks “are these the very same piece of paper?”..equals()asks “do these two pieces of paper have the same words written on them?”. Usually you care about the words.
Remember: Compare numbers with
==. Compare Strings with.equals().
Ignoring capital letters
public class Main {
public static void main(String[] args) {
String answer = "YES";
System.out.println(answer.equals("yes"));
System.out.println(answer.equalsIgnoreCase("yes"));
}
}Output
false true
Alphabetical order: compareTo
a.compareTo(b) gives a number: negative if a comes first in the dictionary, 0 if they're equal, positive if a comes after:
public class Main {
public static void main(String[] args) {
System.out.println("apple".compareTo("banana") < 0);
System.out.println("cat".compareTo("cat"));
System.out.println("zoo".compareTo("ant") > 0);
}
}Output
true 0 true
Strings never change
String methods don't change the original string. They give you a new one. Strings in Java are immutable (can't be changed):
public class Main {
public static void main(String[] args) {
String name = "ravi";
name.toUpperCase();
System.out.println(name);
name = name.toUpperCase();
System.out.println(name);
}
}Output
ravi RAVI
Common mistake: Calling
name.toUpperCase();on its own does nothing useful – store the result:name = name.toUpperCase();