OOP CS3391 UNIT-1 (Lecture Note-11)
OOP CS3391 UNIT-1 (Lecture Note-11)
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