Complete the code to declare a static variable in Java.
public class Example { public [1] int count = 0; }
The keyword static makes the variable belong to the class, not instances.
Complete the code to call a static method from the class without creating an object.
public class Calculator { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int sum = Calculator.[1](5, 3); System.out.println(sum); } }
The static method add is called using the class name without creating an object.
Fix the error in accessing a non-static variable from a static method by completing the code.
public class Counter { static int count = 0; public static void increment() { [1]++; } }
To access a non-static variable from a static method, you must use an object or make the variable static. Here, using Counter.count assumes count is static.
Fill both blanks to create a static method that returns the square of a number.
public class MathUtil { public [1] int square(int num) { return num [2] num; } }
The method is declared static so it belongs to the class. The multiplication operator * calculates the square.
Fill all three blanks to create a static block that initializes a static variable.
public class Config { public static String setting; static [1] { setting = [2]; } public static void main(String[] args) { System.out.println([3]); } }
The static block runs once to initialize the static variable setting with the value "default". Then it is printed in main.
