Multiple choice technology programming languages

What gets printed when the following program is compiled and run. Select the one correct answer. class test { public static void main(String args[]) { int i,j,k,l=0; k = l++; j = ++k; i = j++; System.out.println(i); } }

  1. 0

  2. 1

  3. 2

  4. 3

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

The post-increment l++ assigns the current value 0 to k, then increments l to 1. Pre-increment ++k increments k to 1 first, then assigns 1 to j. Post-increment j++ assigns 1 to i, then increments j to 2. The output is 1.

AI explanation

To answer this question, let's go through each line of code and track the values of the variables:

  • int i,j,k,l=0;: This line declares four variables i, j, k, and l. l is initialized to 0.
  • k = l++;: The value of l is assigned to k first, and then l is incremented by 1. So, k becomes 0, and l becomes 1.
  • j = ++k;: k is incremented by 1 first, and then the value of k is assigned to j. So, k becomes 1, and j becomes 1.
  • i = j++;: The value of j is assigned to i first, and then j is incremented by 1. So, i becomes 1, and j becomes 2.
  • System.out.println(i);: The value of i is printed, which is 1.

Therefore, the correct answer is B) 1.