nerdexam
Oracle

1Z0-808 · Question #23

public class TestScope { public static void main (String[] args) { int var1 = 200; System.out.print (doCalc(var1)); System.out.print ("+var1); } static int doCalc (int var1) { var1 = var1 * 2…

The correct answer is A. 400 200. Option A is correct because Java passes primitive values by copy, not by reference. When var1 = 200 from main is passed to doCalc, the method receives its own separate copy named var1. Doubling it to 400 inside doCalc only affects the local parameter - the original var1 in main…

Working with Methods and Encapsulation

Question

public class TestScope { public static void main (String[] args) { int var1 = 200; System.out.print (doCalc(var1)); System.out.print ("+var1); } static int doCalc (int var1) { var1 = var1 * 2; return var1; } } What is the result?

Options

  • A400 200
  • B200 200
  • C400 400
  • DCompilation fails.

How the community answered

(27 responses)
  • A
    89% (24)
  • C
    7% (2)
  • D
    4% (1)

Explanation

Option A is correct because Java passes primitive values by copy, not by reference. When var1 = 200 from main is passed to doCalc, the method receives its own separate copy named var1. Doubling it to 400 inside doCalc only affects the local parameter - the original var1 in main remains 200. So the first print outputs 400 (the returned value) and the second outputs 200 (the unchanged original).

B (200 200) is wrong because doCalc genuinely returns var1 * 2 = 400, not the original value. C (400 400) is wrong because Java is not pass-by-reference - the method's local var1 and main's var1 are completely independent variables that merely share a name. D is wrong because the code compiles and runs without errors.

Memory tip: In Java, primitive types (int, double, etc.) are always passed by value - think of it as handing someone a photocopy of a document. They can scribble all over their copy, but your original stays clean.

Topics

#variable scope#method parameters#pass-by-value#local variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice