Java arrays

What is an Array?

An array is a collection of a fixed number of the same types of elements.  Each element has a position in the array, which indicated by an integer value called index. The index which starts with 0 is used to determine the position of the items. The size of an array is also called length, which is the number of elements that can fit in it. It is important to know that an array is not a primitive data type, but an object.

The following is defining an array of an integer type data and its length is 5, which means that it has enough room for 5 integers.

int [] intArray = new int [5] 

The following code changes the value of the third element in the array to 27. Remember that the first element index is 0.
intArray [2] = 27

arrays-color

Example 1:

In the following example we define an array of an integer without adding any values to it. By executing the following code, five zeros (0) like “-0-0-0-0-0” is written to the standard output. That is because the length of the array is 5.

public class MyArray {

	public static void main(String[] args){
		int[] arrayInt = new int[5];
		for(int i = 0; i < arrayInt.length; i ++ ) {

			System.out.print("-" + arrayInt[i]);
		}
	}
}

Multidimensional Arrays

Multidimensional or array of arrays can be used for example to represent rooms which belongs to a specific floor in a building. A building for example has three floors and each floor contains 5 rooms as shown in the table below.

In this example we store each room number by the floor to which it belongs.

 index  (0)   (1)  (2)   (3)
 (0)  floor 1 room 1 room 2 room 3 room 4
 (0) floor 2  room 5 room 6 room 7 room 8
 (0) floor 3  room 9 room 10 room 11 room 12

The following array of arrays example represent the floors and the rooms of the above table as below:

Example 2

If you try to compile and execute the following main method, the code writes”-5-6-7-8″ to the standard output, which are the room numbers of the second floor of the building. In the following example the “3” represents the total number of the floors (the rows) and the  the “4” represents the  total number of the rooms (the columns).

The indexes of the arrays start with (0).

int array [][] = new int[3][4];

public class MyArray {

	public static void main(String[] args){
		int array[][] = new int[3][4];
		array[0][0] = 1;
		array[0][1] = 2;
		array[0][2] = 3;
		array[0][3] = 4;

		array[1][0] = 5;
		array[1][1] = 6;
		array[1][2] = 7;
		array[1][3] = 8;

		array[2][0] = 9;
		array[2][1] = 10;
		array[2][2] = 11;
		array[2][3] = 12;

		for(int row = 0; row < array.length; row ++ ) {
			for(int col = 0; col < array[row].length; col ++ ) {
				if(row == 1) {
					System.out.print("-" + array[row][col]);
				}
			}
		}
	}
}

 

Sorting elements of arrays

You can sort the elements of an array by using the sort method of the Java standard API: Arrays.sort(). If you want to use the standard methods of the Arrays class, you need to import the package of that class which is java.util;

Example 3:

If the following code is compiled and run, it writes the following to the standard output
, 12, 30, 6, 25, 33 // not sorted
, 6, 12, 25, 30, 33 // sorted

import java.util.Arrays;

public class MyArray {

	public static void main(String[] args){
		int[] arrayInt = new int[5];
		arrayInt[0] = 12;
		arrayInt[1] = 30;
		arrayInt[2] = 6;
		arrayInt[3] = 25;
		arrayInt[4] = 33;
		for(int i = 0; i < arrayInt.length; i ++ ) {
			System.out.print(", " + arrayInt[i]);
		}
		Arrays.sort(arrayInt); // This line sorts our array.
		System.out.println();
		for(int i = 0; i < arrayInt.length; i ++ ) {
			System.out.print(", " + arrayInt[i]);
		}
	}
}

Exercise 1

What happens when the following program is compiled and run?

public class MyArray {

	public static void main(String[] args){
		char[] arrayChar = new char[4];
		arrayChar[0] = 'C';
		arrayChar[3] = 'K';
		arrayChar[2] = 'Z';
		arrayChar[1] = 'W';
		for(int i = 0; i < arrayChar.length; i ++ ) {
			System.out.print("-" + arrayChar[i]);
		}
	}
}

Select the correct answer.


Exercise 2

What happens when the following program is compiled and run?

public class MyArray {

	public static void main(String[] args){
		int[] arrayInt = new int[4];
		arrayInt[0] = 8;
		arrayInt[1] = 3;
		arrayInt[2] = 6;
		arrayInt[3] = 5;
		for(int i = 0; i < arrayInt.length; i ++ ) {
			if(i == 2) {
				System.out.print("-" + arrayInt[1]);
			}
			else {
				System.out.print("-" + arrayInt[i]);
			}
		}
	}
}

Select the correct answer.


Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.


Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

4 Comments

Add a Comment
  1. This site is very clean and user friendly style and design, as well as the articles. You are an expert in Java!

  2. Good article thanks!

    1. You are welcome!

  3. Thanks for this explanation! The examples and the exercises make it easier to understand!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017