Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Arrays
collection of similar type of elements.
contiguous memory location.
is index based
Advantage
Code Optimization
Random access
Types of Array in java
Arrays
Single Dimensional
Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation
Array RefVar=new datatype[size];
Arrays
Arrays
Arrays
Multidimensional
stored in row and column.
Based on index (matrix form).
Example to instantiate
int[][] arr=new int[3][3];
Arrays
Example to initialize Multidimensional Array
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Arrays
Arrays
Is an object.
Person mary = new Person ( );
int myArray[ ] = new int[5];
int myArray[ ] = {1, 4, 9, 16, 25};
String languages [ ] = {"Prolog",
"Java"};
allocated dynamically.
so fewer memory leaks
Java doesnt have pointers!
Arrays
Arrays
Specify type,
use new operator
Two steps:
int c[]; //declaration
c = new int[ 12 ]; //initialization
One step:
int c[] = new int[12];
Primitive elements initialized to zero or false
Non-primitive references are null
Multiple declarations:
String b[] = new String[ 100 ], x[] = new String[ 27 ];
Also:
double[] array1, array2;
Put brackets after data type
Arrays
Examples Using Arrays
new
Dynamically creates arrays
Method length
Returns length
myArray.length
Initializer lists
int myArray[] = { 1, 2, 3, 4, 5 };
new operator not needed
provided automatically
Arrays
char chararra[] = new char [255]
MyObj ObjArra[];
Arrays
Multiple-Subscripted Arrays
Represent tables
Arranged by m rows and n columns (m by n array)
Can have more than two subscripts
Declaration
Double brackets
int b[][];
b = new int[ 3 ][ 3 ];
Declares a 3 by 3 array
Arrays
Declaration (continued)
Initializer lists
int b[][] = { { 1, 2 }, { 3, 4 } };
1 2
3 4
int b[][];
b = new int[ 2 ][ ];
b[ 0 ] = new int[ 5 ];
b[ 1 ] = new int[ 3 ];
THANKS..