Introduction
So far you’ve learnt what methods and variables are and how to use them. In the case of variables you have also seen, how to get a user’s input and store it. If you want to store multiple inputs of the same type, for example numbers for a calculator, you’ll have to create different variables for each input, right?
In this part you’ll learn, how to store multiple values into one variable (sort of).
Solution to the last exercise
The exercise was:
Answer the following questions!
- What will be printed to the console when you call printX?
- Which x will be altered? The global one or the method’s one?
- What happens if you print out x in the main method (with the println-method)?
- 9999 will be printed out, because you call the method printX, which has a parameter x, which is valid inside the method. Then in the first line of the printX method, 9999 is assigned to x, which is printed afterwards. So 9999 will always be shown on the console.
- The method’s x will be altered. If you’d like to alter the global x, you have to tell the compiler to alter the global x. You’ll learn how you can do that later in this series.
- If you print out the x in the main method, the global x will be printed out, because the main method doesn’t know about the local x in the printX method. This is due to the scope of the variable. A variable is always just valid in a specific context. The global one is valid in the whole code file, the method’s parameters are only valid inside the method.
Something theoretical before we start
In part two of this series I told you, that you can store exactly one value into a variable. Now we’ll talk about arrays, which (sort of) allow you, to store multiple values in one variable. So did I tell you the truth in part 2?
Well discussing this is beyond the scope of this series, as this series is for beginners. So image an array as a type of variable (in fact it’s something special, similar to the string) that holds multiple variables which hold single values. An array is like a box of chocolates. A box contains multiple, but a fixed number, of storage spaces for chocolates. Each chocolate is the same same size and you can access all of them individually. In our example the chocolates hold a certain value each, let’s say their filling.
And now you know the key features of arrays:
- Fixed length
- Fixed variable type
Declaring arrays
Imagine you want a user to input 10 values to draw a graph on the screen. How would you do this?
Obviously you could just use 10 different variables and ask the user to input 10 numbers:
private int point0; private int point1; private int point2; ... private int point9;
As you can see, this is a pretty bad solution, because it takes up a lot of space in your code and it makes it less readable. And this is just the beginning. You’ll also have to get the input and draw each variable at once. And the worst thing is, that nothing is exchangeable. You’ll have to alter your code a lot to change it’s functionality, as everything is hardcoded.
But there are arrays, which allow you to store multiple values together and make your code look more clean, easier to read and easier to modify:
private int[] points = new int[10];
In the snippet above you can see how to declare and instantiate an array. The line basically means: Create an array, which will hold integer variables. Make the array 10 fields long, so I can store 10 integers in it.
As you can see, the ‘new’-keyword is used. This shows you, that arrays are objects, even though they are instantiated a special way. However, we’ll look at objects later in this series.
Write to arrays, read from arrays
We created a new array in the above section, but it is still empty, so we have to fill it. Like I said above, you can imagine an array like a box of chocolates. In this case, our array has space for 10 chocolates (integers), which are all laid out in one line. I’ve added the indices of the storage places to the table below (Note that an array’s index always starts with 0):
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Value |
As you can see, our array is empty. If we want to save a new value to the space with the index 5, we have to write:
points[5] = 1337;
Our array now looks like this:
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Value | 1337 |
Now we’ll set the array’s field with the index 0 and we’ll update the field at index 5:
points[0] = 24; points[5] = -1;
Our array looks like this now:
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Value | 24 | -1 |
You should get the trick. Now let’s see how to read a value from an array. The following snippet will output the value of the array with the index 5:
int index5 = points[5]; System.out.println(index5);
As you can see, you can read an array’s value at an index easily. Don’t forget to tell the compiler which value of the array you want, by giving it the index, otherwise it’ll give you the array! The index is always written in between the brackets! The following snippet shows you how to not read an array’s value at an index:
// Wrong! // points itself is an int-array // points[index] is an integer int index6 = points;
Reading an array like this will always give you a variable with the type of the array and the value at the array’s index.
Syntax
Array declaration and instantiation:
(access_mod) field_type[] array_name = new field_type[array_length];
Example:
public char[] myText = new char[100];
Assigning an array’s field:
Remember that the index always starts with 0! So the array’s first element has the index 0
array_name[field's_index_to_assign] = new_value;
Example:
myText[20] = 'f';
Reading an array’s field:
array_name[field's_index_to_read];
Example:
char singleChar = myText[20];
Exercise
Warning: Advanced exercise! Try to solve it, without looking it up in the next part of the series or anywhere else, I’ll explain the solution in the next part, but It’ll help you a lot to understand the topic, if you do this exercise on your own. However don’t be upset, if you can’t solve it. It’s intended to be a hard exercise!
Arrays can hold every type of object or primitive variable. So an array can also hold another array, which will create a so called multi-dimensional array. Try to do that!
Try to create an array that holds integer arrays! Instantiate both with a length of five fields and try to read to and write from the integer arrays!
Hint: Look at the syntax section and read the last two sentences, it should be easier to think of the right syntax for multi-dimensional arrays!
Table of contents
Part 1 – MyFirstProgram
Part 2 – Access Modifiers and Variables
Part 3 – Methods
Part 4 – Arrays (You are here)
Part 5 – Control flow
Part 6 – Classes and Objects
Part 7 – Exceptions and exception handling
Addendum 1 – IntelliJ QuickTip
Addendum 2 – Important programming concepts explained
11 thoughts on “Programming Basics 4 – Arrays”