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
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
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.
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
length(): It is the final method applicable only for String objects. It represents the number of characters present in the String.
Example
Last updated