0
0
Javaprogramming~15 mins

Primitive vs reference storage in Java - Practice Questions

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Java Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output of primitive and reference variable changes
What is the output of the following Java code?
Java
public class Test {
    public static void main(String[] args) {
        int a = 5;
        int b = a;
        b = 10;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
Aa = 5\nb = 10
Ba = 5\nb = 5
Ca = 10\nb = 10
Da = 10\nb = 5
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Output when modifying an object reference
What is the output of this Java code?
Java
public class Test {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = arr1;
        arr2[0] = 10;
        System.out.println(arr1[0]);
    }
}
A1
B10
CCompilation error
D0
Attempts:
2 left
💻 code output
advanced
2:00remaining
Effect of reassigning object references
What is the output of this Java code?
Java
public class Test {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder("Hello");
        StringBuilder sb2 = sb1;
        sb2.append(" World");
        sb2 = new StringBuilder("New");
        System.out.println(sb1.toString());
    }
}
ANew
BHello
CHello World
DCompilation error
Attempts:
2 left
💻 code output
advanced
2:00remaining
Output when passing primitives and objects to methods
What is the output of this Java code?
Java
public class Test {
    public static void main(String[] args) {
        int x = 5;
        StringBuilder sb = new StringBuilder("Hi");
        modify(x, sb);
        System.out.println(x + " " + sb.toString());
    }
    static void modify(int a, StringBuilder b) {
        a = 10;
        b.append(" there");
    }
}
A5 Hi
B10 Hi there
C10 Hi
D5 Hi there
Attempts:
2 left
🧠 conceptual
expert
2:00remaining
Understanding memory behavior of primitives and references
Which statement best describes how Java stores primitive types and reference types in memory?
APrimitive variables store the actual data value; reference variables store the memory address of the object.
BPrimitive variables store the memory address of the object; reference variables store the actual data value.
CBoth primitive and reference variables store actual data values directly in the stack memory.
DBoth primitive and reference variables store memory addresses pointing to objects in the heap.
Attempts:
2 left