Java programming — Effect of passing primitives and updating a static field: class Test { static int s; public static void main(String [] args) { Test p = new Test(); p.start(); System.out.println(s); } void start() { int x = 7; twice(x); System.out.print(x + " "); } void twice(int x) { x = x*2; s = x; } }

Difficulty: Easy

Correct Answer: 7 14

Explanation:


Introduction / Context:
This checks two ideas: primitives are passed by value, and static fields are shared across instances and can be set inside instance methods.



Given Data / Assumptions:

  • Local variable x is 7 inside start().
  • twice(x) multiplies its parameter and stores the result in static s.


Concept / Approach:
Because primitives are passed by value, the caller's x does not change. However, setting the static variable s persists and can be printed later in main.



Step-by-Step Solution:

Inside twice: x becomes 14 locally; assign s = 14.Back in start: local x remains 7; print "7 ".Back in main: print s which is 14; combined output is "7 14".


Verification / Alternative check:
Print x again after twice to confirm no change, and print s to confirm update.



Why Other Options Are Wrong:
They assume x changed in caller or that s was not updated.



Common Pitfalls:
Expecting call-by-reference semantics for primitives; misunderstanding static field scope.



Final Answer:
7 14

More Questions from Operators and Assignments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion