12) Arrays

Array in Java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation its length is fixed.

It stores the value on the basis of the index value.

Advantage of Array

One variable can store multiple values: The main advantage of the array is we can represent multiple values under the same name.

Code Optimization: No, need to declare a lot of variable of same type data, we can retrieve and sort data easily.

Random access: We can retrieve any data from array with the help of the index value.

Disadvantage of Array

The main limitation of the array is Size Limit when once we declare array there is no chance to increase and decrease the size of an array according to our requirement, Hence memory point of view array concept is not recommended to use. To overcome this limitation, Java introduces the collection concept.

Types of Array

There are two types of array in Java.

  • Single Dimensional Array

  • Multidimensional Array

Array Declaration

String studentName[];

Or

String []studentName;

Or

String[] studentName;

Note: At the time of array declaration we cannot specify the size of the array. For Example int[5]

This is wrong.

Array creation

Every array in a Java is an object, hence we can create array by using new keyword.

int[] arr = new int[10]; // The size of array is 10.

or

int[] arr = {10,20,30,40,50};

Accessing array elements

Access the elements of array by using index value of an element.

arrayname[n-1];

Java array initialization and instantiation together

int marks[] = {98, 95, 91, 93, 97};

Iterating a Java Array

package com.gs.ilp.corejava.Arrays;

public class IterateJavaArray {
	public static void main(String args[]) {
		String studentsName[] = { "Monty", "John", "Smith", "Clark", "Susen" };
		// java array iteration using enhanced for loop
		for (String studentName : studentsName) {
			System.out.println(studentName);
		}
	}
}

Multidimensional Arrays

When a component type itself is an array type, then it is a multidimensional array. Though you can have multiple dimensions nested to ‘n’ level, the final dimension should be a basic type of primitive or an Object.

int[][] i = new int[5][10];

int[] []j = new int[5][10];

int[] marks, fruits, matrix[];

marks = new int[5];

fruits = new int[15];

matrix = new int[4][2];

in above examples i,j and matrix are multidimensional arrays.

Iterate a java multidimensional array

package com.gs.ilp.corejava.Arrays;

public class IterateMultiDimensionalJavaArray {
	public static void main(String args[]) {
		int sudoku[][] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };
		for (int row = 0; row < sudoku.length; row++) {
			for (int col = 0; col < sudoku[row].length; col++) {
				int value = sudoku[row][col];
				System.out.print(value);
			}
			System.out.println();
		}
	}
}

Output:

Sort a Java array

java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array.

package com.gs.ilp.corejava.Arrays;

import java.util.Arrays;

public class ArraySort {
	public static void main(String args[]) {
		int marks[] = { 94, 98, 92, 93, 97 };
		System.out.println("Before sorting: " + Arrays.toString(marks));
		Arrays.sort(marks);
		System.out.println("After sorting: " + Arrays.toString(marks));
	}
}

Output:

Difference Between Length and Length() in Java

length: It is a final variable and only applicable for array. It represents size of array.

Example

int[] a=new int[10];
System.out.println(a.length);  // 10
System.out.println(a.length());  // Compile time error

length(): It is the final method applicable only for String objects. It represents the number of characters present in the String.

Example

String s="Java";
System.out.println(s.length());  // 4
System.out.println(s.length);  // Compile time error

Last updated