0
0
Javaprogramming~20 mins

Reference data types in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reference Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Java code with String references?
Consider the following Java code snippet. What will be printed when it runs?
Java
public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = a;
        a = "world";
        System.out.println(b);
    }
}
Ahello
Bworld
Cnull
DCompilation error
Attempts:
2 left
💡 Hint
Remember that Strings are immutable and variables hold references.
Predict Output
intermediate
2:00remaining
What is the output of this Java code with arrays and references?
Look at this Java code. What will it print?
Java
public class Main {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = arr1;
        arr2[0] = 10;
        System.out.println(arr1[0]);
    }
}
ACompilation error
B10
C0
D1
Attempts:
2 left
💡 Hint
Arrays are objects and variables hold references to them.
🔧 Debug
advanced
2:00remaining
What error does this Java code produce?
Examine this Java code. What error will it cause when compiled or run?
Java
public class Main {
    public static void main(String[] args) {
        String s = null;
        if (s.equals("test")) {
            System.out.println("Match");
        }
    }
}
AArrayIndexOutOfBoundsException
BCompilation error: cannot call method on null
CNo output, program runs fine
DNullPointerException at runtime
Attempts:
2 left
💡 Hint
Calling a method on a null reference causes an error.
🧠 Conceptual
advanced
2:00remaining
How many objects are created in this Java code?
Consider this Java code snippet. How many distinct objects are created in memory?
Java
public class Main {
    public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = "abc";
        String s3 = s1;
    }
}
A3
B1
C2
D0
Attempts:
2 left
💡 Hint
Remember string literals and new String() create objects differently.
Predict Output
expert
2:00remaining
What is the output of this Java code with object references and mutation?
Analyze this Java code. What will it print?
Java
class Box {
    int value;
    Box(int v) { value = v; }
}

public class Main {
    public static void main(String[] args) {
        Box b1 = new Box(5);
        Box b2 = b1;
        b2.value = 10;
        b1 = new Box(20);
        System.out.println(b2.value);
    }
}
A10
B5
C20
DCompilation error
Attempts:
2 left
💡 Hint
Changing b1 to a new object does not affect b2's reference.