String methods return new strings — Aptitude Question
String methods return new strings: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
String s = "placement";
s.toUpperCase();
s.concat(" test");
System.out.println(s);
}
}Options
- placement
- PLACEMENT
- placement test
- PLACEMENT test
Show the answer and the worked solution
Correct answer: A. placement
Worked solution
- Strings are immutable, so toUpperCase and concat cannot change s; they build and return new strings.
- Neither return value is assigned to anything, so both new strings are discarded immediately.
- s still refers to the original object and placement is printed.
Answer: placement.
The idea
Every String method that looks like a mutation is really a factory. The fix is s = s.toUpperCase(), and forgetting the assignment is one of the most common Java mistakes.
Shortcut. Neither call's return value is assigned, and a String never changes in place, so s prints exactly as declared.
Common trap. "PLACEMENT test" assumes both methods modify s in place; each builds a new String that is thrown away at once.
All Programming Fundamentals questions · placement mock tests