Practice mode Java

Given class C { static int n = 0; C() { n++; } }, what does new C(); new C(); new C(); System.out.println(C.n); print?

Correct answer C. 3

Explanation

A static field has one copy per class, shared by every instance, however many objects are made. Each constructor call increments that same n, so after three objects it holds 3. If n were an instance field, each object would have its own copy, and the expression C.n would not even compile.

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.