nerdexam
Oracle

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.

Java Basics

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)
  • A
    81% (17)
  • B
    5% (1)
  • C
    5% (1)
  • D
    10% (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.

A10 10Correct

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.

B8 9

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.

C9 8

This answer incorrectly assumes that `obj.i` and `StaticField.i` are distinct variables after operations, which is false for a static field.

D7 10

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

#static members#class variables#object state

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice