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.
- Question 1 · Easy
What is the output of the following code?
String s = "Hello, World!"; System.out.println(s.length());- A12Why not A: Count every character including the comma, space, and exclamation mark. "Hello, World!" has 13 characters.
- B13Correct
- C11Why 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.
- D10Why not D: Counting only the letters (no punctuation/space) gives 10, but
length()counts every character in the String.
ExplanationString.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.
- A
- Question 2 · Easy
What does the following code print?
String s = "programming"; System.out.println(s.substring(3, 7));- AgramCorrect
- BgraWhy not B:
substring(3, 7)includes index 3 up to but NOT including index 7. That is 4 characters, not 3. - CrammWhy not C: Index 3 is 'g' (p=0, r=1, o=2, g=3). substring(3,7) starts at 'g', not 'r'.
- DgramiWhy not D:
substring(end)is exclusive: index 7 is NOT included. Characters at indices 3,4,5,6 = g,r,a,m.
ExplanationIndices: 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`.
- A
- 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:compareToreturns an int (0 if equal, not boolean). Comparing an int totruecauses a compile error. - D
if (String.equals(a, b))Why not D:equalsis an instance method; there is no staticString.equals(a, b)syntax. Usea.equals(b).
ExplanationFor 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 takeawayUse `.equals()` to compare String content; `==` compares object references and can give wrong results.
- A
- Question 4 · Easy
What is the output of the following code?
System.out.println(Math.abs(-7)); System.out.println(Math.pow(2, 3));- A7\n8Why not A:
Math.powreturns a double. The output would be7then8.0, not8. - B7\n8.0Correct
- C-7\n8.0Why not C:
Math.abs(-7)returns the absolute value, which is positive 7. - D7\n6.0Why not D:
Math.pow(2, 3)computes 2^3 = 8.0, not 6.0 (which would be 2*3).
ExplanationMath.abs(-7)returns7(an int).Math.pow(2, 3)returns8.0as adouble(2 raised to the power 3). Note thatMath.powalways returns adouble.Key takeaway`Math.pow(base, exp)` always returns a `double`. `Math.abs` returns the same type as its argument.
- A
- Question 5 · Easy
What is the output of the following code?
String s = "Java"; s = s.toUpperCase(); s = s + " rocks"; System.out.println(s);- AJava rocksWhy not A:
toUpperCase()creates a new String with all uppercase letters. The reassignment makes s refer to "JAVA". - BJAVA rocksCorrect
- CJAVA ROCKSWhy not C: Only the first
toUpperCase()call is made. The concatenated " rocks" is not uppercased. - Djava rocksWhy not D:
toUpperCase()converts all characters to uppercase. The original lowercase 'j','a','v','a' become 'J','A','V','A'.
ExplanationStrings are immutable.
toUpperCase()returns a new String; the old one is unchanged. Afters = s.toUpperCase(), s refers to "JAVA". Concatenating " rocks" gives "JAVA rocks".Key takeawayString methods return new Strings — they do not modify the original. Reassign if you want to keep the result.
- A
- 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"));- A2\n0Why not A:
indexOfreturns -1 (not 0) when the substring is not found. - B3\n-1Why not B: Indices: a(0)b(1)c(2)d(3)e(4)f(5). The substring "cd" starts at index 2, not 3.
- C2\n-1Correct
- D2\nnullWhy not D:
indexOfreturns the primitive int -1 when not found, not the String "null".
ExplanationIndices: 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.
- A
- Question 7 · Easy
What is the value of
resultafter this code executes?double result = Math.sqrt(Math.pow(3.0, 2) + Math.pow(4.0, 2));- A5.0Correct
- B7.0Why not B: This is 3+4. The code computes sqrt(3^2 + 4^2) = sqrt(9+16) = sqrt(25) = 5.
- C25.0Why not C: sqrt(25) = 5.0, not 25.0. The
Math.sqrtis applied to the sum 9+16=25. - D12.5Why not D:
Math.pow(3,2)+Math.pow(4,2)= 9+16 = 25, and sqrt(25)=5, not 12.5.
ExplanationThis 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.
- A
- Question 8 · Easy
What is the output of the following code?
String s = "Hello World"; System.out.println(s.substring(6));- AWorldCorrect
- BWorldWhy 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.
- CorldWhy not C: Index 6 is 'W', not 'o' (which is at index 7). substring(6) includes 'W'.
- DHelloWhy not D:
substring(6)returns from index 6 to the end, not from the beginning to index 6.
ExplanationIndices: 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.
- A
- Question 9 · Easy
What is printed by the following code?
String s = " hello "; System.out.println(s.trim().toUpperCase().length());- A5Correct
- B9Why not B: 9 is the length before trimming.
trim()removes leading/trailing whitespace, leaving "hello" (5 chars). - C7Why not C: 7 would result if only one leading or trailing space was trimmed.
trim()removes all leading and trailing whitespace. - DCompile errorWhy 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.
ExplanationMethod 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 takeawayString methods can be chained; each returns a new String (or int for `length()`). Trim removes all leading/trailing whitespace.
- A
- 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);- Atrue\ntrueWhy not A: Java caches Integer objects only in the range -128 to 127. Values outside this range create new objects, so
c == dcompares different references and returns false. - Bfalse\nfalseWhy not B: Values -128 to 127 are cached by the Integer pool, so
a == bis true (same cached object). - Ctrue\nfalseCorrect
- Dfalse\ntrueWhy 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.
ExplanationJava's
Integerautoboxing caches values from -128 to 127. For these values, autoboxedIntegerobjects with the same value share the same reference, so==returns true. For 200 (outside the cache range), two separateIntegerobjects are created, and==compares references — returning false.Key takeawayInteger autoboxing caches -128 to 127. Use `.equals()` to compare Integer values reliably, not `==`.
- A
- Question 11 · Medium
What is the output of the following code?
String s = null; System.out.println(s.length());- A0Why not A:
nullmeans no object is referenced. Calling any method onnullthrows a NullPointerException, not returns 0. - BNullPointerException at runtimeCorrect
- CCompile errorWhy not C: The code compiles fine.
sis a valid String variable. The NPE only occurs at runtime whenlength()is called on a null reference. - DnullWhy not D: Calling a method on a null reference throws a NullPointerException; it does not print the String "null".
ExplanationWhen
sisnull, it does not refer to any String object. Calling.length()on it at runtime throws aNullPointerException. The code compiles successfully but crashes when executed.Key takeawayCalling any method on a null reference throws NullPointerException at runtime — always check for null before calling methods.
- A
- Question 12 · Medium
What is the value of
nafter the following code executes?int n = (int)(Math.random() * 6) + 1;- AA random integer from 0 to 5Why not A: Adding 1 shifts the range.
(int)(Math.random()*6)gives 0–5, and adding 1 gives 1–6. - BA random integer from 1 to 6Correct
- CA random integer from 0 to 6Why 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). - DA random double from 1.0 to 6.0Why not D: The cast
(int)converts the result to an integer before adding 1, so the final type is int, not double.
ExplanationMath.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 takeawayPattern for a random integer in [min, max]: `(int)(Math.random() * (max - min + 1)) + min`.
- A