By
Dr. Yasser Abdelhamid
2D arrays
http://www.javatpoint.com/
Pearson Education, Inc. slides
Dr. Yasser Abdelhamid
Thebrackets of the array type can be
associated with the element type or with the
name of the array
Thereforethe following two declarations are
equivalent:
double[] prices;
double prices[];
Thefirst format generally is more readable
and should be used
Copyright © 2014 Pearson Education, Inc.
An initializer list can be used to instantiate
and fill an array in one step
Thevalues are delimited by braces and
separated by commas
Examples:
int[] units = {147, 323, 89, 933,
540,269, 97, 114, 298, 476};
char[] grades = {'A', 'B', 'C', 'D',
’F'};
Copyright © 2014 Pearson Education, Inc.
Note that when an initializer list is used:
the new operator is not used
no size value is specified
The size of the array is determined by the number
of items in the list
Aninitializer list can be used only in the array
declaration
See Primes.java
Copyright © 2014 Pearson Education, Inc.
//********************************************************************
// Primes.java Author: Lewis/Loftus
//
// Demonstrates the use of an initializer list for an array.
//********************************************************************
public class Primes
{
//-----------------------------------------------------------------
// Stores some prime numbers in an array and prints them.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println("Array length: " + primeNums.length);
System.out.println("The first few prime numbers are:");
for (int prime : primeNums)
System.out.print(prime + " ");
}
}
Copyright © 2014 Pearson Education, Inc.
Output
//********************************************************************
// Primes.java Author: Lewis/Loftus
// Array length: 8
// Demonstrates The
the first
use of few
an initializer list for
prime numbers are:an array.
//********************************************************************
2 3 5 7 11 13 17 19
public class Primes
{
//-----------------------------------------------------------------
// Stores some prime numbers in an array and prints them.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println("Array length: " + primeNums.length);
System.out.println("The first few prime numbers are:");
for (int prime : primeNums)
System.out.print(prime + " ");
}
}
Copyright © 2014 Pearson Education, Inc.
Declaring and Using Arrays
Arrays of Objects
Two-Dimensional Arrays
Copyright © 2014 Pearson Education, Inc.
A one-dimensional array stores a list of elements
A two-dimensional array can be thought of as a
table of elements, with rows and columns
one two
dimension dimensions
Copyright © 2014 Pearson Education, Inc.
Tobe precise, in Java a two-dimensional
array is an array of arrays
A two-dimensional array is declared by
specifying the size of each dimension
separately:
int[][] table = new int[12][50];
Anarray element is referenced using two
index values:
value = table[3][6]
Thearray stored in one row can be specified
using one index
Copyright © 2014 Pearson Education, Inc.
//********************************************************************
// TwoDArray.java Author: Lewis/Loftus
//
// Demonstrates the use of a two-dimensional array.
//********************************************************************
public class TwoDArray
{
//-----------------------------------------------------------------
// Creates a 2D array of integers, fills it with increasing
// integer values, then prints them out.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int[][] table = new int[5][10];
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;
// Print the table
for (int row=0; row < table.length; row++)
{
for (int col=0; col < table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
}
}
Copyright © 2014 Pearson Education, Inc.
//********************************************************************
// TwoDArray.java Author: Lewis/Loftus
//
// Demonstrates the use of a two-dimensional array.
//********************************************************************
Output
public class TwoDArray
0 { 1 2 3 4 5 6 7 8
9
//-----------------------------------------------------------------
10 // Creates
11 12 a 2D array
13 of 14
integers,15fills it
16with increasing
17 18
// integer values, then prints them out.
19
20 //-----------------------------------------------------------------
21 22 23 24 25 26 27 28
public static void main(String[] args)
29
{
30 31 int[][]
32 table =33new int[5][10];
34 35 36 37 38
39
40 41 // Load
42 the table
43 with 44
values 45 46 47 48
49 for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;
// Print the table
for (int row=0; row < table.length; row++)
{
for (int col=0; col < table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
}
}
Copyright © 2014 Pearson Education, Inc.
Which of the following are valid declarations?
Which instantiate an array object? Explain
your answers.
int primes = {2, 3, 4, 5, 7, 11};
Invalid; an int cannot be declared and initialized using an
intializer list. The brackets are missing.
float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88};
Valid; the brackets can be placed either after the element type
or after the reference variable. However, this is not the
preferred technique. This declaration creates an array object.
int[] scores = int[30];
Invalid; the right hand side of the assignment operator
must contain either an initializer list or a new operation.
int[] primes = new {2,3,5,7,11};
Invalid; “new” on the right hand side of the assignment
operator is neither necessary nor acceptable.
Copyright © 2014 Pearson Education, Inc.
int[] scores = new int[30];
Valid; the assignment is correct Java syntax. This
declaration creates an array object.
char grades[] = {'a', 'b', 'c', 'd', 'f'};
Valid; the brackets can be placed either after the element
type or after the reference variable. However, this is not
the preferred technique. This declaration creates an array
object.
char[] grades = new char[];
Invalid; the size of the array must be indicated when the
array is instantiated.
Copyright © 2014 Pearson Education, Inc.
Write an array declaration and any necessary supporting
classes to represent the following statements:
a. students’ names for a class of 25 students
String[] students = new String[25];
b. students’ test grades for a class of 40 students
int[] grades = new int[40];
or, for simple letter grades:
char[] grades = new char[40];
or, for letter grades that include pluses and minuses
String[] grades = new String[40];
c. students’ names for a class and homework grades for each
student
Student[] myClass = new Student[MAX];
public class Student
{
private String name;
private int[] grades;
}
Copyright © 2014 Pearson Education, Inc.
d. for each employee of the L&L International Corporation:
the employee number, hire date, and the amount of the last
five raises
Employee[]employees = new Employee[MAX];
public class Employee
{
private int employeeNumber;
private String hireDate;
private double raise[] = new double[5];
}
Copyright © 2014 Pearson Education, Inc.
Describe what problem occurs in the following code.
What modifications shouldbe made to it to eliminate
the problem?
int[] numbers = {3, 2, 3, 6, 9, 10, 12, 32, 3, 12, 6};
for (int count = 1; count <= numbers.length; count++)
System.out.println(numbers[count]);
The for loop fails to print the 0th element of the array, and
attempts to print the nonexistent 11th element of the
array. As a consequence, an
ArrayIndexOutOfBoundsException is thrown. The
problem can be eliminated by providing a for loop which
initializes count to 0 (rather than 1) and tests if count is
less than (rather than less than or equal to)
numbers.length.
Copyright © 2014 Pearson Education, Inc.
Write code that sets each element of an array called
nums to the value of the constant INITIAL.
for (int index = 0; index < nums.length; index++)
nums[index] = INITIAL;
Write code that prints the values stored in an array
called names backwards.
for (int index = names.length-1; index >= 0; index--)
System.out.println(names[index]);
Write a method called sumArray that accepts an array of
floating point values and returns the sum of the values stored
in the array.
public float sumArray(float[] values)
{
float sum = 0;
for (int index = 0; index < values.length; index++)
sum += values[index];
return sum;}
Copyright © 2014 Pearson Education, Inc.