AP Computer Science A Using Objects — Worked Answer Explanations

Unit 2 · 12 questions explained

Below is a complete answer key for our AP Computer Science A Using Objects practice questions. For each question you'll find the correct choice, a full written explanation of how to get there, and — for every wrong answer — a short note on exactly why it's tempting and where it goes wrong. Reading these straight through is one of the fastest ways to find the gaps in a unit before exam day.

Prefer to test yourself first? Take the timed Using Objects practice test and come back here to review, or head back to the Using Objects unit overview.

In-content ad
  1. Question 1 · Easy

    What is the output of the following code?

    String s = "Hello, World!";
    System.out.println(s.length());
    
    • A
      12
      Why not A: Count every character including the comma, space, and exclamation mark. "Hello, World!" has 13 characters.
    • B
      13Correct
    • C
      11
      Why not C: This omits two characters, likely the comma+space or space+exclamation. Count: H-e-l-l-o-,-space-W-o-r-l-d-! = 13.
    • D
      10
      Why not D: Counting only the letters (no punctuation/space) gives 10, but length() counts every character in the String.
    Explanation

    String.length() returns the number of characters including spaces and punctuation. "Hello, World!" = H(1) e(2) l(3) l(4) o(5) ,(6) space(7) W(8) o(9) r(10) l(11) d(12) !(13) = 13.

    Key takeaway

    `String.length()` counts every character: letters, spaces, digits, and punctuation.

  2. Question 2 · Easy

    What does the following code print?

    String s = "programming";
    System.out.println(s.substring(3, 7));
    
    • A
      gramCorrect
    • B
      gra
      Why not B: substring(3, 7) includes index 3 up to but NOT including index 7. That is 4 characters, not 3.
    • C
      ramm
      Why not C: Index 3 is 'g' (p=0, r=1, o=2, g=3). substring(3,7) starts at 'g', not 'r'.
    • D
      grami
      Why not D: substring(end) is exclusive: index 7 is NOT included. Characters at indices 3,4,5,6 = g,r,a,m.
    Explanation

    Indices: p(0)r(1)o(2)g(3)r(4)a(5)m(6)m(7)i(8)n(9)g(10). substring(3, 7) returns characters at indices 3,4,5,6 = "gram". The end index is exclusive.

    Key takeaway

    `substring(begin, end)` returns characters from index `begin` up to but NOT including `end`.

  3. Question 3 · Easy

    Which of the following correctly compares two String objects for equal content in Java?

    String a = "hello";
    String b = "hello";
    
    • A
      if (a == b)
      Why not A: == on objects compares references (memory addresses), not content. It may return true due to string interning but is unreliable for general use.
    • B
      if (a.equals(b))Correct
    • C
      if (a.compareTo(b) == true)
      Why not C: compareTo returns an int (0 if equal, not boolean). Comparing an int to true causes a compile error.
    • D
      if (String.equals(a, b))
      Why not D: equals is an instance method; there is no static String.equals(a, b) syntax. Use a.equals(b).
    Explanation

    For String content comparison, always use .equals(). The == operator checks if two references point to the same object in memory, which is unreliable for Strings created at runtime. a.equals(b) compares the actual character sequences.

    Key takeaway

    Use `.equals()` to compare String content; `==` compares object references and can give wrong results.

  4. Question 4 · Easy

    What is the output of the following code?

    System.out.println(Math.abs(-7));
    System.out.println(Math.pow(2, 3));
    
    • A
      7\n8
      Why not A: Math.pow returns a double. The output would be 7 then 8.0, not 8.
    • B
      7\n8.0Correct
    • C
      -7\n8.0
      Why not C: Math.abs(-7) returns the absolute value, which is positive 7.
    • D
      7\n6.0
      Why not D: Math.pow(2, 3) computes 2^3 = 8.0, not 6.0 (which would be 2*3).
    Explanation

    Math.abs(-7) returns 7 (an int). Math.pow(2, 3) returns 8.0 as a double (2 raised to the power 3). Note that Math.pow always returns a double.

    Key takeaway

    `Math.pow(base, exp)` always returns a `double`. `Math.abs` returns the same type as its argument.

  5. Question 5 · Easy

    What is the output of the following code?

    String s = "Java";
    s = s.toUpperCase();
    s = s + " rocks";
    System.out.println(s);
    
    • A
      Java rocks
      Why not A: toUpperCase() creates a new String with all uppercase letters. The reassignment makes s refer to "JAVA".
    • B
      JAVA rocksCorrect
    • C
      JAVA ROCKS
      Why not C: Only the first toUpperCase() call is made. The concatenated " rocks" is not uppercased.
    • D
      java rocks
      Why not D: toUpperCase() converts all characters to uppercase. The original lowercase 'j','a','v','a' become 'J','A','V','A'.
    Explanation

    Strings are immutable. toUpperCase() returns a new String; the old one is unchanged. After s = s.toUpperCase(), s refers to "JAVA". Concatenating " rocks" gives "JAVA rocks".

    Key takeaway

    String methods return new Strings — they do not modify the original. Reassign if you want to keep the result.

  6. Question 6 · Easy

    What is the output of the following code?

    String s = "abcdef";
    System.out.println(s.indexOf("cd"));
    System.out.println(s.indexOf("xy"));
    
    • A
      2\n0
      Why not A: indexOf returns -1 (not 0) when the substring is not found.
    • B
      3\n-1
      Why not B: Indices: a(0)b(1)c(2)d(3)e(4)f(5). The substring "cd" starts at index 2, not 3.
    • C
      2\n-1Correct
    • D
      2\nnull
      Why not D: indexOf returns the primitive int -1 when not found, not the String "null".
    Explanation

    Indices: a(0)b(1)c(2)d(3)e(4)f(5). indexOf("cd") finds the substring starting at index 2. indexOf("xy") finds nothing and returns -1 (not 0 or null).

    Key takeaway

    `String.indexOf()` returns the starting index of the first occurrence, or -1 if not found.

  7. Question 7 · Easy

    What is the value of result after this code executes?

    double result = Math.sqrt(Math.pow(3.0, 2) + Math.pow(4.0, 2));
    
    • A
      5.0Correct
    • B
      7.0
      Why not B: This is 3+4. The code computes sqrt(3^2 + 4^2) = sqrt(9+16) = sqrt(25) = 5.
    • C
      25.0
      Why not C: sqrt(25) = 5.0, not 25.0. The Math.sqrt is applied to the sum 9+16=25.
    • D
      12.5
      Why not D: Math.pow(3,2)+Math.pow(4,2) = 9+16 = 25, and sqrt(25)=5, not 12.5.
    Explanation

    This is the Pythagorean theorem: sqrt(3² + 4²) = sqrt(9 + 16) = sqrt(25) = 5.0. Math.pow(3.0, 2) = 9.0, Math.pow(4.0, 2) = 16.0, sum is 25.0, Math.sqrt(25.0) = 5.0.

    Key takeaway

    `Math.pow(base, exp)` and `Math.sqrt(x)` work together for common math formulas. Both return double.

  8. Question 8 · Easy

    What is the output of the following code?

    String s = "Hello World";
    System.out.println(s.substring(6));
    
    • A
      WorldCorrect
    • B
      World
      Why not B: Index 6 is 'W' (H=0,e=1,l=2,l=3,o=4,space=5,W=6). The space at index 5 is NOT included.
    • C
      orld
      Why not C: Index 6 is 'W', not 'o' (which is at index 7). substring(6) includes 'W'.
    • D
      Hello
      Why not D: substring(6) returns from index 6 to the end, not from the beginning to index 6.
    Explanation

    Indices: H(0)e(1)l(2)l(3)o(4) (5)W(6)o(7)r(8)l(9)d(10). substring(6) returns from index 6 to the end: "World".

    Key takeaway

    `substring(beginIndex)` returns from that index to the end of the string.

  9. Question 9 · Easy

    What is printed by the following code?

    String s = "  hello  ";
    System.out.println(s.trim().toUpperCase().length());
    
    • A
      5Correct
    • B
      9
      Why not B: 9 is the length before trimming. trim() removes leading/trailing whitespace, leaving "hello" (5 chars).
    • C
      7
      Why not C: 7 would result if only one leading or trailing space was trimmed. trim() removes all leading and trailing whitespace.
    • D
      Compile error
      Why not D: Method chaining is valid in Java when each method returns an object that has the next method. trim() returns String, toUpperCase() returns String, length() returns int.
    Explanation

    Method chaining is evaluated left to right. s.trim() = "hello" (5 chars). .toUpperCase() = "HELLO". .length() = 5. Note: toUpperCase() doesn't change the count, just the characters.

    Key takeaway

    String methods can be chained; each returns a new String (or int for `length()`). Trim removes all leading/trailing whitespace.

  10. Question 10 · Medium

    What is the output of the following code?

    Integer a = 127;
    Integer b = 127;
    Integer c = 200;
    Integer d = 200;
    System.out.println(a == b);
    System.out.println(c == d);
    
    • A
      true\ntrue
      Why not A: Java caches Integer objects only in the range -128 to 127. Values outside this range create new objects, so c == d compares different references and returns false.
    • B
      false\nfalse
      Why not B: Values -128 to 127 are cached by the Integer pool, so a == b is true (same cached object).
    • C
      true\nfalseCorrect
    • D
      false\ntrue
      Why not D: The cache applies to -128..127, not to values above 127. So 127 is cached (true) and 200 is not (false), not the reverse.
    Explanation

    Java's Integer autoboxing caches values from -128 to 127. For these values, autoboxed Integer objects with the same value share the same reference, so == returns true. For 200 (outside the cache range), two separate Integer objects are created, and == compares references — returning false.

    Key takeaway

    Integer autoboxing caches -128 to 127. Use `.equals()` to compare Integer values reliably, not `==`.

  11. Question 11 · Medium

    What is the output of the following code?

    String s = null;
    System.out.println(s.length());
    
    • A
      0
      Why not A: null means no object is referenced. Calling any method on null throws a NullPointerException, not returns 0.
    • B
      NullPointerException at runtimeCorrect
    • C
      Compile error
      Why not C: The code compiles fine. s is a valid String variable. The NPE only occurs at runtime when length() is called on a null reference.
    • D
      null
      Why not D: Calling a method on a null reference throws a NullPointerException; it does not print the String "null".
    Explanation

    When s is null, it does not refer to any String object. Calling .length() on it at runtime throws a NullPointerException. The code compiles successfully but crashes when executed.

    Key takeaway

    Calling any method on a null reference throws NullPointerException at runtime — always check for null before calling methods.

  12. Question 12 · Medium

    What is the value of n after the following code executes?

    int n = (int)(Math.random() * 6) + 1;
    
    • A
      A random integer from 0 to 5
      Why not A: Adding 1 shifts the range. (int)(Math.random()*6) gives 0–5, and adding 1 gives 1–6.
    • B
      A random integer from 1 to 6Correct
    • C
      A random integer from 0 to 6
      Why not C: Math.random() returns [0.0, 1.0). Multiplying by 6 gives [0.0, 6.0). Casting to int gives 0, 1, 2, 3, 4, or 5 (never 6).
    • D
      A random double from 1.0 to 6.0
      Why not D: The cast (int) converts the result to an integer before adding 1, so the final type is int, not double.
    Explanation

    Math.random() returns a double in [0.0, 1.0). Multiplying by 6 gives [0.0, 6.0). Casting to int truncates to 0, 1, 2, 3, 4, or 5. Adding 1 shifts the range to 1, 2, 3, 4, 5, or 6. This is the standard die-roll pattern.

    Key takeaway

    Pattern for a random integer in [min, max]: `(int)(Math.random() * (max - min + 1)) + min`.