0
0
Javaprogramming~15 mins

Static methods in Java - Practice Problems & Coding Challenges

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Static Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output 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);
    }
}
A2
B0
C1
DCompilation error
Attempts:
2 left
🧠 conceptual
intermediate
1:30remaining
Static method access to instance variables
Which statement about static methods in Java is true?
AStatic methods can only access static variables directly.
BStatic methods can directly access instance variables without an object.
CStatic methods can access instance variables if they are declared final.
DStatic methods can access instance variables only if the class is final.
Attempts:
2 left
🔧 debug
advanced
2:00remaining
Identify 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();
    }
}
AOutput: 5
BRuntime error: NullPointerException
CCompilation error: non-static variable number cannot be referenced from a static context
DCompilation error: missing return statement
Attempts:
2 left
💻 code output
advanced
1:30remaining
Output 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);
    }
}
ACompilation error
B7
C34
D12
Attempts:
2 left
🚀 application
expert
2:30remaining
Static 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();
    }
}
ACompilation error
B2
C1
D0
Attempts:
2 left