Bird
0
0

Consider this Java class:

hard📝 Application Q15 of 15
Java - Static Keyword
Consider this Java class:
class Employee {
    static int employeeCount = 0;
    String name;
    Employee(String name) {
        this.name = name;
        employeeCount++;
    }
    static void printCount() {
        System.out.println("Total employees: " + employeeCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee("Alice");
        Employee e2 = new Employee("Bob");
        e1.printCount();
        Employee.printCount();
    }
}

What will be the output when running Main?
ATotal employees: 1 Total employees: 2
BTotal employees: 2 Total employees: 1
CTotal employees: 2 Total employees: 2
DCompilation error due to calling static method on instance
Step-by-Step Solution
Solution:
  1. Step 1: Count employees created

    Two Employee objects are created, so employeeCount becomes 2.
  2. Step 2: Understand static method calls

    Calling printCount() on instance e1 or class Employee both print the same static variable value.
  3. Final Answer:

    Total employees: 2 Total employees: 2 -> Option C
  4. Quick Check:

    Static method prints shared count = 2 [OK]
Quick Trick: Static method prints shared count; instance call allowed [OK]
Common Mistakes:
  • Thinking static method can't be called on instance
  • Assuming employeeCount resets per object
  • Confusing output order or values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes