Null-safe comparisons
== asks whether two references point to the very same String object; equals asks whether two Strings hold the same characters. Always compare text with equals (or equalsIgnoreCase, compareTo, Objects.equals), because == only looks right when the pool happens to share an object.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static boolean isYes(String answer) that returns true for "yes", "YES" or "Yes" (with surrounding spaces allowed) and false for null. Test it with four inputs.
Sort the array {"delta", "Alpha", "charlie", "Bravo"} first in natural order and then ignoring case, and print both.
Write a program that shows == failing for a String read from "name=Ravi".split("=")[1] while equals succeeds.
Explain it without notes
What is the difference between == and equals for Strings? Why does == sometimes give the right answer?
How do you compare Strings safely when either might be null?
What does compareTo return, and why does "Zebra" sort before "apple"?
Why is "abc".equals(new StringBuilder("abc")) false, and what should you use instead?
How does switch on a String work under the hood, and what happens with null?
Expected output
admin -> full access
null -> read only
Objects.equals(null, null): true
Objects.equals(null, x): false
Objects.equals(x, x): true
a.equals(c) threw NullPointerException