Arrays: Reference Types with Special Syntax
What You'll Learn
You'll discover that arrays, despite their special bracket syntax, are actually objects created with new that store references to their element data on the heap.
Arrays Are Objects in Disguise
Even though arrays look different from typical objects (using [] instead of method calls), they are reference types just like any other object in Java. When you create an array, you're creating an object on the heap, and your array variable holds a reference to that object.
Creation with new
Remember from earlier lessons that objects are created using the new keyword and allocated on the heap. Arrays are no exception:
int[] numbers = new int[5]; // Creates an array object on the heap
String[] names = new String[3]; // Also creates an object on the heap
The new keyword allocates memory on the heap for the array object, which includes:
- The array's length
- Storage space for the elements (or references to elements, if they're reference types)
Why the Special Syntax?
Arrays get special treatment in Java's syntax because they're so fundamental and frequently used. Instead of calling methods like array.get(0) or array.set(0, value), you use the bracket notation array[0]. But underneath, it's still an object with its data stored on the heap.
Think of It This Way
Imagine arrays as special boxes that Java lets you open with square brackets instead of a key. The box itself still lives in the same warehouse (heap) as all other objects, and your variable is still just an address pointing to that box.
Key Takeaway: Arrays are full-fledged objects created with new and stored on the heap; Java simply provides bracket syntax as convenient shorthand for accessing their elements.