0
0
Javaprogramming~15 mins

Object lifetime in Java - Practice Problems & Coding Challenges

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Object Lifetime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
What is the output of this Java code involving object references?

Consider the following Java code snippet. What will be printed when it runs?

Java
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);
    }
}
A10
BCompilation error
C20
D0
Attempts:
2 left
💻 code output
intermediate
2:00remaining
What happens to the object after null assignment?

What will be the output of this Java program?

Java
public class Main {
    public static void main(String[] args) {
        String s = new String("hello");
        s = null;
        System.out.println(s);
    }
}
Ahello
BRuntime NullPointerException
CCompilation error
Dnull
Attempts:
2 left
💻 code output
advanced
2:00remaining
What is the output when an object is eligible for garbage collection?

Consider this Java code. What will be printed?

Java
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");
    }
}
AEnd of main
BCompilation error
CFinalize called\nEnd of main
DRuntime error
Attempts:
2 left
🔧 debug
advanced
2:00remaining
Identify the error related to object lifetime and references

What error will this Java code produce when compiled or run?

Java
public class Main {
    public static void main(String[] args) {
        String s;
        System.out.println(s);
    }
}
ARuntime NullPointerException
BCompilation error: variable s might not have been initialized
CPrints null
DCompilation error: cannot find symbol s
Attempts:
2 left
🧠 conceptual
expert
2:00remaining
How many objects are eligible for garbage collection after this code?

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;
A2
B1
C0
D3
Attempts:
2 left