233k views
0 votes
What is the output of the following piece of code?

java

int x,y,z;
x=3;
y=5;
z=7;
z=x=y;
System.out.println(x+" "+ y +" "+ z);
a. 3 5 7
b. 5 7 5
c. 15 15 15
d. 3 3 3
e. 5 3 7
f. 5 5 5
g. 7 7 7

User Sharno
by
8.0k points

1 Answer

1 vote

Final answer:

The code will output "5 5 5" because of the chained assignment which assigns the value 5 to x, y, and z sequentially.

Step-by-step explanation:

The output of the provided piece of Java code will be determined by the assignment operations. The line z=x=y; is an example of chained assignment, which assigns the value from right to left. This means that the value of y, which is 5, is assigned to x, and then this new value of x, which is now 5, is assigned to z. Hence, all three variables x, y, and z will have the value 5 after the execution of this statement.

The correct answer is therefore (f) 5 5 5.

When System.out.println(x+" "+ y +" "+ z); is executed, it prints the values of x, y, and z separated by spaces. Since all variables have the value 5, the output will be "5 5 5".

User Danielstn
by
7.6k points