Introduction to Arrays

An array keeps several values of the same type together in one fixed-size container, like eggs in a carton.

Novice · Java · Updated

By

Arrays represent a foundational concept in programming. They allow you to work with multiple related variables as a group rather than individual variables.

Consider purchasing eggs. Even if you purchase eggs individually, like at a farmers' market, you would still put them in a container to take them home.

Twelve loose eggs with nothing holding them together, like separate variables

Think of each egg as a variable. Just like you want to store all eggs together, we often need to group our variables together. An egg carton is like an Array. It is a container that is optimized for storing eggs.

A dozen eggs held together in one carton, the way an array holds values together

Arrays are fixed in size. In other words, if you have a 6 pack of eggs, you can't simply stretch it to fit 12 eggs. You would need to get a bigger carton and move the 6 eggs from the smaller carton to the bigger one.

A 6-egg carton next to a 12-egg carton: to hold more eggs you need a new, bigger carton

Arrays are containers that hold similar items. You would not buy a dozen eggs and put them in a 12-pack box of soda. Similarly, you would not create an Array of Strings and try to store numbers in it.

An egg carton next to a 12-pack of soda: each container is made for one kind of item

Cheat sheets