SCJP Java String Handling and Regular Expressions 1 — Questions and Answers
Question 1: What is the result of the following code? String s = "Hello"; s.concat(" World"); System.out.println(s);
- Hello World
- Hello (Correct answer)
- null
- Compilation error
Correct answer: Hello
String objects are immutable; concat() returns a new String but the result is not assigned back to s, so s remains "Hello".
Question 2: Which of the following creates a String object in the string pool?
- new String("hello")
- String s = new String("hello")
- String s = "hello" (Correct answer)
- String s = new String()
Correct answer: String s = "hello"
String literals (String s = "hello") are stored in the string pool, while using new String() always creates an object on the heap.
Question 3: What does the == operator compare when used between two String objects?
- The content of the strings
- The length of the strings
- The reference (memory address) of the objects (Correct answer)
- The hash codes of the strings
Correct answer: The reference (memory address) of the objects
== compares object references, not content; use equals() to compare String content.
Question 4: Which class provides a thread-safe, mutable sequence of characters?
- String
- StringBuilder
- StringBuffer (Correct answer)
- CharSequence
Correct answer: StringBuffer
StringBuffer is synchronized, making it thread-safe, whereas StringBuilder is faster but not thread-safe.
Question 5: What is the output of: System.out.println("abc".indexOf('c'));
- 1
- 2 (Correct answer)
- 3
- -1
Correct answer: 2
indexOf() returns the zero-based index; 'a' is at 0, 'b' at 1, 'c' at 2.
Question 6: What is printed by: System.out.println("Hello World".substring(6));
- Hello
- World (Correct answer)
- World
- orld
Correct answer: World
substring(6) returns characters from index 6 to the end; index 6 is 'W', yielding "World".
Question 7: Which method correctly checks whether a String starts with a given prefix?
- contains()
- startWith()
- startsWith() (Correct answer)
- beginsWith()
Correct answer: startsWith()
The correct method name is startsWith(), which returns true if the string begins with the specified prefix.
What is the result of the following code?
String s = "Hello";
s.concat(" World");
System.out.println(s);