In Java, why do we use static methods instead of instance methods sometimes?
Think about calling a method without making a new object.
Static methods belong to the class itself, so you can call them without creating an object. Instance methods need an object to work because they can access instance variables.
What is the output of this Java code?
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); } }
Count is static and shared, id is instance-specific.
Each new object increments the static count. The first object gets id 1, second gets id 2, and count is 2.
What error does this Java code produce?
class Demo { int x = 5; static void show() { System.out.println(x); } public static void main(String[] args) { show(); } }
Static methods cannot access instance variables directly.
Static methods belong to the class and do not have access to instance variables without an object. Trying to access 'x' causes a compile-time error.
What is the main purpose of a static block in Java?
Think about when static variables get their values.
Static blocks run once when the class loads and are used to initialize static variables or run setup code.
Consider this Java code. How many objects are created and what is printed?
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); } }
Remember that assigning c3 = c2 does not create a new object.
Only two new objects are created with 'new'. The assignment c3 = c2 points to existing object. The static count increments twice, so prints 2.
