20ES3102 Java Programming Unit I Chapter 3 Arrays
20ES3102 Java Programming Unit I Chapter 3 Arrays
Arrays
• Array Basics
• Arrays in Classes and Methods
• Programming with Arrays and
Classes
• Sorting Arrays
• Multidimensional Arrays
Motivation
• How to organize 100 Student objects?
• 100 different Student object names?
• Organize data for efficient access
– Class: different data types in one object
– Array: multiple objects of the same type
Overview
• An array
– a single name for a collection of data values
– all of the same data type
– subscript notation to identify one of the values
• A carryover from earlier programming languages
• More than a primitive type, less than an object
– like objects when used as method parameters and return
types
– do not have or use inheritance
• Accessing each of the values in an array
– Usually a for loop
Creating Arrays
• General syntax for declaring an array:
• Examples:
80-element array with base type char:
char[] symbol = new char[80];
pressure[3] = keyboard.nextInt();
System.out.println("You entered" + pressure[3]);
Some Array Terminology
Array
name
temperature[n + 2] Index - also called a subscript
- must be an int,
- or an expression that evaluates to an
temperature[n + 2] int
Indexed variable - also called an
element or subscripted variable
temperature[n + 2] Value of the indexed variable
- also called an element of the
temperature[n + 2] = 32; array
Programming Tip:
Do not count on default initial values for array elements
– explicitly initialize elements in the declaration or in a loop
Arrays, Classes, and Methods
An array of a class can This excerpt from the Sales Report program
be declared and the in the text uses the SalesAssociate class
class's methods applied
to the elements of the to create an array of sales associates:
array.
public void getFigures()
create an array of {
SalesAssociates System.out.println("Enter number of sales associates:");
numberOfAssociates = SavitchIn.readLineInt();
SalesAssociate[] record =
each array element is new SalesAssociate[numberOfAssociates];
a SalesAssociate for (int i = 0; i < numberOfAssociates; i++)
variable {
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
use the readInput record[i].readInput();
method of System.out.println();
SalesAssociate }
}
Arrays and Array Elements
as Method Arguments
• Arrays and array elements can be
– used with classes and methods just like other
objects
– be an argument in a method
– returned by methods
public static void main(String[] arg)
Indexed {
Scanner keyboard = new Scanner(System.in);a
Variables System.out.println("Enter your score on exam 1:");
int firstScore = keyboard.nextInt();
as Method int[ ] nextScore = new int[3];
int i;
Arguments double possibleAverage;
for (i = 0; i < nextScore.length; i++)
nextScore[i] = 80 + 10*i;
nextScore is
for (i = 0; i < nextScore.length; i++)
an array of ints {
possibleAverage = average(firstScore, nextScore[i]);
System.out.println("If your score on exam 2 is "
an element of + nextScore[i]);
nextScore is System.out.println("your average will be "
+ possibleAverage);
an argument of
}
method }
average public static double average(int n1, int n2)
{
average return (n1 + n2)/2.0;
method definition } Excerpt from ArgumentDemo
program in text.
16
Passing Array Elements
public static void main(String[] arg)
{
SalesAssociate[] record = new SalesAssociate[numberOfAssociates];
int i;
for (i = 0; i < numberOfAssociates; i++)
{
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
record[i].readInput();
}
m(record[0]);
}
public static void m(SalesAssociate sa)
{
}
When Can a Method Change an
Indexed Variable Argument?
• primitive types are “call-by-value”
– only a copy of the value is passed as an argument
– method cannot change the value of the indexed variable
• class types are reference types (“call by reference”)
– pass the address of the object
– the corresponding parameter in the method definition
becomes an alias of the object
– the method has access to the actual object
– so the method can change the value of the indexed
variable if it is a class (and not a primitive) type
Passing Array Elements
int[] grade = new int[10];
obj.method(grade[i]); // grade[i] cannot be changed
• In this example, the output from the command line above will be:
Hello Josephine Student
Using = with Array Names:
Remember They Are Reference Types
A value changed in a
The output for this code will be:
is the same value
2 2 obtained with b
10 10
Using == with array names:
remember they are reference types
int i; a and b are both
int[] a = new int[3]; 3-element arrays of ints
int[] b = new int[3];
for(i=0; i < a.length; i++) all elements of a and b are
a[i] = 0; assigned the value 0
for(i=0; i < b.length; i++)
tests if the
b[i] = 0; addresses of a
if(b == a) and b are equal,
System.out.println("a equals b"); not if the array
else values are equal
System.out.println("a does not equal b");
The output for this code will be " a does not equal b"
because the addresses of the arrays are not equal.
Behavior of Three Operations
Primitive Class Entire Array
Type Type Array Element
Assignment Copy content Copy Copy Depends on
(=) address address primitive/
class type
Equality Compare Compare Compare Depends on
(==) content address address primitive/
class type
Parameter Pass by Pass by Pass by Depends on
Passing value reference reference primitive/
(content) (address) (address) class type
Testing Two public static boolean equals(int[] a,
int[] b)
Arrays for {
boolean match = false;
Equality if (a.length == b.length)
{
match = true; //tentatively
• To test two arrays for int i = 0;
equality you need to while (match && (i < a.length))
{
define an equals if (a[i] != b[i])
match = false;
method that returns i++;
true if and only the }
}
arrays have the same return match;
}
length and all
corresponding values
are equal
public class returnArrayDemo
{
public static void main(String arg[])
Methods {
char[] c;
c = vowels();
that Return for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
an Array public static char[] vowels()
{
• the address of char[] newArray = new char[5];
newArray[0] = 'a';
the array is newArray[1] = 'e';
passed newArray[2] = 'i';
newArray[3] = 'o';
• The local array newArray[4] = 'u';
return newArray;
name within the }
}
method is just
another name c, newArray, and
for the original the return type of
vowels are
array
all the same type:
char []
Searching an Array
• There are many techniques for searching an array for a particular value
• Sequential search:
– start at the beginning of the array and proceed in sequence until either
the value is found or the end of the array is reached*
• if the array is only partially filled, the search stops when the last
meaningful value has been checked
– it is not the most efficient way
– but it works and is easy to program
* Or, just as easy, start at the end and work backwards toward the beginning
Example: Sequential Search of an Array
public boolean onList(String item)
{
boolean found = false;
int i = 0;
while ((! found) &&
(i < countOfEntries))
The onList method of {
OneWayNoRepeatsList if (item.equals(entry[i]))
found = true;
sequentially searches the else
array entry to see it the i++;
parameter item is in the }
array
return found;
}
Gotcha: Returning an
Array Attribute (Instance Variable)
• Access methods that return references to array instance variables cause
problems for information hiding.
Example: class …
{
private String[] entry;
…
public String[] getEntryArray()
{
return entry;
}
Even though entries is declared private, a method outside the class
can get full access to it by using getEntryArray.
• In most cases this type of method is not necessary anyhow.
• If it is necessary, make the method return a copy of the array instead of
returning a reference to the actual array.
Sorting an Array
• Sorting a list of elements is another very common problem (along with
searching a list)
– sort numbers in ascending order
– sort numbers in descending order
– sort strings in alphabetic order
– etc.
• There are many ways to sort a list, just as there are many ways to
search a list
• Selection sort
– one of the easiest
– not the most efficient, but easy to understand and program
Selection Sort Algorithm
for an Array of Integers
To sort an array on integers in ascending order:
1. Find the smallest number and record its index
2. swap (interchange) the smallest number with the first
element of the array
– the sorted part of the array is now the first element
– the unsorted part of the array is the remaining
elements
3. repeat Steps 2 and 3 until all elements have been placed
– each iteration increases the length of the sorted part
by one
Key:
Selection Sort Example smallest remaining value
sorted elements
1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4]
before: 7 6 11 17 3 15 5 19 30 14
after: 3 6 11 17 7 15 5 19 30 14
2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6]
3 6 11 17 7 15 5 19 30 14
3 5 11 17 7 15 6 19 30 14
• Arrays with more than two dimensions are a simple extension of two-
dimensional (2-D) arrays
Indexes 0 1 2 3 4 5
0 $1050 $1055 $1060 $1065 $1070 $1075
1 $1103 $1113 $1124 $1134 $1145 $1156
2 $1158 $1174 $1191 $1208 $1225 $1242
3 $1216 $1239 $1262 $1286 $1311 $1335
Row Index 3 4 $1276 $1307 $1338 $1370 $1403 $1436
(4th row) … … … … … … …