You are on page 1of 33

Arrays in Java

Lecture 5

The Institute of Finance Management


Faculty Of Computing, Information Systems & Mathematics
Computer Science Department
Introduction to Arrays
• Primitive variables are designed to hold only
one value at a time
Introduction to Arrays
• Array is a data structure that represents a collection
of data of the same types
Declaring Array Variables
• This statement declares numbers as an array
reference variable.
Datatype [] arrayRefVar;
• Example:
int [] numbers; // declares a reference to an
// array that hold int
• The numbers variable can reference an array of int values.

• Declaring an array reference variable does not create an array.


So we use the new keyword to create an array and assign its
address to the numbers variable.
Creating arrays
int [] numbers;
numbers = new int[6]; //creates a new array that hold 6
integers
or
int [] numbers = new int[6]; // declare and create in 1-step

• The number inside the brackets indicates the number of elements, or


values, the array can hold.
• Array element values are initialized to 0 for the numeric primitive data
types, '\u0000' for char types, false for Boolean types, and null for
reference types;
The Length of an Array
• Once an array is created, its size is fixed. It cannot be
changed.
• You can find its size using
arrayRefVar.length
(in Java, arrays are objects!)
• For example
numbers.length; // returns 6
Accessing the Elements of an Array
• An array is accessed by indexed variable which
includes:
1. The reference name
2. An index that identifies which element in the array to
access. Index numbering always starts at zero (0-based)
Using Indexed Variables
• After an array is created, an indexed variable can
be used in the same way as a regular variable.
(see ArrayDemo1.java)

• Array subscripts can be accessed using variables


(such as for loop counters). (see
ArrayDemo2.java)
ArrayDemo1.java
ArrayDemo2.java
Bounds Checking
• Array indexes always start at zero and continue to
(array.length - 1).

int[] values = new int[3];

• This array would have indexes 0 through 2. Trying to


access indexes more than 2 will cause an runtime
error.
values[2] = 7; // ok
values[3] = 9; // error
Initializing an array
• Declaring, creating, initializing in one step:
int[ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};

• The numbers in the list are stored in the array in


order:
days[0] is assigned 31,
days[1] is assigned 28,
days[2] is assigned 31,
days[3] is assigned 30,
etc

• Note: you do not use the new keyword when you


use an initialization list.
ArrayInitialization.java
int[ ] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

for (int index = 0; index < days.length; index++){


System.out.println("Month " + (index + 1) + " has "
+ days[index] + " days.");
}
Outputs:
Month 1 has 31 days.
Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.
Alternate Array Declaration
• Previously we showed arrays being declared
(preferred):
int[] numbers;

• However, the brackets can also go here:


int numbers[];

• Multiple arrays can be declared on the same line.


int[] numbers, codes, scores
The Arrays.sort Method
• Since sorting is frequently used in programming, Java provides
several overloaded sort methods for sorting an array of int, double,
char, short, long, and float in the java.util.Arrays class.
• For example, the following code sorts an array of numbers and an
array of characters in ascending order.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


java.util.Arrays.sort(numbers);

Output: 1.9 2.9 3.4 3.5 4.4 6.0

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


java.util.Arrays.sort(chars);

Output: 4 A D F P a
The enhanced for loop
• Simplified array processing (read only)
• Iterate once for every elements in an array. Each time the
loop iterates, it copies an array element to a variable.
• General format:
for(datatype elementVariable : array) statement;

Example:

int[] numbers = {3, 6, 9};


for(int val : numbers) {
System.out.println("The next value is " + val);
}
Create Array Dynamically
Reassigning Array References
• An array reference can be assigned to another array of the same type
// Create an array referenced by the numbers
variable.
int[] numbers = new int[10];
// Reassign numbers to a new array.
numbers = new int[5]

• The first statement creates 10 elements integer array and assigns its
address to the numbers variable.
• The second statement allocate 5 elements integer array and assigns its
address to the numbers variable
Reassigning Array References

• After the second statement executes, the numbers variable


references the five element array instead of the ten element
array.
• Because the ten element array is no longer referenced, it
cannot be accessed.
String Array
• Arrays are not limited to primitive data.
• An array of String objects can be created: String[]
names = { "Bill", "Susan", "Steven", "Jean" };
MonthDays.java
String Array
• If an initialization list is not provided, the new keyword must be
used to create the array:

String[] names = new String[4];


String Array
• When an array is created in this manner, each
element of the array must be initialized
Array of objects
• An array can hold objects as well as primitive type values. An array of
objects is actually an array of reference variables.
• The code below declares an array of five BankAccount objects. The
variable that references the array is named accounts.

BankAccount[] accounts = new BankAccount[5]


Two Dimensional Arrays
• A two-dimensional array is an array of arrays.
• It is very common to use a two-dimensional (2D) array to
represent a matrix, a table, or an image.
• A 2D array has rows and columns.
Two Dimensional Arrays
• Declaring a two-dimensional array requires two sets of
brackets and two size declarators
 The first one is for the number of rows
 The second one is for the number of columns

• The two sets of brackets in the data type indicate that the
scores variable will reference a two-dimensional array.
Accessing Two-Dimensional Array Elements
Accessing Two-Dimensional Array Elements
Array Initializer
• You can also use an array initializer to declare,
create and initialize a two-dimensional array.
• For example,
Accessing Two-Dimensional Array Elements
Multidimensional Arrays

• Occasionally, you will need to represent n-


dimensional data structures. In Java, you can create
n-dimensional arrays for any integer n.

• The way to declare two-dimensional array variables


and create two-dimensional arrays can be
generalized to declare n-dimensional array variables
and create ndimensional arrays for n >= 3.
Multidimensional Arrays Declaration
END

You might also like