Slides Arrays Arrays Part 1
Slides Arrays Arrays Part 1
Lets look at ways to store, and manipulate, multiple values of the same type.
The most common way to do this, in Java, is with an array.
An array is a data structure, that allows you to store a sequence of values, all of the same
type.
You can have arrays for any primitive type, like ints, doubles, booleans, or any of the 8
primitives we've learned about.
You can also have arrays for any class.
Stored values in an array with 5 elements "Andy" "Bob" "Charlie" "David" "Eve"
The square brackets can follow the type as shown in the first two
examples.
The brackets can also be after the variable name, as shown in the
last example.
One way to instantiate the array, is with the new keyword, much as we've seen, with most
of the classes we've used to date, with the exception of String.
On this slide, we have an array declaration on the left of the equals sign, and then an array
creation expression on the right side.
For comparison, I'm showing you a typical array variable declaration, and a class instance,
or object creation expression, using the StringBuilder class.
They look pretty similar, but there are two major differences.
Square brackets are required when using the new keyword, and a size is specified between
them. So in this example, there will be 10 elements in the array.
An array instantiation doesn't have a set of parentheses, meaning we can't pass data to a
constructor for an array.
In fact, using parentheses with an array instantiation, gives you a compiler error.
You can't change the size of an array, after the array is instantiated.
We can't add or delete elements, we can only assign values to one of the ten elements in
this array, in this example.
In this example, you can see we still use the new keyword, and have int, with the square
brackets.
But here we specify the values, we want the array to be initialized to, in a comma delimited
list, in curly braces.
Because these values are specified, the length of the array can be determined, so we don't
specify the size in the square brackets.
And actually, Java provides an even simpler way to do this.