Professional Documents
Culture Documents
What Is Array: - An Array Is A Container Object That Holds When The Array Is Created. After Creation, Its Length Is Fixed
What Is Array: - An Array Is A Container Object That Holds When The Array Is Created. After Creation, Its Length Is Fixed
type arrayname[ ];
or
type[ ] arrayname ;
Eg:
int number[ ]; or int [ ] number ;
float arr[ ]; or float [ ]arr ;
Creation of array:
arrayname[subscript] = value ;
Eg:
number[0] = 5;
number[1] = 4;
number[2] = 1;
number[3] = 12;
number[4] = 8;
Cont.
• We can also initialize arrays automatically in the same way
as the ordinary variables when they are declared, as shown
below:
type arrayname[ ] = { val1, val2, ……, valn } ;
int x[ ][ ] = new int[3][ ]; // An array with 3 rows and variable size columns
x[0] = new int[3]; // Allocate space for 3 int elements in the first row
x[1] = new int[1]; // Allocate space for 3 int elements in the first row
x[2] = new int[2]; // Allocate space for 3 int elements in the first row
Cont.
for(int i = 0; i < x.length; i++) // x.length is the number of rows
{
for(int j = 0; j < x[i].length; j++) // x[i].length is the number of elements in
// row number i
{
catch(NumberFormatException e)
{ }
}
}
Cont.
System.out.print("\n The variable sized array is: \n");
}
System.out.println();
}
} // End of the main function
} // End of the class definition
Output:
Arrays of Objects
• An array of objects is created like an array of
primitive type data items in the following way.
Student[] arr = new Student[7];
//student is a user-defined class
The studentArray contains seven memory spaces each
of the size of student class in which the address of
seven Student objects can be stored. The Student
objects have to be instantiated using the constructor of
the Student class, and their references should be
assigned to the array elements in the following way .
Student[] arr = new Student[5];
Example
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
public class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;
// allocating memory for 5 objects of type
Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1,"aman");
// initialize the second elements of the array
arr[1] = new Student(2,"vaibhav");
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");
arr[4] = new Student(5,"mohit");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}