AP Computer Science A · Topic 3.7
Comparing Objects Practice
Part of Boolean Expressions and if Statements.
Practice questions
6
Sample questions
5 of 6 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public static boolean isHello(String s) { if (s == "hello") { return true; } return false; }What is wrong with this method?
- A
The if-statement is missing braces
- B
The method should return s instead of true
- C
Nothing is wrong; it works correctly for all inputs
- Dcheck_circle
Strings should be compared with .equals, not ==
Why
== compares object references for Strings, not contents. Use s.equals("hello") to compare characters; == may succeed for literals due to interning but fails generally.
- A
Sample 2difficulty 4/5
To check if <code>String s</code> equals <code>"yes"</code>, use
- Acheck_circle
s.equals("yes")
- B
s.compareTo("yes")
- C
s == "yes"
- D
s == 'yes'
Why
Use <code>.equals</code> for string content comparison; <code>==</code> only checks references.
- A
Sample 3difficulty 4/5
For <code>String a = new String("hi"); String b = new String("hi");</code> — what is <code>a == b</code> and <code>a.equals(b)</code>?
- A
== true; equals false
- B
Both false
- C
Both true
- Dcheck_circle
== false; equals true
Why
<code>==</code> compares references (different objects → false); <code>.equals</code> compares content (same content → true).
- A
Sample 4difficulty 4/5
Why is <code>if (0.1 + 0.2 == 0.3)</code> unreliable?
- A
Always works
- Bcheck_circle
Round-off error in floating-point representation
- C
0.1 isn't a valid number
- D
Doubles can't be compared
Why
Binary FP cannot represent 0.1 exactly; 0.1+0.2 = 0.30000000000000004.
- A
Sample 5difficulty 4/5
<code>s.equals(null)</code> (where s is non-null) returns
- A
Throws NullPointerException
- B
true
- Ccheck_circle
false
- D
Compile error
Why
Equals returns false for null comparison; doesn't throw.
- A