3. Arrays in Java - ZolotovaNatalia/JavaCourse_2017 GitHub Wiki
What is an Array?
So far, you have been working with variables that keep only one value. The integer variables you have set up have held only one number, and the string variables just one long string of text. An array is a way to hold more than one value at a time. It's like a list of items. Think of an array as the columns in a table. You can have a table with only one column, or lots of them. The data held in a single-list array might look like this:
Array Values | |
---|---|
0 | 12 |
1 | 100 |
2 | 5 |
3 | 238 |
4 | 45 |
5 | 89 |
Arrays have a position number for each row. The positions in an array start at 0 and go up sequentially. Each position in the array can then hold a value. In the table above array position 0 is holding a value of 12, array position 1 is holding a value of 100, position 2 has a value of 2, and so on.
To set up an array like that in the table above, you have to tell Java what kind of data is going in to your array (integers, strings, boolean values, etc). Then you give a name to your array and using a keyword new
set up a new array object. In between the square brackets you need to determine the size of the array, also called length of the array, that shows Java how many elements should be there:
int[ ] myArray = new int[6];
So we are telling Java to set up an array with 6 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 6 positions will be zero ( 0 ).
To assign values to the various positions in an array, you do it in the normal way:
myArray[0] = 12;
Here, a value of 12 is being assigned to position 0 in the array called myArray. Again, the square brackets are used to refer to each position. If you want to assign a value of 100 to array position 1, the code would be this:
myArray[1] = 100;
And to assign a value of 5 to array position 2, it's this:
myArray[2] = 5;
Don't forget, because arrays start at 0, the third position in an array has the index number 2.
If you know what values are going to be in the array, you can set them up like this instead:
int[ ] myArray= { 12, 100, 5, 238};
This method of setting up an array uses curly brackets after the equals sign. In between the curly brackets, you type out the values that the array will hold. But this is just for data types of int values, string, and char values. Otherwise, you need the new keyword. So, having a string array you can do this:
String[ ] stringArray = {"One", "Two", "Three", "Four" };
Or for boolean:
boolean[ ] booleanArray = {false, true, false, true};
To get at the values held in your array, you type the name of the array followed by an array position(index of element) in square brackets. Like this:
System.out.println( myArray[2] );
The above code will print out whatever value is held at array position 2 in the array called myArray.
To see print how many elements in the array you can use property length
, that every array in Java has:
System.out.println(myArray.length);
Let's make some practice!
Create a new project in Eclipse and create class in it with any name you like, for example, MyFirstArray. Add a main method in this class and create an array myFirstArray with elements of any type you like: integer, double, String, char or boolean. Fill the array with elements and print them in console one by one or all together.
For example:
public class MyFirstArray {
public static void main(String[] args) {
double[] myFirstArray = new double[5];
myFirstArray[0] = 0.56;
myFirstArray[1] = 1.35;
myFirstArray[2] = 2.09;
myFirstArray[3] = 3.123;
myFirstArray[4] = 4.45;
System.out.println(myFirstArray);
System.out.println(myFirstArray[0]);
System.out.println(myFirstArray[3]);
System.out.println(myFirstArray[4]);
System.out.println(myFirstArray.length);
}
}
Also print out the element with index out of range of the array and see what happens. Think about why. For example:
System.out.println(myFirstArray[5]);
Create another array of another type and don't fill the last element. Print it out and see what value has the last element depending on the type. For example, the array is of 5 String elements, filled only 4 of them and we print out the 5'th element (index 4):
System.out.println(stringArray [4]);
Loop an Array
Assume you have a very huge array of 1000 or more elements and you need to perform some operations with each element one by one. Access them separately, using the approach described above, can take much time and thousands lines of code. That's not effective. Instead of typing them one by one you can use loops. There are several kinds of loops: for(...)
, while(..)
, forEach(...)
, do() - while()
. We will talk about for(...)
and while(..)
loops.
For()
loop
According to the Oracle official documentation, the for statement provides a compact way to iterate over a range of values. The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s)
}
Where:
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the termination expression evaluates to false, the loop terminates.
- The increment expression is invoked after each iteration through the loop.
That's an example how we can loop the array of 5 elements:
public class MyFirstArray {
public static void main(String[] args) {
double[] myFirstArray = new double[5];
myFirstArray[0] = 0.56;
myFirstArray[1] = 1.35;
myFirstArray[2] = 2.09;
myFirstArray[3] = 3.123;
myFirstArray[4] = 4.45;
for(int i = 0; i < myFirstArray.length; i++){
System.out.println(myFirstArray[i]);
}
}
}
In this example initialization expression is int i = 0
. We declare a variable i and set a start value 0. This initialization happens only once at the first iteration. If you want to use i outside of the loop, you can define it before.
Then we define the termination expression : i < myFirstArray.length
. This means, that the loop shouldn't be terminated until i value is less then the length of the array. This expression is executed at every entry the loop.
In the increment expression (it can also be decrement expression) i++
we define how i variable changes at each iteration. In our case we increment it on 1. This happens only if the termination expression returns true.
As an exercise, print out also value of i
variable at each iteration.
While() loop
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following program:
class WhileLoop{
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
Do-while loop
There is another type of loops in Java called do-while loop, which can be expressed as:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following program:
class DoWhileLoop{
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
See more in the Oracle official documentation.
Exercises
- Create an array of int type and fill it with values:
int[] intArray1 = new int[5];
intArray1[0] = 1;
intArray1[1] = 2;
intArray1[2] = 3;
intArray1[3] = 4;
intArray1[4] = 5;
Another array initialization:
int[] intArray2 = {1, 2, 3};
- Create an array of String type and fill it with values:
String[] stringArray1 = new String[3];
stringArray1 [0] = "ab";
stringArray1 [1] = "abc";
stringArray1 [2] = "abcd";
Another array initialization:
String[] stringArray2 = {"ab", "abc", "abcd"};
- Pring out intArray1 and its elements:
System.out.println(intArray1);
System.out.println("array length = " + intArray1.length);
System.out.println("intArray[0] = " + intArray1[0]);
System.out.println("intArray[1] = " + intArray1[1]);
System.out.println("intArray[2] = " + intArray1[2]);
System.out.println("intArray[3] = " + intArray1[3]);
System.out.println("intArray[4] = " + intArray1[4]);
- Print out the whole array:
System.out.println("Original Array : "+ Arrays.toString(intArray));
- Print out amount of elements in the array (length):
System.out.println(intArray.length);
- Using loop for() print out elements of the array in the direct order:
for(int i = 0; i < intArray1.length; i++){
System.out.println("intArray[" + i + "] = " + intArray1[i]);
}
- Using loop for() print out elements of the array in the reverse order:
for(int i = intArray1.length - 1; i >= 0; i--){
System.out.println("intArray[" + i + "] = " + intArray1[i]);
}
- Using loop while() print out elements of the array in the direct order:
int k = 0;
while(k < intArray1.length){
System.out.println("intArray[" + k + "] = " + intArray1[k]);
k++;
}
- Using loop while() print out elements of the array in the reverse order:
int l = intArray1.length - 1;
while(l >= 0){
System.out.println("intArray[" + l + "] = " + intArray1[l]);
l--;
}
- Calculate the sum of elements:
int sum = 0;
for(int i = 0; i < intArray1.length; i++){
sum += intArray1[i];
}
System.out.println("Sum = " + sum);
- Loop that never ends - infinitive loop:
int i = 0;
while (i < 10){
System.out.println(i);
}
To exit this loop we need to increase i on each iteration:
int i = 0;
while (i < 10){
System.out.println(i);
i++;
}
Or you can also use the key word break and exit the loop after the first iteration:
int i = 0;
while (i < 10){
System.out.println(i);
break;
}
-
Iterate any array with values of type int over for() and while() loops, so that every element is increased on 1.
-
Create an array1 with values of type int and fill it. Create another array2 of the same type and size as array1. Iterate over array1 with for() and while() loops and fill the array2 with elements from array1 in reverse order. For example, if array1 looks like {1, 2, 3}, array2 should be {3, 2, 1}.
-
Write a program to calculate the average value of elements from any array with numbers.
-
Write a program to remove a specific element from an array (use index of this element).