Arrays
Arrays
1
ARRAY
Array is a collection of similar type of elements
that have contiguous memory location.
In java, array is an object the contains elements
of similar data type.
It is a data structure where we store similar
elements. We can store only fixed elements in an
array.
Array is index based, first element of the array is
stored at 0 index.
2
Advantage of Array
Code Optimization: It makes the code optimized, we
can retrieve or sort the data easily.
Random access: We can get any data located at any
index position.
Disadvantage of Array
Size Limit: We can store only 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.
3
Types of Array: There are two types of array.
Single Dimensional Array
Multidimensional Array-
2D array
3D array
Jagged array
4
SINGLE DIMENSIONAL ARRAY
The syntax for declaring and instantiating an
array:
There are two ways to declare an array,
type[] arrayName;
type arrayName[];
5
How to instantiate an array
arrayName = new type[length];
How to declare and instantiate an array in one
statement
type[] arrayName = new type[length];
6
EXAMPLES
Array of integers
int[] num = new int[5];
Array of Strings
8
THE ARRAYS CLASS
Arrays.sort
e.g-
int[] numbers = {2,6,4,1,8,5,9,3,7,0};
Arrays.sort(numbers);
for (int num : numbers)
{
System.out.print(num + " ");
}
9
SOME OTHER METHODS:
equals( arrayName1, arrayName2 )
copyOf( arrayName, length )
10
TWO-DIMENSIONAL ARRAYS
int[][] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
11
JAGGED ARRAY
type[][] arrayName = new type[rowCount][];
e.g:-int num[][]=new int[4][];
num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];
12
ENHANCED FOR LOOP FOR 2D ARRAY
for (int[] num: arr)
{
for(int data: num)
{
System.out.println(data);
}
}
13
ANONYMOUS ARRAY:
An array without any name is called
anonymous array.
Anonymous array is passed as an argument of
method
Syntax: new arrayType[]{ array elements};
// anonymous int array
new int[] { 1, 2, 3, 4};
// anonymous char array
new char[] {'x', 'y', 'z‘};
// anonymous String array
new String[] {“hello", “hi", “bye"};
// anonymous multidimensional array 14
15
16
4 D ARRAY
Array of 3 D Array
int [][][][] num=new int[2][2][2][2];
17