# Hard Multiple Choice Questions¶

These problems are harder than most of those that you will usually see on the AP CS A exam.

4-9-1: Given the following code segment, which of the following is true?

String s1 = new String("Hi There");
String s2 = new String("Hi There");
String s3 = s1;

I.   (s1 == s2)
II.  (s1.equals(s2))
III. (s1 == s3)
IV.  (s2.equals(s3))

• (A) II and IV
• III is also correct.
• (B) II, III, and IV
• String overrides equals to check if the two string objects have the same characters. The == operator checks if two object references refer to the same object. So II is correct since s1 and s2 have the same characters. Number II is correct since s3 and s1 are referencing the same string, so they will be ==. And s2 and s3 both refer to string that have the same characters so equals will be true in IV. The only one that will not be true is I, since s1 and s2 are two different objects (even though they have the same characters).
• (C) I, II, III, IV
• I is not correct since s1 and s2 are two different objects (even though they have the same characters). If s1 and s2 were both referring to literals, then I would be correct, but the new operator forces a new object to be created.
• (D) II only
• III and IV are also correct.
• (E) IV only
• II and III are also correct.

4-9-2: What does the following code print?

System.out.println("13" + 5 + 3);

• (A) 21
• This would be correct if it was System.out.println(13 + 5 + 3), but the 13 is a string.
• (B) 1353
• This is string concatenation. When you apprend a number to a string it get turned into a string and processing is from left to right.
• (C) It will give a run-time error
• You can append a number to a string in Java. It turns the number into a string and then appends the second string to the first string.
• (D) 138
• This would be correct if it was System.out.println("13" + (5 + 3)), but the 5 is turned into a string and appended to the 13 and then the same is done with the 3.
• (E) It will give a compile-time error
• You can append a number to a string in Java. It will compile.
Next Section - Strings - Summary