In Java, what will be the output of the following program using a left shift inside a method (note pass-by-value of primitives)? public class Test { public static void leftshift(int i, int j) { i <<= j; } public static void main(String args[]) { int i = 4, j = 2; leftshift(i, j); System.out.println(i); } }

Difficulty: Easy

Correct Answer: 4

Explanation:


Introduction / Context:
This question checks understanding of Java’s pass-by-value semantics for primitives. Shifting a copy of a primitive parameter inside a method does not change the original variable in the caller.



Given Data / Assumptions:

  • Method leftshift takes two ints i and j.
  • It performs i <<= j on the parameter i.
  • Caller has i = 4, j = 2 and prints i after calling.


Concept / Approach:
Java passes primitives by value. That means the method receives a copy of i. Modifying i inside leftshift does not affect the caller’s i. Therefore, after the call, the original i is still 4.



Step-by-Step Solution:

Caller sets i = 4, j = 2.Call leftshift(i, j) → inside, parameter i becomes 4 << 2 = 16.Method returns; the caller’s i remains unchanged (still 4).Print i → prints 4.


Verification / Alternative check:
If the method returned the shifted value and the caller assigned it back (i = leftshift(i, j)), then the printed value would change. But here the method is void and no assignment occurs.



Why Other Options Are Wrong:
They assume pass-by-reference for primitives or that the method’s modification leaks into the caller.



Common Pitfalls:
Confusing Java’s reference semantics for objects with primitive pass-by-value; forgetting that only a returned value or a mutable object state can alter the caller.



Final Answer:
4

More Questions from Operators and Assignments

Discussion & Comments

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