Java programming — Primitives are passed by value; confirm behavior with boolean: class Test { public static void main(String [] args) { Test p = new Test(); p.start(); } void start() { boolean b1 = false; boolean b2 = fix(b1); System.out.println(b1 + " " + b2); } boolean fix(boolean b1) { b1 = true; return b1; } }

Difficulty: Easy

Correct Answer: false true

Explanation:

Introduction / Context:This question confirms that Java passes primitives by value, so reassigning a parameter inside a method does not change the caller's variable.

Given Data / Assumptions:

  • Main creates b1 as false and calls fix(b1).
  • fix assigns true to its local parameter and returns it.

Concept / Approach:Primitives are copied when passed to methods. Changing the local copy does not affect the original variable. The return value may differ from the original.

Step-by-Step Solution:

Before call: b1 is false.In fix: local b1 becomes true; method returns true.Back in start: original b1 remains false; b2 receives true.Prints "false true".

Verification / Alternative check:Print identity or use different names to emphasize the copy behavior.

Why Other Options Are Wrong:They imply call-by-reference semantics, which Java does not use for primitives.

Common Pitfalls:Assuming Java can pass primitives by reference; only object references are passed by value (and still by value).

Final Answer:false true

More Questions from Operators and Assignments

Discussion & Comments

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