Command Palette

Search for a command to run...

Back to the lesson: Topic 6.2 — == vs equals for Strings
Core Java · Example 2 of 3

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.

01

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.

02

Sort the array {"delta", "Alpha", "charlie", "Bravo"} first in natural order and then ignoring case, and print both.

03

Write a program that shows == failing for a String read from "name=Ravi".split("=")[1] while equals succeeds.

Explain it without notes

01

What is the difference between == and equals for Strings? Why does == sometimes give the right answer?

02

How do you compare Strings safely when either might be null?

03

What does compareTo return, and why does "Zebra" sort before "apple"?

04

Why is "abc".equals(new StringBuilder("abc")) false, and what should you use instead?

05

How does switch on a String work under the hood, and what happens with null?

Null-safe comparisons
Sign in to run this example in your browser.

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