Consider the following Java code snippet. What will be printed when it runs?
class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box b1 = new Box(10); Box b2 = b1; b2.value = 20; System.out.println(b1.value); } }
Remember that both variables point to the same object in memory.
Both b1 and b2 refer to the same Box object. Changing b2.value changes the same object that b1 points to, so printing b1.value outputs 20.
What will be the output of this Java program?
public class Main { public static void main(String[] args) { String s = new String("hello"); s = null; System.out.println(s); } }
What does printing a null reference print?
Assigning null to s means it no longer points to the string object. Printing s prints the string "null".
Consider this Java code. What will be printed?
class Demo { protected void finalize() { System.out.println("Finalize called"); } } public class Main { public static void main(String[] args) { Demo d = new Demo(); d = null; System.gc(); System.out.println("End of main"); } }
Garbage collection and finalize timing is unpredictable.
The finalize() method may not run immediately or at all before the program ends. So only "End of main" is guaranteed to print.
What error will this Java code produce when compiled or run?
public class Main { public static void main(String[] args) { String s; System.out.println(s); } }
Local variables must be initialized before use.
The local variable s is declared but not initialized. Java requires local variables to be assigned before use, so this causes a compilation error.
Given the following code, how many objects are eligible for garbage collection immediately after line 10?
1: class Node {
2: Node next;
3: Node() { next = null; }
4: }
5:
6: Node a = new Node();
7: Node b = new Node();
8: a.next = b;
9: b = null;
10: a = null;Think about which objects have no references after line 10.
After line 10, both a and b are null. The two Node objects created have no references and are eligible for garbage collection.
