Find the bug · #20 · Types and comparisons Easy Java
The coupon works for testers, not for shoppers
Shoppers say the welcome coupon is rejected, but the team can’t reproduce it.
On this page
The report
Shoppers say the WELCOME10 coupon is rejected at checkout. The team can’t reproduce it: when they type it in capitals, with no spaces, it works every time.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Coupons {
static final String CODE = "WELCOME10";
// The code the shopper typed, trimmed and in capitals.
static boolean isValid(String typed) {
String code = typed.trim().toUpperCase();
return code == CODE;
}
}Read it, then pick a line.
For two String objects, what does == compare in Java: the text, or something else?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
System.out.println(Coupons.isValid("WELCOME10"));
System.out.println(Coupons.isValid("welcome10"));
System.out.println(Coupons.isValid(" WELCOME10 "));It prints
true false false
It should print
true true true
Show the answer: the bug, the fix, and how you’d find it
The bug (line 7)
Line 7 compares strings with ==, which in Java checks whether both are the same object, not whether they hold the same text. Typed exactly in capitals, Java hands back the very same string, so it works in testing; anything that makes a new string (lower case, spaces) fails. Compare text with equals.
The fix
4 // The code the shopper typed, trimmed and in capitals.5 static boolean isValid(String typed) {6 String code = typed.trim().toUpperCase();7 return code == CODE;7 return code.equals(CODE);8 }9}How you’d find it
- Reproduce what shoppers do, not what testers do: lower case, or a space copied from an email. Both are rejected.
- Exact capitals work but equivalent input doesn’t, so the comparison itself is suspect. It uses
==. - Recall what
==means for objects in Java: the same object.trimandtoUpperCaseonly return the original string when nothing changes.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
check(Coupons.isValid("welcome10"), "lower case");
check(Coupons.isValid(" WELCOME10 "), "spaces");
check(!Coupons.isValid("WELCOME20"), "a wrong code");Where else this bites
- Comparing boxed
Integervalues with==(see “Big orders don’t merge”). - JavaScript’s
==is a different trap: it converts types, so"1" == 1is true.