Consider the following Java code snippet. What will be printed to the console?
public class HeapTest { public static void main(String[] args) { String a = new String("hello"); String b = new String("hello"); System.out.println(a == b); System.out.println(a.equals(b)); } }
Remember that == compares references, and equals() compares content.
The new String("hello") creates two different objects in heap memory, so a == b is false. But their contents are the same, so a.equals(b) is true.
Choose the correct statement about Java heap memory.
Think about where objects and arrays live in Java.
Heap memory stores all objects and arrays and is shared among all threads. Primitive local variables are stored on the stack, not heap.
Analyze the following Java code. What error will it cause when run?
public class HeapOverflow { public static void main(String[] args) { int i = 0; while(true) { i++; int[] arr = new int[1000000]; System.out.println("Iteration: " + i); } } }
Think about what happens when you keep creating large arrays without releasing them.
The code keeps creating large arrays without references being freed, filling heap memory until it runs out, causing an OutOfMemoryError.
Which of the following Java code snippets correctly creates an object that will be stored in heap memory?
Remember how objects are created with new keyword.
Only new String("hello") creates a new object in heap memory. Option C uses a string literal which is stored in the string pool, not heap in the same way. Option C is invalid syntax, and D is invalid assignment.
Consider this Java code snippet. How many distinct objects are created in heap memory after it runs?
public class ObjectCount { public static void main(String[] args) { String s1 = "test"; String s2 = new String("test"); String s3 = s2.intern(); Integer i1 = 100; Integer i2 = new Integer(100); } }
Remember string literals, new keyword, and interning behavior.
Objects created: "test" literal (string pool), new String("test"), new Integer(100), and the Integer i1 = 100; uses cached Integer object (not new). The intern() returns the literal object, so no new object there. Total 4 objects.
