Java arrays

We are aware that a variable can hold only one value at a given time. When we want to store multiple values of same data types we can create that many number of variables. This approach is quite easy when we have less number of values but if we have many values say 100 then to define 100 variables is very difficult and not possible to remember all variable names and also this can lead to programming errors. To overcome this problem, most programming languages, including Java offer arrays.

What is an array?

Array is a collection of values of same data type. We can store multiple values in an array and refer them with a single name and a different index. For example, We can create an array to store names of our family members under a variable name family. So by using family variable we can able to access each and every family member.

The most important point to be remembered in an array is it can store multiple values of same data type.

There are multiple types of arrays based on dimension they are a one-dimensional array, two-dimensional arrays and multi-dimensional arrays.

One dimensional array

These are the basic form of arrays. Their syntax is,

datatype array_name[] = new dataype[size];

In the above syntax, data type denotes the type of values the array can store. The array_name denotes the name of the array. The new keyword is used to create new objects. We will learn more about new while we are discussing classes and objects. The last one size denotes the number of elements this array is going to hold. Below is the example for creating an array which holds 10 integer values.

int values[] = new int[10];

Just like variables, we can also initialize an array while declaring it. The below syntax shows initializing with an example.

type array-name[ ] = {val1, val2, val3, ... , valN };
int nums[] = { 99, -10, 100, 18, -97, 23, 43, -9, 87, 49 };

Accessing array elements

We have created an array of 10 integers and initialized it, but how to access each element in an array? This can be achieved by the index of the element. Every element of an array has its own index based on its position in the array. This index starts from 0 and ends at size-1. The first element will have index 0, second element’s index 1 and so on. Finally, last element index is: array size-1. The below program creates an array and prints all of its elements using the index.

/*
This is a simple Java program about Arrays.
Call this file KH_Arrays1D.java.
*/
public class KH_Arrays1D {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		//Number elements we initialized without size then number of elements decides size of array
		int nums[] = { 99, -10, 100, 18, -97, 23, 43, -9, 87, 49 };		
		for(int i = 0; i < 10; i++ )
			System.out.println("Element " + (i+1) + ": " + nums[i]);
		
	}
}

Download the code Run the code

Output:

Element 1: 99
Element 2: -10
Element 3: 100
Element 4: 18
Element 5: -97
Element 6: 23
Element 7: 43
Element 8: -9
Element 9: 87
Element 10: 49

Two dimensional arrays

This is the simplest form of multi-dimensional arrays. In simple terms, a two-dimensional array is an array of single dimensional arrays. Below is an example of the two-dimensional array. This creates a 2D array with 3 rows and 4 elements in each row. In other words an integer array with 3 rows and 4 columns.

A multidimensional array can be initialized for each row as given below. In the below example, it is clear that each row is itself an array.

int table[][] = new int[3][4];
int table[][] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}    
};

The below program creates a 3 X 4 table and prints them. You can observe that we have one index for each row and one index for each element in each row.

/*
This is a simple Java program about Arrays.
Call this file KH_Arrays2D.java.
*/
public class KH_Arrays2D {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		int table[][] = {
					{1, 2, 3, 4},
					{5, 6, 7, 8},
					{9, 10, 11, 12}    
				};		
		for (int i = 0; i < 3; i++ ) {
			for( int j = 0; j < 4; j++) {
			    System.out.print(table[i][j] + "\t");
			}
			System.out.println("");
		}		
	}
}

Download the code Run the code

Output:

1       2       3       4
5       6       7       8
9       10      11      12

Multidimensional Arrays

As you have already seen how 2D arrays can be created, initialized and accessed, in the same way, any dimensional array can be created. Below is a quick syntax for the n-dimensional array.

type name[ ][ ]...[ ] = new type[size1][size2]...[sizeN];
type array_name[ ] [ ] = {
{ val, val, val, ..., val },
{ val, val, val, ..., val },
.
.
.
{ val, val, val, ..., val }
};

Array length member

In the above programs, we have used the size of array constant number to terminate loops. It works in most of the cases. But by mistake if we write larger number than the size of the array then we will get a runtime error. To avoid these errors Java provides length member for each array object. This length member tells us how many elements are present in the array. If it is a one-dimensional array then it returns size of that array. Whereas if it multidimensional array it return the size of the upper layer, for example, for the 2-dimensional array it returns a number of rows in the 2D array. below program clearly demonstrates how to use length member to get the size and how to use in loops.

/*
This is a simple Java program about Arrays.
Call this file KH_ArraysLength.java.
*/
public class KH_ArraysLength {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		int elements[] = new int[10];
		int table[][] = {
					{1, 2, 3, 4},
					{5, 6, 7, 8},
					{9, 10, 11, 12}    
				};
		
		System.out.println("length of list is " + elements.length);
		System.out.println("length of table is " + table.length);
		System.out.println("length of table[0] is " + table[0].length);
		System.out.println("length of table[1] is " + table[1].length);
		System.out.println("length of table[2] is " + table[2].length);
		System.out.println();
		// use length to initialize list
		for(int i=0; i < elements.length; i++)
			elements[i] = i + 1;
		
		System.out.print("Here is list: ");
		
		for(int i=0; i < elements.length; i++)
			System.out.print(elements[i] + " ");
		System.out.println();		
	}
}

Download the code Run the code

Output:

length of list is 10
length of table is 3
length of table[0] is 4
length of table[1] is 4
length of table[2] is 4

Here is list: 1 2 3 4 5 6 7 8 9 10
<<< Java looping statementsJava Classes and Objects >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .