Answer to Question #276116 in Java | JSP | JSF for Candy

Question #276116

What is the result of the following program?

Consider the following code fragment

Rectangle r1 = new Rectangle();

r1.setColor(Color.red);

Rectangle r2 = r1;

r2.setColor(Color.blue);

After the above piece of code is executed, what are the colors of r1 and r2 (in this order)?


1
Expert's answer
2021-12-09T01:23:34-0500

Code

public class MyClass {
    public static void main(String args[]) {
      Rectangle r1 = new Rectangle();
      r1.setColor(Color.RED);
      Rectangle r2 = r1;
      r2.setColor(Color.BLUE);
      
      System.out.println(r1.getColor());
      System.out.println(r2.getColor());
    }
    static enum Color {
        RED, BLUE
    }
    static class Rectangle {
        private Color color;
        public void setColor(Color color) {
            this.color = color;
        }
        public Color getColor() {
            return this.color;
        }
    }
}

Output:

BLUE
BLUE

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS