We use primitive and reference storage to hold data in Java. Primitives store simple values directly, while references store addresses to objects.
Primitive vs reference storage in Java
public class PrimitiveVsReference { public static void main(String[] args) { // Primitive type example int number = 5; // Reference type example String text = new String("Hello"); } }
Primitive types store actual values directly in memory.
Reference types store a reference (address) to the object in memory.
int a = 10; int b = a; b = 20; System.out.println(a); // prints 10
String s1 = new String("Hi"); String s2 = s1; s2 = "Bye"; System.out.println(s1); // prints Hi
int[] arr1 = {1, 2, 3}; int[] arr2 = arr1; arr2[0] = 10; System.out.println(arr1[0]); // prints 10
int x = 5; int y = x; x = 7; System.out.println(y); // prints 5
This program shows how changing a copied primitive does not affect the original, but changing a copied reference affects the original object.
public class PrimitiveVsReference { public static void main(String[] args) { // Primitive example int originalNumber = 100; int copiedNumber = originalNumber; copiedNumber = 200; System.out.println("Original number: " + originalNumber); System.out.println("Copied number: " + copiedNumber); // Reference example int[] originalArray = {1, 2, 3}; int[] copiedArray = originalArray; copiedArray[0] = 99; System.out.print("Original array after change: "); for (int num : originalArray) { System.out.print(num + " "); } System.out.println(); System.out.print("Copied array after change: "); for (int num : copiedArray) { System.out.print(num + " "); } System.out.println(); } }
Time complexity for copying primitives is O(1) because it copies the value directly.
Copying references is also O(1) but both variables point to the same object, so changes affect both.
A common mistake is thinking that copying a reference creates a new object; it does not.
Use primitives for simple data and references for objects or collections.
Primitives store actual values; references store addresses to objects.
Changing a copied primitive does not affect the original; changing a copied reference affects the original object.
Understanding this helps avoid bugs and manage memory better in Java.
