AP CSA Unit 1 Day 17: Equals vs. Doubleequals

Unit 1 Foundation (Cycle 1) Day 17 of 28 Foundation

equals() vs == for Strings

Section 1.11 — Strings: Comparison

Key Concept

Method signatures in Java include the method name and parameter types (but not the return type). When a method is called, Java matches the call to the correct overloaded version based on the number and types of arguments. Parameters are passed by value in Java — for primitives, the method receives a copy; for objects, the method receives a copy of the reference. This means a method can modify an object's state through the reference, but cannot make the caller's variable point to a different object.

Consider the following code segment.

String a = "hello"; String b = "hel"; b += "lo"; System.out.println(a == b); System.out.println(a.equals(b));

What is printed as a result of executing the code segment?

Answer: (B) false true

Two different comparison operators:

a == b: Compares references (memory addresses). a points to the literal "hello" in the String pool. b was built by concatenation ("hel" + "lo"), creating a new object. Different objects means == returns false.

a.equals(b): Compares the actual character content. Both contain "hello", so equals() returns true.

Why Not the Others?

(A) == checks if two variables point to the exact same object in memory. Since b was created via concatenation at runtime, it is a different object than the literal "hello".

(C) The content of both strings is identical ("hello"), so .equals() returns true. It compares characters, not references.

(D) This is backwards. == compares references (false here), and .equals() compares content (true here).

Common Mistake

The == vs .equals() distinction is the #1 tested String concept on the AP exam. == checks if two variables refer to the same object. .equals() checks if two Strings have the same characters. Always use .equals() to compare String content.

AP Exam Tip

If you see == used with Strings on the AP exam, the answer almost always involves it returning false even when the content matches. The exam loves testing this distinction.

Review this topic: Section 1.11 — Strings: Comparison • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.