{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# arrays - Arrays Motivation for Arrays Suppose we want to...

This preview shows pages 1–3. Sign up to view the full content.

Arrays Motivation for Arrays Suppose we want to store 100 values entered by the user. Knowing what we do so far, we would have to declare 100 different variables to hold the information. This would be doable, but it would be a giant pain. Next, suppose we want to store a bunch of values entered by the user, but we don’t know how many – it might be 10, it might be 100,000. We could try to declare 100,000 variables, just in case, but even this wouldn’t work if the user decided to store more than that. To solve this problem, we need a convenient to store a list of values. Furthermore, we want this list to be able to hold any number of values, depending on the user’s needs. Java has a feature called an array that is used to store a variable number of elements. Single-Dimensional Arrays A single-dimensional array stores a list of elements of the same type. We can make this list be any size that we want. Declaration Here’s how to declare an array: type[] name; This will declare an array called name that can hold elements of type type . For example, to declare an array of int s called nums : int[] nums; Now, we need to create space for the array. Before we can add any elements to the array, we need to specify the number of slots we want to reserve. Here’s how: name = new type[size]; Here, name is the name of the array, type is the type of elements the array holds, and size is a positive integer that specifies how many slots we want in the array. size can be either a constant value (like 10) or an int variable. Here’s how to make our nums array have 10 slots: nums = new int[10]; We can also declare an array and reserve space for it on the same line: int[] nums = new int[10];

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document