1Z0-803 · Question #146
Given: class X { static void m(String s1) { s1 = "acting"; } public static void main(String[] args) { String s2 = "action"; m(s2); System.out.println(s2); } } What is the result?
The correct answer is B. action. This question tests the understanding of String immutability and how object references are passed by value in Java, specifically when a method reassigns its parameter.
Question
Given:
class X { static void m(String s1) { s1 = "acting"; } public static void main(String[] args) { String s2 = "action"; m(s2); System.out.println(s2); } } What is the result?
Options
- Aacting
- Baction
- CCompilation fails
- DAn exception is thrown at runtime
How the community answered
(53 responses)- A17% (9)
- B72% (38)
- C8% (4)
- D4% (2)
Why each option
This question tests the understanding of String immutability and how object references are passed by value in Java, specifically when a method reassigns its parameter.
The method `m` reassigns its local parameter `s1` to 'acting', but this does not affect the `s2` variable in the `main` method because String objects are immutable and references are passed by value.
In Java, String objects are immutable, and object references are passed by value; therefore, the assignment `s1 = "acting"` inside method `m` only reassigns the local parameter `s1` to a new String object, leaving the `s2` variable in `main` pointing to its original 'action' String.
The code is syntactically correct and will compile without errors.
There are no operations in the code that would lead to a runtime exception.
Concept tested: String immutability, pass-by-value for references
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Topics
Community Discussion
No community discussion yet for this question.