Java traps · Chapter 1 of 16

== versus equals on strings

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Everyday traps
  • 3 tasks
  • Java
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

A test that calls a method with the literal "SBC" hands it the same interned object the method compares with. The test passes, the bug ships, and only real input, built at run time, shows it. Nothing throws and nothing is logged as an error: the comparison is simply false.

The usual fix is equals. Which side you call it on matters, because plenty of values are null. A seat lookup that finds no coach, in a small program run with java Codes.java:

static String coachOf(String ticket) {
  return null;
}

System.out.println("B2".equals(coachOf("PNR 4521")));
System.out.println(coachOf("PNR 4521").equals("B2"));
false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because the return value of "Codes.coachOf(String)" is null
	at Codes.main(Codes.java:8)

"B2".equals(x), or Objects.equals(x, "B2"), is safe for null. A switch on a String compares with equals too, but it throws on null.

The lesson

By the end of this case

You can tell == on strings from its symptoms, make it happen on purpose with a String built at run time, fix it with equals the null-safe way, and pin it down with a JUnit test that fails on the bug and passes on the fix.

The ticket

TC-512: The CHAI10 poster gives nobody a discount. Assigned to you by Kabir. Priority: high. Since: the poster campaign went live on Monday.

Anjali, in the counters group at 9:40 am: "We put CHAI10 posters on every platform at SBC. Passengers scan the QR, the code shows on the till, and they still pay ₹40 for a masala chai, not ₹36. Two of them argued with Lakshmi at counter 3. When the counter staff type the code in the demo app, it works. I tried it myself."

The till's log for the first scans at SBC this morning:

06:12:31  till  bill SBC-10421: offer CHAI10, 0% off, pay 40
06:14:02  till  bill SBC-10422: offer CHAI10, 0% off, pay 80
06:15:47  till  bill SBC-10423: no offer, 0% off, pay 25

Kabir: "The offer code in Offers.java has unit tests and they are green. The only new thing is where the code comes from: the till used to get it from a button, now it cuts it out of the QR text. Same letters, different journey. Reproduce it first, then fix it, then make sure it never comes back. You are in Offers.java."

Two ways to ask "the same?"

For objects, == asks is it the very same object? It compares references. equals asks do they hold the same value? String overrides equals to compare the characters. A station code read from a timetable line shows the difference (run with run-app in a scratch folder):

String typed = "SBC";
String fromLine = "SBC,07:45,Udyan Express".split(",")[0];
System.out.println(typed == "SBC");
System.out.println(fromLine == "SBC");
System.out.println(fromLine.equals("SBC"));
true
false
true

Why is the first one true? Java interns string literals: every "SBC" written in the program is one shared object. So == between two literals works by accident. split, substring, a StringBuilder, a line read from a file or a request: each makes a new String, and == is false even though the letters match.

Making it happen on purpose

You reproduce a bug before you fix it, every time. Your repro is a method, Repro.reproduce(), that runs the ticket's steps against the real code and returns what the code gave. It never asserts and never decides the answer itself. Here that means a code that arrives the way the station gets it: cut out of the QR text.

The check runs your reproduce() twice: beside the original Offers.java, where it must give the bug's value, and beside a fixed one, where it must give the healthy value. A repro that returns the answer without calling the code fails the second run. In the terminal, cd chapters/01-string-equals and run run-app: it prints what reproduce() returned.

A test that would have caught it

A guard test turns the repro into something that runs before every release. In JUnit, a method marked @Test is one test, and assertEquals(expected, actual) or assertTrue(...) checks a value. For a station lookup with the same bug:

@Test
void codeFromATimetableLineIsHome() {
  String code = "SBC,07:45,Udyan Express".split(",")[0];
  assertTrue(Stations.isHome(code));
}

run-app test runs every *Test.java file in the folder. Beside the buggy lookup, with a second test that passes the literal:

PASS  literalCodeIsHome()
FAIL  codeFromATimetableLineIsHome()
      AssertionError: expected: <true> but was: <false>
2 tests, 1 failed

A good guard fails on the bug and passes on the fix, and it covers the edges a hurried fix breaks: here, a bill with no offer at all.

Your turn

Three tasks, one file each. In Repro.java, make a scanned CHAI10 get no discount on purpose, and run it with run-app. In Offers.java, fix the comparison. In OffersTest.java, write the guard: the check runs it beside the original code, the fix and a wrong fix that calls code.equals("CHAI10"). Then answer Kabir's interview question at the bottom of the case, in your own words.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    Repro.java: a scanned CHAI10 that gets no discount

    Write reproduce() in Repro.java. Take the text a passenger's phone reads from the offer poster's QR, "OFFER:CHAI10", get the code out of it with Offers.codeFromQr, and return Offers.discountPercent of that code.

    The check runs your reproduce() twice: beside the original Offers.java it must return 0 (a code that should give 10% gets nothing), and beside a fixed Offers.java it must return 10. So it must really scan the QR text and ask for the discount. No real waiting and no reading input: reproduce() must finish within 3 seconds.

  2. Task 2

    Offers.java: a scanned code gets its discount

    Fix discountPercent(String code) in Offers.java so that it compares the code's text, wherever the String came from: CHAI10 gives 10, STAFF50 gives 50, any other code gives 0, and null (a bill with no offer) gives 0 without an exception.

    Keep codeFromQr, payable and payable's log line (bill <id>: offer <code>, <percent>% off, pay <amount>) as they are. The check uses its own bills and builds its codes at run time (from QR text, a StringBuilder, a line it splits), not only as literals, and a fix that throws on a null code is as wrong as the bug.

  3. Task 3

    OffersTest.java: a test that would have caught it

    Write a JUnit test class, OffersTest.java, that would have caught this bug before it reached the stations. The check runs your file three times: beside the original Offers.java, where at least one test must fail; beside the fixed Offers.java, where every test must pass; and beside a wrong fix that calls code.equals("CHAI10"), where at least one test must fail.

    So test both sides: a code built at run time (from QR text, as the poster's code is) gets its discount, and a bill with no offer (a null code) gets 0 without an exception. No real waiting: each test must finish within 3 seconds.

What you will learn

  • Repro.java: a scanned CHAI10 that gets no discount
  • Offers.java: a scanned code gets its discount
  • OffersTest.java: a test that would have caught it

More in Everyday traps

Build "== versus equals on strings" yourself

Tapri Counter runs on Java, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.