Why Arrays Got Introduced?
Can arrays be replaced with primitives? This lesson teaches how arrays enhance algorithm performance and substitute primitive data types.
Let's take a step back and consider why we need arrays in the first place. 🤔
Why not make use of primitives?
In Java int
takes 4
bytes. So, the declaration below occupies 4
bytes of memory.
int a = 100;
What if we want to store six int
values (or 24
bytes)? We need to use six different variables individually, each occupying 4
bytes so that the total will be 6 * 4 = 24
bytes.
// each of the following occupies 4 bytes, which is 6 * 4 bytes
int a1 = 100;
int a2 = 200;
int a3 = 300;
int a4 = 400;
int a5 = 500;
int a6 = 600;
Creating six different variables is a bit dirty and not a good idea. What if we wanted to store a million entries? Are we supposed to create a million different variables? 😢 Isn't this bad coding?
Arrays to the rescue 🤩
Instead, we store the million items in an array sequentially in an int[] array
. This can be achieved easily by following the declaration and initialization with values.
int[] array = {100, 200, 300, 400, 500, 600};
Arrays are used for efficient data storage, quick access, and optimized memory usage.
Isn't the array beautiful? 😻