LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 8

An instance field and a static field Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links