1Z0-803 · Question #83
What is the result? Class StaticField { static int i = 7; public static void main(String[] args) { StaticFied obj = new StaticField(); obj.i++; StaticField.i++; obj.i++; System.out.println(StaticField
The correct answer is A. 10 10. Static variables in Java are class-level variables, meaning there is only one copy shared by all instances of the class and accessible via both class and object references.
Question
What is the result? Class StaticField { static int i = 7; public static void main(String[] args) { StaticFied obj = new StaticField(); obj.i++; StaticField.i++; obj.i++; System.out.println(StaticField.i + " "+ obj.i); } }
Options
- A10 10
- B8 9
- C9 8
- D7 10
How the community answered
(21 responses)- A81% (17)
- B5% (1)
- C5% (1)
- D10% (2)
Why each option
Static variables in Java are class-level variables, meaning there is only one copy shared by all instances of the class and accessible via both class and object references.
The `i` variable is declared as `static`, making it a class variable. All references to `i`, whether through an object (`obj.i`) or the class itself (`StaticField.i`), access and modify the same single variable. Initially `i` is 7. `obj.i++` makes `i=8`. `StaticField.i++` makes `i=9`. `obj.i++` makes `i=10`. Thus, both `StaticField.i` and `obj.i` will print 10.
This answer incorrectly implies that `obj.i` and `StaticField.i` would hold different values after increments, failing to recognize that a static field is shared.
This answer incorrectly assumes that `obj.i` and `StaticField.i` are distinct variables after operations, which is false for a static field.
This answer incorrectly suggests that `StaticField.i` would remain 7 or that the values would diverge in a way inconsistent with a shared static variable.
Concept tested: Java static variables, class vs instance fields
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Topics
Community Discussion
No community discussion yet for this question.