SCJP Java String Handling and Regular Expressions 4 — Questions and Answers
Question 1: What does the `String.format("%05d", 42)` call return?
- "00042" (Correct answer)
- "42000"
- "42 "
- " 42"
Correct answer: "00042"
The format specifier `%05d` pads the integer with leading zeros to a total width of 5.
Question 2: Which `Pattern` flag makes `.` match newline characters in addition to all other characters?
- Pattern.DOTALL (Correct answer)
- Pattern.MULTILINE
- Pattern.UNICODE_CASE
- Pattern.COMMENTS
Correct answer: Pattern.DOTALL
`Pattern.DOTALL` enables the `.` metacharacter to match any character including line terminators.
Question 3: Given `String s = "aabbcc"; s.replaceAll("(.)\\1", "$1");`, what is the result?
- "abc" (Correct answer)
- "aabbcc"
- "abc"
- A compile error
Correct answer: "abc"
The regex `(.)\1` matches any character followed by itself (a backreference), and `$1` replaces the pair with a single instance.
Question 4: What is the output of `System.out.println("hello".indexOf('l', 4));`?
- -1 (Correct answer)
- 2
- 3
- 4
Correct answer: -1
`indexOf(char, fromIndex)` starts searching at index 4; since 'l' does not appear at index 4 or later in "hello", it returns -1.
Question 5: Which statement correctly creates a `StringBuilder` with an initial capacity of 50?
- new StringBuilder(50) (Correct answer)
- new StringBuilder("50")
- new StringBuilder(); sb.ensureCapacity(50)
- StringBuilder.withCapacity(50)
Correct answer: new StringBuilder(50)
The `StringBuilder(int capacity)` constructor creates a builder with the specified initial capacity.
Question 6: What does `Matcher.find()` return on successive calls when there are multiple non-overlapping matches?
- true for each match found, then false when no more exist (Correct answer)
- true only for the first match
- All matches at once as a list
- It resets and starts over each call
Correct answer: true for each match found, then false when no more exist
`Matcher.find()` advances through the input and returns `true` each time a new match is located, returning `false` when the input is exhausted.
Question 7: What is printed by: `String s = "Java"; System.out.println(s.substring(1, 3));`?
- "av" (Correct answer)
- "ava"
- "Ja"
- "Java"
Correct answer: "av"
`substring(beginIndex, endIndex)` returns characters from index 1 (inclusive) to index 3 (exclusive), which is "av".
What does the `String.format("%05d", 42)` call return?