nerdexam
Oracle

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.

Working with Selected Classes from the Java API

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)
  • A
    17% (9)
  • B
    72% (38)
  • C
    8% (4)
  • D
    4% (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.

Aacting

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.

BactionCorrect

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.

CCompilation fails

The code is syntactically correct and will compile without errors.

DAn exception is thrown at runtime

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

#String immutability#pass by value#method parameters

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice