Array in Java with Real-Time Example

The simple meaning of an array is a collection of elements with same features that have contiguous memory. In Java, an array is defined as an object that contains elements that have the same data type. Arrays are dynamically allocated and are referred by a common name. Array in Java can be used as a static field and a local variable.

An array is a data structure where a fixed set of elements of similar types are stored. It is based on an index and has index beginning from 0 (zero). The length of an array can be found by using member length as they are objects. Both primitive data types and objects of a class can be included in an array on the basis of its definition.

An array is used in a program by first declaring a variable to reference the array and then the type of the array is specified. The array in Java performs different functions than the array in C/C++ does. For loop or for each loop is most used to process an array.

Advantages of Array in Java

  • Code optimization:

By defining an array, the programmer can easily retrieve and sort the data. Therefore, an array makes the code optimized.

  • Random access:

Any data can be located at any index position in an array.

Disadvantages of Java Array

  • Size limit:

In an array, only a fixed set of elements can be stored. The size of the array does not grow during runtime. But this problem can be solved by the use of the collection framework.

Type of Array in Java

There are two types of arrays in Java. They are:

  1. Single dimensional array
  2. Multidimensional array

Single dimensional array in Java

A single dimensional array is a collection of variables that have similar types. The variables in the array are denoted by a common name.  While cloning a single dimensional array, the new array will have the copies of the elements of the original array, not the references.

Syntax:

dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Example:

class ArrayClass { 
	public static void main(String args[]) {

		int a[] = new int[5]; // <-- declaration and instantiation
		a[0] = 100;
		a[1] = 200;
		a[2] = 300;
		a[3] = 400;
		a[4] = 500;

		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);

		}
	}
}

Multidimensional array in Java

A multidimensional array is defined as arrays of arrays. In a multidimensional array, each element of one array holds the reference of another array. It is created in Java by using one set of square brackets per every dimension. The multidimensional array is also called jagged arrays.

Data are stored in a matrix form in the multidimensional array, that is in row and column based index. While cloning a multidimensional array, the new array with the elements of the original array also has references.

Syntax:

dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example:

public class MultiArrayClass {

	public static void main(String args[]) {

		int array[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
}

Check also:  ArrayList in Java with Real Time Example

Passing Array to a method in Java

In Java, an array can be passed to a method like passing primitive type values to the method. This is done in order to reuse the same login on an array.

public class ArrayMethodClass {

	public static void main(String[] args) {

		int[] first = { 1, 2, 3, 4, 5 };

		arrayMethod(first);

		for (int i : first) {
			System.out.println(i);

		}
	}

	public static void arrayMethod(int second[]) {

		for (int i = 0; i < second.length; i++) {
			second[i] += 5;
		}
	}
}

What is the class name of the Java Array?

As mentioned earlier, an array is an object. A proxy class is created for each array and the name of such class is known by using the getClass().getName() method.

Copying a Java Array

System class is an array method that is used to copy one array to another.

public class CopyingArray {

	public static void main(String[] args) {

		int[] first = { 1, 2, 3, 4, 5, 6, 7, 8 };

		int[] second = new int[first.length];

		for (int i = 0; i < first.length; i++) {
			second[i] = first[i];
		}

		for (int i = 0; i < second.length; i++) {
			System.out.println(second[i]);
		}
	}
}

Check also: OOPs Concepts in Java – Four Main Concepts

Array in Java: Real-Time Example

In real time scenarios, we can make a card game using Array. Let’s see a simple example:

Total number of Spades: 13
Total number of Diamonds: 13
Total number of Clubs: 13
Total number of Hearts: 13
Set of playing cards: 52

public class CardGame {

		public static void main(String[] args) {

		String[] suits = { "S", "D", "C", "H" };
		String[] card = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J","Q", "K", "A" };
		String[] deck = new String[52];

		for (int i = 0; i < deck.length; i++) {
			deck[i] = card[i / 13] + suits[i / 13];
		}

		for (int i = 0; i < deck.length; i++) {
			int num = (int) (Math.random() * card.length);
			String st = deck[i];
			deck[i] = deck[num];
			deck[num] = st;
		}
		for (String str : deck) {
			System.out.println(str);
		}
	}
}

Leave a Reply

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