0
0
Javaprogramming~15 mins

Why static is needed in Java - Challenge Your Understanding

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Static Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 conceptual
intermediate
2:00remaining
Why use static methods in Java?

In Java, why do we use static methods instead of instance methods sometimes?

AStatic methods are slower because they need an object to run.
BStatic methods can access instance variables directly without an object.
CStatic methods are used only for private data hiding.
DStatic methods belong to the class and can be called without creating an object.
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Output of static vs instance variable access

What is the output of this Java code?

Java
class Test {
    static int count = 0;
    int id;
    Test() {
        count++;
        id = count;
    }
    public static void main(String[] args) {
        Test a = new Test();
        Test b = new Test();
        System.out.println(a.id + "," + b.id + "," + Test.count);
    }
}
A1,2,2
B2,2,2
C1,1,2
D0,0,0
Attempts:
2 left
💻 code output
advanced
2:00remaining
What error occurs when accessing instance variable from static method?

What error does this Java code produce?

Java
class Demo {
    int x = 5;
    static void show() {
        System.out.println(x);
    }
    public static void main(String[] args) {
        show();
    }
}
ACompile-time error: non-static variable x cannot be referenced from a static context
BRuntime NullPointerException
CPrints 5
DCompile-time error: missing return statement
Attempts:
2 left
🧠 conceptual
advanced
2:00remaining
Why is static block used in Java?

What is the main purpose of a static block in Java?

ATo initialize instance variables before constructor runs
BTo initialize static variables when the class is loaded
CTo execute code only when an object is created
DTo override static methods
Attempts:
2 left
🚀 application
expert
3:00remaining
How many objects are created and what is output?

Consider this Java code. How many objects are created and what is printed?

Java
class Counter {
    static int count = 0;
    Counter() {
        count++;
    }
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = c2;
        System.out.println(count);
    }
}
A3 objects created, prints 3
B3 objects created, prints 2
C2 objects created, prints 2
D2 objects created, prints 3
Attempts:
2 left