Challenge - 5 Problems
Static Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of static method call
What is the output of the following Java program?
Java
public class Test { static int count = 0; public static void increment() { count++; } public static void main(String[] args) { increment(); increment(); System.out.println(count); } }
Attempts:
2 left
💡 Hint
Static methods can access static variables directly.
✗ Incorrect
The static method increment() increases the static variable count by 1 each time it is called. It is called twice, so count becomes 2.
🧠 Conceptual
intermediateStatic method access to instance variables
Which statement about static methods in Java is true?
Attempts:
2 left
💡 Hint
Think about what static means in relation to objects.
✗ Incorrect
Static methods belong to the class, not to any object instance, so they cannot access instance variables directly. They can only access static variables directly.
🔧 Debug
advancedIdentify the error in static method usage
What error will this code produce?
Java
public class Example { int number = 5; public static void printNumber() { System.out.println(number); } public static void main(String[] args) { printNumber(); } }
Attempts:
2 left
💡 Hint
Static methods cannot access instance variables directly.
✗ Incorrect
The static method printNumber() tries to access the instance variable number without an object reference, which causes a compilation error.
❓ Predict Output
advancedOutput of static method with parameters
What is the output of this Java program?
Java
public class Calculator { public static int multiply(int a, int b) { return a * b; } public static void main(String[] args) { int result = multiply(3, 4); System.out.println(result); } }
Attempts:
2 left
💡 Hint
Static methods can take parameters and return values.
✗ Incorrect
The static method multiply returns the product of 3 and 4, which is 12.
🚀 Application
expertStatic method call from instance method
Consider this Java class. What will be the output when main runs?
Java
public class Counter { private static int count = 0; public void increment() { count++; } public static void printCount() { System.out.println(count); } public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); c1.increment(); c2.increment(); printCount(); } }
Attempts:
2 left
💡 Hint
Static variables are shared across all instances.
✗ Incorrect
Both c1 and c2 increment the same static variable count, so after two increments, count is 2.
