Practice mode Java

Given class P { int v = 1; }, what does P a = new P(); P b = a; b.v = 7; System.out.println(a.v); print?

Correct answer D. 7

Explanation

The assignment b = a copies the reference, not the object, so a and b both point to the single P created by new. Changing b.v therefore changes the field that a.v reads, and 7 is printed. The tempting answer 1 assumes assignment clones objects, which Java never does for reference types.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.