SCJP Java String Handling and Regular Expressions 2 — Questions and Answers
Question 1: What is the output of: System.out.println("Java".toUpperCase());
- java
- JAVA (Correct answer)
- Java
- jAVA
Correct answer: JAVA
toUpperCase() converts every character in the string to its uppercase equivalent.
Question 2: What does String.valueOf(42) return?
- 42 as an int
- "42" as a String (Correct answer)
- 42.0 as a double
- A NullPointerException
Correct answer: "42" as a String
String.valueOf(int) converts the integer to its String representation, returning "42".
Question 3: Which regular expression pattern matches one or more digits?
- \d*
- \d?
- \d+ (Correct answer)
- \d{0,}
Correct answer: \d+
The quantifier + means one or more, so \d+ matches one or more digit characters.
Question 4: What is the result of " Hello ".trim()?
- " Hello "
- "Hello "
- "Hello" (Correct answer)
- " Hello"
Correct answer: "Hello"
trim() removes leading and trailing whitespace from both ends of the string.
Question 5: Which method of the Pattern class is used to compile a regular expression?
- Pattern.create()
- Pattern.build()
- Pattern.compile() (Correct answer)
- Pattern.match()
Correct answer: Pattern.compile()
Pattern.compile(String regex) compiles the given regular expression into a Pattern object.
Question 6: What does the String method replace(char oldChar, char newChar) return?
- It modifies the original String in place
- A new String with all occurrences of oldChar replaced by newChar (Correct answer)
- Only the first occurrence replaced
- A boolean indicating if replacement occurred
Correct answer: A new String with all occurrences of oldChar replaced by newChar
replace() returns a new String because Strings are immutable; all occurrences of oldChar are replaced.
Question 7: What is the output of: System.out.println("hello".charAt(1));
- h
- e (Correct answer)
- l
- 1
Correct answer: e
charAt(1) returns the character at index 1, which is 'e' (index 0 is 'h').
What is the output of: System.out.println("Java".toUpperCase());