You are on page 1of 11

ARRAYS

Arrays in Java

 Indexes start at 0.
 All data types (primitive and user-defined
objects) can be put into arrays.
 Any expression which evaluates to an
integer can be used as the array subscript.
Declaring Arrays

 Arrays must be both declared and


allocated (using the new command):
<datatype [] arrayname= new datatype[n]>
<datatype arrayname[]=new datatype[n]>
 int myarray[] == new int [100];

 int myarray[];
myarray = new int[100];
Example Declarations

 char chararray[] = new char [25]


 byte bytearray[] = new byte [25]
 MyObj ObjArray[];
ObjArray = new MyObj[10]
 byte [] array1, array2;
array1 = new byte[10];
array2 = new byte[20];
Initialization of Single
Dimensional Array
 Single dimensional arrays can be
initialized in following manner –
int arr[5] = {34, 56, 67, 12, 45};
Values will be stored as –
arr[0] = 34;
arr[1] = 56;
arr[2] = 67;
arr[3] = 12;
arr[4] = 45;
Double Dimensional Arrays
 Double dimensional arrays are created in following
manner –
data_type array_name[][];
array_name[][] = new data_type[row_size][col_size];
where data_type is the type of data to be stored,
array_name is a name assigned to an array,
row_size is a number of rows and
col_size is a number of columns in each row.
For example –
int arr[][]= new int[5][4];
int arr[][];
arr[][] = new int[5][4];
A 5*4 array representation

arr[0][0] arr[0][1] arr[0][2] arr[0][3]

arr[1][0] arr[1][1] arr[1][2] arr[1][3]

arr[2][0] arr[2][1] arr[2][2] arr[2][3]

arr[3][0] arr[3][1] arr[3][2] arr[3][3]

arr[4][0] arr[4][1] arr[4][2] arr[4][3]


Initialization of Double
Dimensional Arrays

Double dimensional arrays are


initialized in following ways –

int arr[3][3] = {
{11,12, 23},
{34, 45, 56},
{67, 78, 89}
};
 These values are stored row-wise in the
arr which is a double dimensional array.
Therefore the values after initialization
will be –
 arr[0][0] = 11
 arr[0][1] = 12
 arr[0][2] = 23
 arr[1][0] = 34
 arr[1][1] = 45
 arr[1][2] = 56
 arr[2][0] = 67
 arr[2][1] = 78
 arr[2][2] = 89
 Values can also be stored at desired
locations during initialization. For example
int arr[3][3] = {
{34},
{23, 45},
{89, 67, 54}
};
This will cause following effect in the arr –
 arr[0][0] = 34
 arr[0][1] = 0
 arr[0][2] = 0
 arr[1][0] = 23
 arr[1][1] = 45
 arr[1][2] = 0
 arr[2][0] = 89
 arr[2][1] = 67
 arr[2][2] = 54
Multi Dimensional Arrays

 int arr[][][];
 arr[][][] = new int[size1] [size2]
[size3];

This allocates a three dimensional array in


the memory which can store up to 3 * 3 * 3
integer values. The first element of this
array will be arr[0][0][0] and the last
element of this array will be arr[3][3][3];

You might also like