Consider the following code segment:
public class VariablesExample {
public static void main(String[] args) {
int num1 = 5;
int num2 = 7;
final int num3 = 10;
double pi = 3.1415;
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
num3 = 20;
pi = 3.14;
System.out.println("num1: " + num1);
System.out.println("num2: " + num2);
System.out.println("num3: " + num3);
System.out.println("pi: " + pi);
}
}
What will be the output of the above code segment? Explain step-by-step what happens with the variables and constants in each statement of the code. If there is an error, explain the reason for the error.
A. num1: 7
num2: 5
num3: 20
pi: 3.14
B. num1: 7
num2: 5
num3: 10
pi: 3.14
C. Compilation Error: Cannot assign a value to a final variable.
D. Compilation Error: Incompatible types.
The output of the above code segment will be:
num1: 7
num2: 5
num3: 10
pi: 3.14
Explanation:
The code segment starts by declaring and initializing the variables num1
and num2
with values 5 and 7 respectively. Additionally, it declares and initializes the constant num3
with the value 10, and the variable pi
with the value 3.1415.
The next three lines of code swap the values of num1
and num2
without using a temporary variable. The values of num1
and num2
are swapped using arithmetic operations. After this swap, num1
will have the value 7 and num2
will have the value 5.
The line num3 = 20;
will result in a compilation error because num3
is declared as a final variable, and once assigned a value, it cannot be reassigned.
The line pi = 3.14;
changes the value of the variable pi
to 3.14.
Finally, the System.out.println()
statements print the values of the variables num1
, num2
, num3
, and pi
.
Therefore, the output will be num1: 7
, num2: 5
, num3: 10
, pi: 3.14
.
Option B is the correct answer.