Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

What is Array

• 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
Important Point
• In Java, all arrays are dynamically allocated.
• Arrays are objects in Java, we can find their length
using the object property length. This is different from
C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other
variables with [] after the data type.
• The variables in the array are ordered, and each has
an index beginning from 0.
• Java array can be also be used as a static field, a local
variable, or a method parameter.
• The size of an array must be specified by int or short
value and not long.
Creating an array:
• Creation of an array involves three steps:

–1 Declare the array

– 2. Create memory locations

– 3. Put values into the memory locations


Declaration of array:
• The syntax for declaration of array in Java is:

type arrayname[ ];
or
type[ ] arrayname ;

Eg:
int number[ ]; or int [ ] number ;
float arr[ ]; or float [ ]arr ;
Creation of array:

• After declaring an array, we need to create


it in the memory.
• Java allows us to create arrays using new
operator, only.
arrayname = new type[size];
• Eg:
number = new int[5];
arr = new float[10];
Cont.
• It is also possible to combine the two
steps: declaration and creation into one
as:

int number[ ] = new int[5];


Initialization of Array:
• The final step is to put the values into the array. This can
be done using the array subscripts as shown below:

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 } ;

• The array initializer is a list of values separated by commas


and surrounded by curly braces.
• Note that no size is given. The compiler allocates enough
space for all the elements specified in the list.
Eg:
int number[ ] = {2, 5, 6, 2, 9};
Advantages of java array over C/C++

• Unlike, C/C++, Java protects arrays from overruns and


under runs. Trying to access an array beyond its
boundaries will generate an error message.
• It is possible to assign an array object to another. Eg:

int a[ ] ={3, 5, 6, 7, 1};


int b[ ];
b = a;
is valid in Java. Both arrays ‘a’ and ‘b’ will have the same
values.
Array length

• In Java, all arrays store the allocated size


in a variable named length. One can
access the length of the array ‘a’ using
a.length.
• Eg:
int size = a.length ;
Example: Program to sort an array of Strings
import java.io.*;
class SortArray
{
public static void main(String args[]) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(isr);

String name[] = new String[5];


for(int i= 0; i < 5; i++)
{
System.out.print("\n Enter the name: ");
name[i] = b.readLine();
}

System.out.print("\n The names are: \n");


for(int i= 0; i < 5; i++)
{
System.out.print("\n" + name[i]);
}
Cont.
for(int i = 0; i < 4; i++)
{
for(int j = i+1; j < 5; j++)
{
if( name[i].compareTo(name[j]) > 0 )
{
String temp = name[i] ;
name[i] = name[j];
name[j] = temp ;
}
}
}
System.out.print("\n The names in the ascending order are: \n");
System.out.print("\n The names are: \n");
for(int i= 0; i < 5; i++)
{
System.out.print("\n" + name[i]);
}
}
}
Output:
Two dimensional arrays:
• Declaration of array:
int a[ ][ ]; or int[ ][ ] a ;
a = new int[3][4];
or
int a[ ][ ] = new int[3][4];
or
int[ ][ ] a = new int[3][4];
Initialization of two dimensional arrays
• Like one-dimensional arrays, two-dimensional arrays can
also be initialized as follows:

int a[3][4] = {3,5,3,2,1,2,5, 6, 5,6,7,8} ;

• The above statement can also be written as:


• int a[ ][ ] = {
{3,5,3,2},
{1,2,5,6},
{5,6,7,8}
};
• All the elements of each row are surrounded by the
braces. Commas are required after each brace that
closes off a row, except in case of the last row.
Variable size array:

• Java treats multidimensional arrays as


arrays of arrays. It is possible to declare a
two dimensional array as follows:
int x[ ][ ] = new int [3][ ];
x[0] = new int [2];
x[1] = new int [3];
x[2] = new int [1];
Example:
import java.io.*;
class VariableArray
{
public static void main(String args[]) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

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
{

System.out.print("\n Enter the element at x[" + i + "][" + j + "] =


“ );
String s = br.readLine();
try
{
x[ i ] [ j ] = Integer.parseInt(s);
}

catch(NumberFormatException e)
{ }
}
}
Cont.
System.out.print("\n The variable sized array is: \n");

for(int i = 0; i < x.length; i++)


{
for(int j = 0; j < x[i].length; j++)
{

System.out.print(" " + x[i][j]);

}
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);
    }
}

You might also like