Java Tutorial/Arrays

Arrays are collections of other things. Their structure is as follows:

[0][1][2][3]...

Each [x] section is one of the "thing". As you can see, they begin not at 1 but at 0. An example of declaring an integer array:

More ways to Declare
An array can be declared like this:

type[]name;

It can be initialized like this:

name = new type[size];

You can combine those steps, but the types always have to match up:

Setting and Accessing Values
You can set a value in an array like this:

Each element in the array is just like a variable! You can do anything to it that you can do to a variable. Remember how we learned about for loops in the last lesson? Well, that can be used to set things in arrays:

Arrays of Arrays
You can make 2D arrays, 3D arrays, and even 4D and 5D arrays!! Here is how:

Then, you can use a simple double for loop to set them:

Using Arguments
Have you been dying to know what the  within the main method is? Well, if you have (and also if you haven't, because you should know), read onwards!

It is just an array with the ones you have been playing with (hopefully) in the rest of this lesson. Try executing the command:

Notice how it doesn't say anything. Where is the "hello hello hello" going? Well, it is going into the arguments (args) array.

The array would be something like:

["hello"]["hello"]["hello"] << length of 3

You can access these in your class. Here is an example that prints the arguments that you send into it:

With the command, the program would output a single line saying "hello".

Uses of Arrays
So... what can you do with these things? Well, you can make (as an example) the basics of a bank account now!

Exercises

 * Make the bank account program print the accounts it received
 * Now edit it so that it removes 1 from each account, and then prints the values

An example of a valid answer: