1Z0-803 · Question #251
Given: public class X { static int i; int j; public static void main(String[] args) { X x1 = new X(); X x2 = new X(); x1.i = 3; x1.j = 4; x2.i = 5; x2.j = 6; System.out.println( x1.i + " "+ x1.j + " "
The correct answer is C. 5 4 5 6. This question assesses the understanding of static vs. instance variables in Java classes. Static variables are shared across all instances of a class, while instance variables are unique to each object.
Question
Given:
public class X { static int i; int j; public static void main(String[] args) { X x1 = new X(); X x2 = new X(); x1.i = 3; x1.j = 4; x2.i = 5; x2.j = 6; System.out.println( x1.i + " "+ x1.j + " "+ x2.i + " "+ x2.j); } } What is the result?
Options
- A3 4 5 6
- B3 4 3 6
- C5 4 5 6
- D3 6 4 6
How the community answered
(54 responses)- A2% (1)
- B6% (3)
- C83% (45)
- D9% (5)
Why each option
This question assesses the understanding of static vs. instance variables in Java classes. Static variables are shared across all instances of a class, while instance variables are unique to each object.
This would be the case if `i` was also an instance variable, meaning `x1.i` and `x2.i` were independent.
This incorrectly shows `x2.i` retaining the value of `x1.i` from an earlier assignment, ignoring the static nature of `i`.
The `i` variable is declared as `static`, meaning there is only one copy shared by all instances of the `X` class. When `x2.i = 5` is executed, it updates the single static `i` to 5, affecting both `x1.i` and `x2.i`. The `j` variable is an instance variable, so `x1.j` remains 4 and `x2.j` becomes 6.
This mixes up the values of `j` or implies incorrect assignments for either static or instance variables.
Concept tested: Java static vs. instance variables
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Topics
Community Discussion
No community discussion yet for this question.