Arrays
In this tutorial, we are going to discuss about overview of arrays in Java. An array is an indexed collection of fixed number of homogeneous data elements. The main advantage of array is we can represent multiple values under the same name. So that readability of the code will be improved. But the main disadvantage of array is fixed in size. i.e., once we created the array with some size then there is no chance of increasing or decreasing the size based on our requirement.
Hence to use arrays compulsory we should know the size in advance which may not possible always. Hence memory point of view arrays not recommended to use. Using collections we can resolve this problem.
Array Declarations
1. Single Dimensional Array
int[] a;
int []a;
int a[];
Here first one is recommended to use because name is clearly separated from the type.
Note
At the time of array declaration we can’t specify the size. Otherwise we will get compilation error.
E.g: int[6] a; // C.E
2. Two Dimensional Array
int[][] x;
int [][]x;
int x[][];
int[] []x;
int[] x[];
int []x[];
3. Three Dimensional Array
int[][][] x;
int [][][]x;
int x[][][];
int[] x[][];
int[] []x[];
int[] [][]x;
int[][] x[];
int[][] []x;
int [][]x[];
int []x[][];
Which of the following declarations are valid.?
int[] a,b; a=1, b=1;
int[] a[],b; a=2, b=1;
int[] []a,b; a=2, b=2;
int[] []a,b[]; a=2,b=3;
int[] []a,[]b; //Compilation Error
Note
If we want to specify the dimension of before the variable it is possible only for the first variable.
i.e.,
int[] []a,[]b,[]c; // Here dimensions b and c are not possible.
Array Creation
Every array in java is an object. Hence we can create by using new operator.
E.g:
int[] x = new int[5];
For every array type corresponding classes are available but these classes are part of Java language and not available to the programmer level. Following are the JVM array descriptors.
[Z = boolean
[B = byte
[S = short
[I = int
[J = long
[F = float
[D = double
[C = char
[L = any non-primitives(Object)
Note
1. At the time of array creation compulsory we have to specify the size. Otherwise we will get compilation error.
E.g:
int[] x = new int[]; //C.E
int[] x = new int[5]; //Fine
2. In Java it is legal to have an array with size zero(0);
int[] x = new int[0];
3. If we are trying to specify array size with negative int value then we will get Runtime exception saying NegativeArraySizeException.
int[] x = new int[-5]; // Compile fine but we will get R.E : NegativeArraySizeException
4. To specify array size the allowed data types in Java are byte, short, char, int. If we are using anyt other type then we will get compile time error.
int[] x = new int[10];
int[] x = new int['a'];
byte b = 10;
int[] x = new int[b];
short s = 10;
int[] x = new int[s];
int[] x = new int[10l]; // C.E: Possible loss of precision found: long required: int
5. The maximum allowed array size in Java is 2147483647. which is maximum value of the int datatype.
int[] x = new int[2147483647]; //Fine
int[] x = new int[2147483648]; // C.E : integer too large
Even in the first case we may get OutOfMemoryError if sufficient heap memory not available.
Multidimensional Array Creation
In Java Multidimensional arrays are not implemented by using matrix representation. SUN people followed array of arrays approach to design Multidimensional arrays. The main advantage of this approach is memory utilization will be improved.
E.g:
int[][] a = new int[3][];
a[0] = new int[3];
a[1] = new int[1];
a[2] = new int[2];
Array Initialization
Once we creates an array every array element is by default initialized with default values.
E.g:Â
int[] x = new int[3];
System.out.println(x); // [I@3e2598
System.out.println(x[0]); // 0
Note
Whenever we are trying to print any object reference internally toString() method will be called which is by default implemented to return string in the following form
classname@hexadecimal_string_of_hashcode
E.g:
int[][] x = new int[3][2];
System.out.println(x); // [I@3e29a8
System.out.println(x[0]); [I@5f2641
System.out.println(x[0][0]); // 0
int[][] x = new int[3][];
System.out.println(x); // [I@3e29a8
System.out.println(x[0]); null
System.out.println(x[0][0]); // R.E: NullPointerException
Note
If we are performing any operation on null then we will get NullPointerException
Once we creates an array every array element by default values. If we are not satisfied with default values then we can override default values with customized values.
E.g
int[] x = new int[5];
x[0] = 10;
x[1] = 20;
x[2] = 30;
x[3] = 40;
x[4] = 50;
x[5] = 60; // R.E: ArrayIndexOutOfBoundException
x[-5] = 70; // R.E: ArrayIndexOutOfBoundException
x[2.5] = 80; // C.E: Possible loss of precision found: double required : int
We can declare, create and initialize an array in a single line
E.g
int[] x = { 10,20,30,40};
char[] ch = {'a', 'e', 'i','o','u'};
String[] str = {"Ashok", "Vinod","Dillesh"};
If we want to use this short cut compulsory we should perform all activities in a single line. If we are trying to divide into multiple lines then we will get compilation error.
E.g
int[] x = {10,20,30}; // Fine
int[] x;
x={10,20,30}; //C.E: Illegal Start of expression
length vs length()
length
- length is a final variable applicable for arrays
- length variable represents the size of the array
E.g:Â
int[] x = new int[3];
System.out.println(x.length); // 3
System.out.println(x.length()); // C.E: Cannot find symbol Symbol: method length() location: int[]
length()
- length is a final method applicable for string objects
- length() method represents number of characters present in the string
E.g
String str = "Ashok";
System.out.println(str.length()); // 5
System.out.println(x.length); //C.E: Cannot find symbol Symbol: variable length location: java.lang.String
Note
length variable applicable for arrays but not for string objects where as length() method applicable for string objects but not for arrays.
In multidimensional arrays length variable represents only base size but not total size.
E.g
int[][] x = new int[6][3];
System.out.println(x.length); // 6
Anonymous Arrays
- Some times we can declare an array without name such type of nameless arrays are called anonymous arrays.
- The main purpose of anonymous arrays is just for instant use or one time usage.
- We can create anonymous array is as follows
new int[] {10,20,30,40,50};
- We can create multidimensional anonymous arrays also
new int[] {{10,20},{30,40,50}};
- While creating anonymous arrays we can’t specify size otherwise we will get compile time error.
E.g:Â
new int[3] {10,20,30}; //C.E
new int[] {10,20,30}; //Fine
package com.ashok.test;
class Test {
public static void main(String args[]) {
sum(new int[] {10,20,30});
}
public static void sum(int[] x) {
int total = 0;
for(int x1 : x) {
total = total + x1;
}
System.out.println("Sum is " + total);
}
}
Array Element Assignments
Case 1: In the case of primitive type arrays as array elements we can provide any type which can be implicitly promoted to declared type.
E.g:
- For int type arrays allowed element types are byte, short, char, int
- For float type arrays allowed elements types are byte, short, char, int, long, float
E.g:Â
int[] x = new int[10];
x[0] = 10;
x[1] = 'a';
byte b = 30;
x[2] = b;
x[3] = 10L; // C.E: Possible loss of precision found : long required: int
Case 2: In the case of object type arrays as array elements we can provide either declared type objects or it’s child class objects.
E.g
Object[] a = new Object[10];
a[0] = new Object();
a[1] = new String("Ashok");
a[2] = new Integer(10);
Number[] n = new Number[10];
n[0] = new Integer[10];
n[1] = new Double[10.5];
n[2] = new String("Ashok"); // C.E: Incompatible types found: java.lang.String required: java.lang.Integer
Case 3: In the case of interface type arrays as array elements. We can provide it’s implemented class objects.
E.g
Runnable[] r = new Runnable[10];
r[0] = new Thread[];
r[1] = new String("Ashok"); // C.E: Incompatible types found: java.lang.String required: java.lang.Runnable
Array Variable Assignments
Case 1: When ever we are assigning one array to another array internal elements won’t be copied just reference variables will be reassigned. Hence sizes are not required to match but types must be matched.
E.g
int[] x = {10,20,30,40,50};
int[] y = {60,70};
x = y; //Fine
y = x; //Fine
Case 2: Array element level promotions are not applicable at array object level. For example char element can be promoted to int type but char[] arrays cannot be promoted to int[] array.
E.g
int[] a = {10,20,30,40,50};
char[] ch = {'a','b','c'};
int[] b = a; //Fine
int[] c = ch; //C.E: Incompatible types found found: char[] required: int[]
Case 3: When ever we are assigning one array to another array dimensions must be matched. For example in the place of one dimensional array we should provide one dimensional array only, if we are trying to provide any other dimensions then we will get compilation error.
E.g
int[][] a = new int[3][];
a[0] = new int[3][2]; //C.E: Incompatible types found:int[][] required: int[]
a[0] = 10; //C.E: Incompatible types found:int required: int[][]
a[0] = new int[2]; // Fine
That’s all about Arrays in Java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!