OOP CS3391 UNIT-1[Lecture Note-12]
OOP CS3391 UNIT-1[Lecture Note-12]
Definition:
An array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type.
The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements.
Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
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.
Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
1. One-Dimensional Array:
One-dimensional array is an array in which the elements are stored in one variable name by
using only one subscript.
Creating an array:
Three steps to create an array:
1. Declaration of the array
2. Instantiation of the array
3. Initialization of arrays
3. Initialization of arrays:
Storing the values in the array element is called as Initialization of arrays.
Syntax:
Example 1:
int regno[] = {101,102,103,104,105,106};
int reg[] = regno;
ARRAY LENGTH:
The keyword length can identify the length of array in Java. To find the number of
elements of an array, use array_name.length
Example1:
int regno[10];
len=regno.length;
System.out.println(len);
Example 2:
for(int i=0; i<reno.length; i++)
{
System.out.println(regno[i]);
}
class Array1
{
public static void main(String[] args)
{
String month_days[];
month_days=new String[12];
month_days[0]="Jan";
month_days[1]="Feb";
month_days[2]="Mar";
month_days[3]="Apr";
month_days[4]="May";
month_days[5]="Jun";
month_days[6]="July";
month_days[7]="Aug";
month_days[8]="Sept";
month_days[9]="Oct";
month_days[10]="Nuv";
month_days[11]="Dec";
System.out.println("the fifth month is "+month_days[4]);
Output:
}
} the fifth month is May
Example 2: Finding sum of the array elements and maximum from the array:
Multidimensional arrays are arrays of arrays. It is an array which uses more than one
index to access array elements. In multidimensional arrays, data is stored in row and
column based index (also known as matrix form).
Uses of Multidimensional Arrays:
Used for table
Used for more complex arrangements
Example:
int[][] arr;
int arr[][];
int [][]arr;
Example to instantiate Multidimensional Array in java:
int[][] arr=new int[3][3];
Example-2
class TwoDarray2
{
public static void main(String args[])
{
int array2[][] = {{1,2,3},{2,4,5},{4,4,5}}; // declaring and initializing 2D array
int i, j, k = 0;
System.out.println("-----Array 2----- ");
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++) Output:
{
System.out.print(array2[i][j] + " "); -----Array 2-----
} 1 2 3
System.out.println(); 2 4 5
} 4 4 5
}
}