Question 8
Back to Exercise
What is the output of the following Java program?
class User {
static int total = 0; // shared by all objects
int logins = 0; // one per object
void login() { logins++; total++; }
}
public class Main {
public static void main(String[] args) {
User a = new User(), b = new User();
a.login(); a.login(); b.login();
System.out.println(a.logins + " " + b.logins + " " + User.total + " " + a.total);
}
}
- A 2 1 3 3 Correct
- B 2 1 3 2
- C 3 3 3 3
- D 2 1 1 2
Correct Answer: Option A
A static field exists once for the class, so every login increments the same total.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!