219k views
5 votes
Consider the following code fragment

Rectangle r1 = new Rectangle();
r1.setColor(Color.blue);
Rectangle r2 = r1;
r2.setColor(Color.red);

After the above piece of code is executed, what are the colors of r1 and r2 (in this order)?
(a) Color.blue
Color.red
(b) Color.blue
Color.blue
(c) Color.red
Color.red
(d) Color.red
Color.blue
(e) None of the above.

1 Answer

6 votes

Final answer:

After the code fragment is executed, both r1 and r2 will have the color Color.red.

Step-by-step explanation:

After the code fragment is executed, both r1 and r2 will have the color Color.red.

When the code Rectangle r2 = r1; is executed, the reference to r1 is assigned to r2. This means that both r1 and r2 are referencing the same object in memory. Therefore, any changes made to r2 will also affect r1.

So when r2.setColor(Color.red); is called, it changes the color of the shared object to Color.red. Both r1 and r2 will reflect this change, resulting in the colors being Color.red for both.

User Sidara KEO
by
9.2k points