Arrays (Java Tutorial)
Arrays (Java Tutorial)
Agenda
What is an array
Declaration of an array
Instantiation of an array
Array length
Multi-dimensional array
What is an Array?
3
Introduction to Arrays
Introduction to Arrays
Declaration of
an Array
6
Declaring Arrays
or
int ages[];
Instantiation of
an Array
8
Array Instantiation
Instantiation
Constructor
Array Instantiation
10
Array Instantiation
11
Array Instantiation
12
Sample Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
13
Accessing Array
Element
14
15
16
NOTE:
for reference data types such as Strings, they are NOT initialized to
blanks or an empty string . Therefore, you must populate the String
arrays explicitly.
17
18
Coding Guidelines
1. It is usually better to initialize or instantiate the
array right away after you declare it. For example,
the declaration,
int []arr = new int[100];
is preferred over,
int []arr;
arr = new int[100];
19
Coding Guidelines
2. The elements of an n-element array have indexes
from 0 to n-1. Note that there is no array element
arr[n]! This will result in an array-index-out-ofbounds exception.
3. Remember: You cannot resize an array.
20
Array Length
21
Array Length
22
Array Length
1
2
3
4
5
6
7
8
9
23
Coding Guidelines
1. When creating for loops to process the elements of an
array, use the array object's length field in the condition
statement of the for loop. This will allow the loop to adjust
automatically for different-sized arrays.
2. Declare the sizes of arrays in a Java program using named
constants to make them easy to change. For example,
final int ARRAY_SIZE = 1000; //declare a constant
. . .
int[] ages = new int[ARRAY_SIZE];
24
Multi-Dimensional
Array
25
Multidimensional Arrays
26
Multidimensional Arrays
For example,
// integer array 512 x 128 elements
int[][] twoD = new int[512][128];
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
// String array 4 rows x 2 columns
String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};
27
Multidimensional Arrays
28
Summary
Arrays
Definition
Declaration
Accessing an element
Multidimensional Arrays
29