SCJP Java String Handling and Regular Expressions 5 — Questions and Answers
Question 1: What is the result of `"ABC".compareToIgnoreCase("abc")`?
- 0 (Correct answer)
- A positive integer
- A negative integer
- It throws an exception
Correct answer: 0
`compareToIgnoreCase` returns 0 when the two strings are equal ignoring case.
Question 2: Which regex quantifier means 'one or more, possessive (no backtracking)'?
- "+" (possessive: `++`) (Correct answer)
- "*" (greedy)
- "+" (reluctant: `+?`)
- "?" (optional)
Correct answer: "+" (possessive: `++`)
The possessive quantifier `++` matches one or more characters without giving them back during backtracking.
Question 3: What does calling `StringBuffer.reverse()` on the buffer `"12345"` produce?
- "54321" (Correct answer)
- "12345"
- "5321"
- A compile error
Correct answer: "54321"
`StringBuffer.reverse()` reverses the character sequence in place and returns the same `StringBuffer`.
Question 4: Which `String` method splits the string `"a,b,,c"` using `","` as delimiter, keeping trailing empty strings?
- split(",", -1) (Correct answer)
- split(",")
- split(",", 0)
- split(",", 1)
Correct answer: split(",", -1)
Passing a negative limit to `split` disables the default behavior of discarding trailing empty strings.
Question 5: What is the output of `System.out.println(Pattern.matches("\\d+", "123abc"));`?
- false (Correct answer)
- true
- 123
- A PatternSyntaxException
Correct answer: false
`Pattern.matches` requires the entire input to match the pattern; "123abc" contains non-digit characters, so it returns `false`.
Question 6: Given `StringBuilder sb = new StringBuilder("Hello"); sb.insert(2, "XY");`, what is `sb.toString()`?
- "HeXYllo" (Correct answer)
- "XYHello"
- "HelloXY"
- "HXYello"
Correct answer: "HeXYllo"
`insert(offset, str)` inserts the string before the character currently at `offset`, so inserting at index 2 places "XY" between 'e' and 'l'.
Question 7: What is the character class `[\\w&&[^\\d]]` equivalent to in Java regex?
- Word characters excluding digits (i.e., letters and underscore) (Correct answer)
- All digits
- All whitespace
- All non-word characters
Correct answer: Word characters excluding digits (i.e., letters and underscore)
`[\w&&[^\d]]` uses intersection: word characters (`\w`) intersected with non-digits (`[^\d]`), yielding letters and the underscore.
What is the result of `"ABC".compareToIgnoreCase("abc")`?