Translate

Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Monday, 25 August 2014

Double dimensional array in java

Double Dimensional Array in java is used to store data in tabular format. To access an individual element of DDA we require 2 indexes:- Row index and Element index.

Declaring DDA variable:-
int arr[ ][ ];
int [ ]arr[ ];
int [ ][ ]arr;


Defining DDA variable:-
arr = new int[4][3];  // here 4 is no of row and 3 is no of column
arr.length = no of row
arr[i].length = no of column


Initialising DDA:-
int arr[ ][ ] = {{90, 80, 70},{40, 50,60},{30, 20, 10}};


Assigning DDA:-
for(i=0; i<arr.length; i++)
    for(j=0; j<arr[i].length; j++)
        arr[i][j] = 100;

Thursday, 21 August 2014

Single dimensional array in java

An array is a group of variable of same data type. Each element in array is assigned a unique number to identify it uniquely. This is called subscript or index. The index starts with 0.

In java an array is created in 2 steps:-

Declaring array variable:-
int arr[ ];
int [ ]arr;
These statements declare an array variable that will refer to an array that we have yet to define. No memory is allocated at this point.


Defining the array:-
arr = new int[5];
This statement creates an array of size 5 of type integer and reference to array is assigned to variable arr.
int arr[ ];                          // same as  int *arr;  in c++
arr = new int[5];             // same as arr = new int[5]; 

In java when array is created all array elements are initialised to their default value automatically.
integer default value = 0
floating default value = 0.0
boolean default value = false
character default value = '\0'                      //null

In java each array has a length variable associated with it that returns number of elements in the array.
int arr[ ] = new int[5];
System.out.print(arr.length);
This will print the array size which is 5 here.


Array index:-
We can use any arithmetic expression on an array index. If we specify an invalid index it will throw an exception at run time.
Array Index Out Of Bound Exception
A long type expression is not allowed as an array index. It is compile time error.

Example:
int a[ ]= {25, 35, 45};                 //valid
int b[ ]= new int[]{25, 35, 45};    //valid
int c[ ]= new int[3]{25, 35, 45};  //not valid as when we defined array size as 3 it is already initialised with 0.
int d[ ]= {10,20,30};                    //valid
int e[ ]= d;                                    //valid as we know int e[ ] is same as int *e in c or c++ which is a pointer                                                                        so it can point to any other memory address already existing.

Total Pageviews