Java 8 Array
Java 8 Array
String[] cars;
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
Disadvantages
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.
Multidimensional Array
Output:
33
3
4
5
System.out.println(min);
}
Output:
10
22
44
6-6
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.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular
form, like a table with rows and columns.
To create a two-dimensional array, add each array within its own set of curly
braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
Access Elements
To access the elements of the myNumbers array, specify two indexes: one
for the array, and one for the element inside that array. This example
accesses the third element (2) in the second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7
Remember that: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
Example
public class Main {
System.out.println(myNumbers[i][j]);
}
}
Output:
1
2
3
4
5
6
7
}}
Output:
2 6 8
6 8 10