1.7

Comparing Values

AP Computer Science A

Comparing primitives: use ==

java
int a = 5;
int b = 5;
System.out.println(a == b);   // true (same value)

double x = 3.14;
double y = 3.14;
System.out.println(x == y);   // true

boolean p = true;
boolean q = false;
System.out.println(p == q);   // false

Comparing objects: use .equals()

java
String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);       // false (different objects in memory!)
System.out.println(s1.equals(s2));   // true (same content)

Why does == fail for objects?

a: [5]     b: [5]     → a == b is true (same value)
s1: [→ location 100: "hello"]    s2: [→ location 200: "hello"]

String literal pool — a tricky exception

java
String s1 = "hello";   // string literal — stored in the String pool
String s2 = "hello";   // same literal — Java reuses the same object

System.out.println(s1 == s2);       // true (same object in the pool!)
System.out.println(s1.equals(s2));   // true (same content)

The golden rule

java
// CORRECT
if (name.equals("Alice")) {
    System.out.println("Hi Alice!");
}

// WRONG — may not work as expected
if (name == "Alice") {
    System.out.println("Hi Alice!");
}

Comparing Strings — more methods

equals() vs equalsIgnoreCase()

java
String a = "Hello";
String b = "hello";

System.out.println(a.equals(b));            // false (case matters)
System.out.println(a.equalsIgnoreCase(b));   // true (ignores case)

compareTo()

java
String a = "apple";
String b = "banana";
String c = "apple";

System.out.println(a.compareTo(b));  // negative (a comes BEFORE b)
System.out.println(b.compareTo(a));  // positive (b comes AFTER a)
System.out.println(a.compareTo(c));  // 0 (they are equal)
java
"Apple".compareTo("apple")   // negative ('A' < 'a')
"cat".compareTo("car")       // positive ('t' > 'r')
"ab".compareTo("abc")        // negative (shorter string is "less")

Null references

java
String name = null;

// This will crash! (NullPointerException)
System.out.println(name.equals("Alice"));

// Safe way to check
if (name != null && name.equals("Alice")) {
    System.out.println("Hi Alice!");
}

// Or check the literal first (literal is never null)
if ("Alice".equals(name)) {
    System.out.println("Hi Alice!");
}

Summary comparison table

java
int a = 5, b = 5;
String s1 = new String("hi");
String s2 = new String("hi");
String s3 = "hi";
String s4 = "hi";

AP Exam Tips

Common Mistakes

Key Vocabulary