Java Array: Logic Formulation and Intro. To Programming
Java Array: Logic Formulation and Intro. To Programming
TO PROGRAMMING
Java Array
Java array is an object which contains elements of a similar data type. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based; the first element of the array is stored at the 0 index.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5}; /declaration, instantiation and initialization
System.out.println(min);
}
Output: 3
Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
In Java, an array is an object. For array object, a proxy class is created whose name can be
obtained by getClass().getName() method on the object.
Output : caffeine
Output:
2 6 8
6 8 10
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.