Slaid FP301 OOP Topic 2.3 Array UPLOAD
Slaid FP301 OOP Topic 2.3 Array UPLOAD
@
An array is a container object that holds a fixed number of
values of a single type
Numbers
100
150
49
225
For example, int[] list; creates a variable named list of type int[ ].
This variable is capable of referring to an array of ints, but initially its
value is null
list
It does not create the array object or allocate space for
array elements.
©AZROL HISHAM JTMK PSIS 7
Declaring a One-Dimensional Array
• Syntax: type [] array_identifier;
or
type array_identifier [] ;
• Examples:
char [] status; int [] ages; Shirt [] shirts; String [] names;
The square brackets may appear as part of the type at the beginning
of the declaration or as part of the array identifier (after identifier)
It is illegal to specify the size of an array during declaration.
(5) list.length
0 list(0) The array objects contains
The statement list=new int[5];
create an array that can hold five five integers which are refer
0 list(1) to as list[0],list[1] and so on.
ints and set the list to refer to its.
0 list(2) Its also contain list.length
which give the number of
0 list(3) item in the array. list.length
can’t be change
0 list(4)
•To create an array involve two step, first declare array variable, second
step allocate a memory for array.
Syntax to declare array:
type [] array_identifier; OR type array_identifier [] ;
Syntax to allocate memory for array
array_identifier = new type [length];
Example:
char [] status = new char [20];
int[] ages = new int [5];
float[] floatNum = new float[20];
Example
int marks_table[][] = new int[5][3];
float hutangKau [][] = new float[10][5];
double belanjaRumah [][] = new double[5][4];
for(int i=0;i<5;i++)
{
System.out.print("Enter the marks: ");
str = stdin.readLine();
marks[i] = Integer.parseInt(str);
}
for(int x=0;x<2;x++){
for(int y=0;y<3;y++){
System.out.println("Marks:” +
marks[x][y]);
}
}
return arrayName;
}
©AZROL HISHAM JTMK PSIS 25
Example:
int [ ] num = {1, 2, 3};
testingArray(num); //Method call
System.out.println("num[0] = " + num[0] + "\n num[1] = " +
num[1] + "\n num[2] =" + num[2]);
...