Multiple choice technology programming languages

public class test { public static void main(String [] args) { int x = 5; test t = new test(); t.doStuff(x); System.out.print("main x = " + x); } void doStuff(int x) { System.out.print("doStuff x = " + x++); } } What is the result?

  1. doStuff x = 6 main x = 6

  2. doStuff x = 5 main x = 6

  3. doStuff x = 5 main x = 5

  4. Compilation fails

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

Java passes primitives by value. The main method passes x=5 to doStuff, which receives a copy. Inside doStuff, x++ increments the copy AFTER printing its current value (5). The original x in main remains unchanged. Output: 'doStuff x = 5' then 'main x = 5'. Option C is correct. If x were an object reference, behavior would differ.

AI explanation

To answer this question, let's go through the code step by step:

  1. In the main method, an integer variable x is declared and assigned the value of 5.
  2. An instance of the test class is created using the new keyword and assigned to the variable t.
  3. The doStuff method of the test class is called with the argument x.
  4. Inside the doStuff method, the value of x is printed, which is initially 5. Then, the x++ expression is evaluated, which increments the value of x by 1.
  5. The main method continues executing after the doStuff method call and prints the value of x, which is still 5.

Therefore, the output of the program is: doStuff x = 5 main x = 5

So, the correct answer is C. doStuff x = 5 main x = 5.