Given the code fragment:
What is the result?
Given the code fragment:
What is the result?
In the code, the `Pet` class has a static `name` attribute, meaning that there is only one shared `name` field among all instances of `Pet`. Initially, `p` is created with the name 'Dog', and then `p1` is assigned to `p`. When `p1.name` is set to 'Cat', this changes the static `name` field to 'Cat'. Both `p` and `p1` refer to this shared static field. Therefore, when `System.out.println(p.name)` is called, it prints 'Cat'. Even after setting `p` to `null`, `p1` still holds a reference to the `Pet` object, and the shared `name` field is still 'Cat'. Hence, printing `p1.name` also results in 'Cat'. Thus, the output is: 'Cat - Cat'.
package q50; public class Q50 { public static void main(String[] args) { Pet p = new Pet("Dog"); Pet p1 = p; p1.name = "Cat"; p = p1; System.out.println(p.name); p = null; System.out.println(p1.name); } } class Pet { public static String name; public Pet(String name) { this.name = name; } public String name() { return name; } public void setName(String name) { this.name = name; } } // Result: // Cat // Cat
B is correct answer