Java Array

Java Array

Array is used to store same ‘type’ of data that can be logically grouped together. 

Array is a fundamental construct in any programming languages. 

This Java tutorial is planned to provide comprehensive information about Java arrays.

Array is one among the many beautiful things in a programming language. 

Easy to iterate, easy to store and retrieve using their index. 

In Java, a beginner starts with public static void main(String args[])

The argument for the main method is an array. We encounter arrays early on.

Java Arrays

In java arrays are objects. All methods of an Object can be invoked on an array. 

Arrays are stored in heap memory.

Logical view of an Array

java array logical view

Though we view the array as cells of values, internally they are cells of variables. 

A java array is a group of variables referenced by a common name. 

Those variables are just references to a address and will not have a name. 

These are called the ‘components’ of a java array. 

All the components must be of same type and that is called as ‘component type’ of that java array.

Physical view of an Array

java array - physical view

Array Declaration

int []marks;

or

int marks[];

Array Instantiation

marks = new int[5];

5 inside the square bracket says that you are going to store five values and is the size of the array ‘n’. When you refer the array values, 

the index starts from 0 ‘zero’ to ‘n-1’. An array index is always a whole number and it can be a int, short, byte, or char.

Once an array is instantiated, it size cannot be changed. Its size can be accessed by using the length field like .length Its a java final instance field.

All java arrays implements Cloneable and Serializable.

Java array initialization and instantiation together

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

ArrayIndexOutOfBoundsException

One popular exception for java beginners is ArrayIndexOutOfBoundsException. 

You get ArrayIndexOutOfBoundsException when you access an array with an illegal index, 

that is with a negative number or with a number greater than or equal to its size. 

This stands second next to NullPointerException in java for popularity.

Java Array Default Values

After you instantiate an array, default values are automatically assigned to it in the following manner.

  • byte – default value is zero
  • short – default value is zero
  • int – default value is zero
  • long – default value is zero, 0L.
  • float – default value is zero, 0.0f.
  • double – default value is zero, 0.0d.
  • char – default value is null, ‘\u0000’.
  • boolean – default value is false.
  • reference types – default value is null.

Notice in the above list, the primitives and reference types are treated differently. 

One popular cause of NullPointerException is accessing a null from a java array.

Iterating a Java Array

public class IterateJavaArray {
	public static void main(String args[]) {
		int marks[] = {98, 95, 91, 93, 97};
		//java array iteration using enhanced for loop
		for (int value : marks){
			System.out.println(value);
		}
	}
}

In language C, array of characters is a String but this is not the case in java arrays. 

But the same behaviour is implemented as a StringBuffer where in the contents are mutable.

ArrayStoreException – When you try to store a non-compatible value in a java array you get a ArrayStoreException.

Multidimensional Arrays

When a component type itself is a array type, then it is a multidimensional array. 

Though you can have multiple dimension nested to n level, the final dimension should be a basic type of primitive or an Object.

int[] marks, fruits, matrix[];

In the above code, matrix is a multidimensional array. You have to be careful in this type of java array declaration.

Internally multidimensional java arrays are treated as arrays of arrays. 

Rows and columns in multidimensional java array are completely logical and depends on the way you interpret it.

Note: A clone of a java multidimensional array will result in a shallow copy.

Iterate a java multidimensional array

Following example source code illustrates on how to assign values and iterate a multidimensional java array.

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();
		}
	}
}

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.

import java.util.Arrays;

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

Copy a Java array

You can use the following options to copy a java array:

  • As illustrated above you can use the util calls Arrays. It contains copyOf method for different java types.
  • The most used class by a java beginner 'System' has a static method to copy an array.
  • Using its clone method you can copy a java array. If the java array is multidimensional, it will be a shallow copy.
  • Write your own for loop iterating through the java array and copy elements yourself. (least preferred)

This Core Java tutorial was added on 31/01/2011.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值