Arrays
Arrays
common name. For example, we can define an array name salary to represent a
set of salaries of a group of employees. A particular value is indicated by
writing a number called index number or subscript in brackets after the array
name. For example,
Salary [10]
one-dimensional array :A list of items can be given one variable name using
only one subscript and such a variable is called a single-subscripted variable
or a one-dimensional array.
Declaration of an array:
Array in java may be declared in two forms:
Form1
type arrayname [];
Form2
Type [] arrayname;
For example,
int number [];
int [] number;
Creation of Arrays:
After declaring an array, we need to create it in the memory. Java allows us to create arrays using new
operator only, as shown below:
For example,
Number [0] = 35;
Number [1] = 40;
We can also initialize a list of values separated by commas and surrounded by curly braces. Note that no
size id given. The compiler allocates enough space for all the elements specified in the list. For example:
int number [] = {35, 40, 20, 57, 19};
}
}
Two-Dimensional Arrays: A list of items can be given one variable name using two
subscript and such a variable is called a two-subscripted variable or a two-
dimensional array.
Declaration of variable:
int myArray [] [];
Creating of array:
myArray [] [] = new int [3] [4];
Initialization of an array:
int myArray [] [] = {0, 0, 0, 1, 1, 1};
This statement can also be written as
Int myArray [] [] = {{0, 0, 0},{1, 1, 1}};
We can also initialize two-dimensional array as
Int myArray [] [] = {
{0, 0, 0},
{1, 1, 1}
};
//Program to display Multiplication Table using two-dimensional //array.
class MulTable
{
final static int ROWS = 20;
final static int COLS =20;
public static void main(String args[])
{
int product[][] = new int [ROWS][COLS];
int row,col;
System.out.println("Multiplication Table");
int i,j;
for(i =10; i<ROWS; i++)
{
for(j=10;j<COLS;j++)
{
product[i][j] = i*j;
System.out.print(" " + product[i][j]);
}
System.out.println(" ");
}
}
}
Instance data: The variable which allocates memory space for each instance of the
class is called instance data. In the above example, width, height, and depth are
instance data (or variable).
There are two methods to declare objects.
First method:
Box mybox = new Box (); Width
Height
mybox Depth
Second method:
Box mybox; Null
Mybox = new Box ();
mybox
Introducing Methods: