Arrays in Java
One Dimensional Array
An
array
is
an
object
that
can
be
used
to
store a list of values. It
is
made
out
of
a
contiguous
block
of
memory
that
is
divided
into
a
number
of
"Memory Blocks." Each Memory Block can hold a value, and all of the values are of the same type. The Memory Blocks are indexed 0 through SIZE -1 and each Memory
Block
can
be accessed by using its index.
To create an array, you need to perform two steps:
1. declare
an
array:
Syntax:
Type arrayname [ ];
2. Create an array using
'new' keyword (Allocate space for its elements):
Syntax:
arrayname = new Type[ Size ];
Above steps can be combined as follows
Type arrayname = new Type[ Size];
Where Type may be any data type or reference Type (class name).
Ex:
Assume
n = 5
int a[ ];
a = new int[n];
Or
int a[ ] = new
int[n];
Memory
Map:
Initialization of 1-D array:
Type
arrayname[ ] = { value1,value2,value3,........value n };
Ex: int a[] = {10,20,30,40,50};
Two Dimensional Array
In addition to one dimensional
we can create arrays of two or more dimensions. In Java, Multidimensional array are implemented as arrays of arrays. You need to perform
two steps
to work with multidimensional
arrays: 1. Declare the array and 2. Allocate space for its elements. When constructing a two-dimensional array, you specify how many rows and
columns you need:
Type arrayname [ ] [
];
arrayname = new Type [M][N];
Where M = no of rows N= no of columns..
Above two steps can be combined as follows
Type arrayname [ ][ ] = new Type[ M][N];
Ex:
int a[][];
a = new
int [M][N];
OR
int a[ ][ ] = new int[
M
][N];
float a[ ][ ] = new float[2][2];
Here a is two dimensional array having 2 rows and 2 columns. i.e. size is 4, we can store 4 elements in that array.
Post a Comment