QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › The language for tests

Types, String and the difference between == and equals

For objects the == operator compares references, not content, while equals compares content if the class overrides it. So == on strings works for pooled literals and breaks on values from an API. Likewise == on Integer works only inside the cache from −128 to 127. Money is kept in BigDecimal and compared with compareTo, because equals takes scale into account.

Java · Language

A test compares two identical strings with ==, and it is green or red at random. Why?

A test class has assertTrue(status == "PAID"). Locally, where status comes from a constant in the same class, it is green. Then the status starts to arrive in an API response, and the very same "PAID" is suddenly not equal to "PAID". The text is identical and the check fails. The reason is that == on objects does not ask "is the text the same" but "is this the same object in memory".

This lesson covers how Java types are laid out, how == differs from equals and which other three "equalities" break an automation engineer's checks: the Integer cache, double for money and null on unboxing.

How it works and why it is designed so

Java has two kinds of types. Primitives (int, long, double, boolean, char and others) hold the value itself and are never null. Reference types (classes, arrays, interfaces, String, the wrappers Integer and Boolean) hold a reference to an object on the heap, and the reference can be null. The == operator always compares what lies in the variable: for a primitive that is the value, for a reference it is the address.

The equals method is declared in Object, and there it also compares references. A class decides what "same content" means and overrides equals. String, the wrappers, BigDecimal, List and record do this, so for them equals compares content. Your own User class without an override behaves like Object: two objects with identical fields are not equal.

== and equals on two strings

==

Same reference?

Two "PAID" objects, one from a literal, one from an API response: different addresses, the result is false.

equals

Same content?

Compares the characters: the same text gives true no matter where the string came from.

Figure 1. Checks on strings need equals.

Example: a string that is "sometimes equal"

The compiler puts string literals into a pool, so identical literals in code point to one object. The same holds for constant expressions: "q" + "a" is computed at compile time. A string assembled at run time lives separately.

String lit = "qa";
String built = "q" + "a";          // a constant expression: the same object
String part = "q";
String runtime = part + "a";       // assembled at run time
String fromNew = new String("qa"); // always a new object

System.out.println(lit == built);        // true
System.out.println(lit == runtime);      // false
System.out.println(lit == fromNew);      // false
System.out.println(lit.equals(runtime)); // true

This is why == on strings creates the false impression that all is well: the check is green on literals and breaks as soon as the value arrives from JSON, a database or getText(). There is an intern() method that returns the pooled string, but relying on it in tests hides the bug instead of fixing it. The right check:

// the expected value on the left: does not fail on null
assertTrue("PAID".equals(status));

// or an assert library that calls equals itself and shows both values
assertEquals("PAID", status);
assertThat(status).isEqualTo("PAID");

// two values, either may be null
boolean same = Objects.equals(expected, actual);

status.equals("PAID") throws NullPointerException when status is null, and the test fails from an unclear place. Assertions (assertEquals, isEqualTo) print expected: "PAID" but was: null, so they are better in tests. The counterpart of assertEquals is assertSame: it deliberately compares references and belongs only where object identity matters (a singleton, for example).

Three other "equalities" that break tests

1. The Integer cache. Wrappers are created through Integer.valueOf, and the specification guarantees a cache for values from −128 to 127. So == on small numbers "works" and on large ones usually does not:

Integer a = 127, b = 127;
Integer c = 1000, d = 1000;
System.out.println(a == b);      // true: from the cache
System.out.println(c == d);      // false: two different objects
System.out.println(c.equals(d)); // true
System.out.println(c == 1000);   // true: c is unboxed to int

The last line shows the second trap. When one side of == is a primitive, the wrapper is unboxed. If it is null, you get a NullPointerException without any method call. int id = response.getId(); fails the same way when the id field of the DTO is an Integer with the value null. The message points to the line but does not say it was unboxing.

2. double for money. Binary floating point has no exact representation of 0.1. So 0.1 + 0.2 gives 0.30000000000000004, and assertEquals(0.3, 0.1 + 0.2) fails. For amounts and prices use BigDecimal created from a string:

BigDecimal price = new BigDecimal("10.50");
BigDecimal sum = price.add(new BigDecimal("0.10"));  // 10.60

new BigDecimal("2.0").equals(new BigDecimal("2.00")); // false: different scale
new BigDecimal("2.0").compareTo(new BigDecimal("2.00")); // 0: the numbers are equal

// AssertJ compares numerically
assertThat(sum).isEqualByComparingTo("10.60");
// double with a tolerance, if precision is not critical
assertEquals(0.3, 0.1 + 0.2, 0.0001);

The constructor new BigDecimal(0.1) from a double carries the inexactness into the number (you get 0.1000000000000000055…), so the string constructor or BigDecimal.valueOf(0.1) is safer. And BigDecimal.equals takes scale into account: 2.0 and 2.00 are different, so amounts are compared with compareTo or isEqualByComparingTo.

3. Case, whitespace and locale. equalsIgnoreCase compares ignoring case. If you must change case yourself, write toLowerCase(Locale.ROOT): without a locale the result depends on the machine's settings (in the Turkish locale an uppercase I becomes a dotless ı, not i). The strip() and isBlank() methods (Java 11) remove whitespace from the edges, but a non-breaking space (U+00A0) from UI text is not whitespace for them, so it has to be replaced explicitly.

Limits and alternatives. Arrays do not override equals: use Arrays.equals, or assertArrayEquals in JUnit. Collections (List, Set, Map) compare elements through their equals, so a list of your own objects without equals is never equal to another such list (details in the lesson on hashCode/equals). In a record, equals is generated from all components.

Common mistakes

  • == on strings or wrappers in a check: works on literals and small numbers, fails on data from the system, and the failure is hard to reproduce.
  • actual.equals(expected) when actual may be null: the test fails with NullPointerException instead of a clear "was null".
  • double or float for an amount: an error in the 17th digit goes unnoticed until a check compares exactly.
  • equals on BigDecimal instead of compareTo: 10.0 and 10.00 differ, and the correct amount "does not match".
  • Assigning a wrapper field to a primitive without a null check.

Check yourself

What does new String("qa") == "qa" print, and why does equals give a different result?

Answer

false: new String creates a new object while the literal lives in the pool, so the addresses differ. equals compares the characters and gives true.

Integer x = 200, y = 200; Why does x == y give false when for 100 it would give true?

Answer

Autoboxing goes through Integer.valueOf, which caches −128…127. 100 comes from the cache, one object; 200 gives two different objects. Compare with equals.

Why is double not suitable for a price, and why does new BigDecimal("2.0").equals(new BigDecimal("2.00")) return false?

Answer

double cannot store 0.1 exactly and errors accumulate. BigDecimal.equals also compares scale (the number of decimal places); numeric equality comes from compareTo.

In an interview. Junior: == compares references (values for primitives), and equals compares content if the class overrides it. In tests I compare strings with equals or an assert library, and for a possible null with Objects.equals. Middle/Senior: I know about the string pool and the Integer cache (−128…127): because of them == sometimes works and sometimes does not, and such a bug lives until the first real value from the API. I keep money in BigDecimal from the string constructor and compare with compareTo, because equals takes scale into account. I watch for unboxing of null in DTOs and change case with Locale.ROOT.

More articles in this chapter