ARRAYS IN
JAVA (ONE-DIMENSIONAL ARRAYS)
TOPICS
· Declaration for 1-dimensional Arrays / Syntax
· Arrays and Methods (Passing Arrays as Arguments)
· Common Operations with One-Dimensional
Arrays
· Read
· Print
· Initialize using an expression
· Sum
· Find
max
· Find
min
· Initialize with random
integers. Range 0 - MAX
· Initialize with random
integers. Range MIN - MAX
Program
#1: Java Program - Putting together some of the most common
operations for 1-dim arrays
Program #2: Java Program
- Common operations with an array of temperatures
OUTLINE
·
A
structured data type is a type that:
o Stores a collection of
individual components. The whole collection has just one variable name
o Allows individual components
from the collection to be stored and retrieved
o Example: Declare variables to store
and total 3 blood pressures
short bp1,
bp2, bp3, total;
Scanner input = new Scanner(System.in);
bp1 = input.nextShort();
bp2 = input.nextShort();
bp3 = input.nextShort();
total = bp1 + bp2 + bp3;
The problem is: what if you want to store and sum 1000 blood
pressures? The program would have more than 3000 lines, and you should use 1000
separate variables. Should be a better way - use a collection of variables, all
of the same type, in which the first part of each variable name is the same,
and the last part is an index value.
short[] bp = new short[1000];//
declares an array of 1000 short integer values
· An array is a
structured data type with the following properties:
Declaring
1-dimensional arrays: Syntax
dataType[]
arrayName = new dataType[length];
Where:
·
dataType - describes the type of data
stored in each component/element of the array
·
arrayName - the name of the array
·
length- the length of the array is specified between [ ] brackets.
The array's length can be any positive integral expression.
NOTE #1: A
one-dimensional array is an array in which the components are arranged in a
list form.
NOTE #2: (Java) When arrays are declared, every element is
automatically initialized to a "zero-equivalent" value.
int:
0
double: 0.0
boolean:
false
char: '\0' (the "null character")
String or object: null (null means "no object")
Example #1: Declare an array called temps
which will hold up to 5 temperatures (of type int).
int[]
temps = new int[5];
Example #2: Declare an array called name
that will hold up to 10 individual char values.
char[] name = new char[10];
Example #3: Declare an array called numbers which will hold up to 10
values (of type int).
int[]
numbers = new int[10];
Array Length - Can be any integral expression (constant OR variable).
Example #1:
int[]
someArray = new int[70];//constant
Example #2:
public
static final int SIZE = 70;
...
int[]
someArray = new int[SIZE];//named constant
Example #3: Dynamic arrays = Arrays that are created
during program execution are called dynamic arrays (size--> input at run
time).
...
int
size;
System.out.print("Enter
the the array size: ");
size = input.nextInt();
...
int[]
someArray = new int[size];//variable, input from user (dynamic array)
Example #4:
...
int
size;
System.out.print("Enter
some positive integer: ");
size = input.nextInt();
...
int[]
someArray = new int[size %
2 + 1];//expression
Example #5: Initialization in declaration
int[]
someArray = {37, 12, 32, 50, 49}; //declaration + initialization
The values, called initial values, are placed between braces and separated by
commas: someArray[0] = 37, someArray[1] = 12, etc. You
don't explicitly specify the array's size in this syntax. The length (size) of
the array is determined by the number of initial values within the braces. If
an array is declared and initialized simultaneously, do not use the operator new to instantiate
the array object. This syntax is useful when you know in advance what the
array's element values will be. Doesn't work for large size arrays. Another
example:
short[]
ages = {40, 13, 20, 19, 36};
...
for (int i
= 0; i < ages.length; i++)
System.out.print(ages[i] + " ");
An array's length field stores its number of elements (the
size of the array). The length can be directly accessed in a program using the
array name and the dot operator.
General syntax:
arrayName.length
NOTE #1: It does not use parentheses like a String's .length()
NOTE #2: The value of length cannot
be changed (other than by creating an entirely new array using new)
Example # 1:
for (int i = 0; i
< temps.length; i++) {
System.out.print(temps[i] + " ");
}
What the index of the last element of the array? The
middle element?
Example # 2:
int[]
list = new int[10];
System.out.print("The
size of the array is: " + list.length);
//OUTPUT:
//The size of the array is: 10
Example # 3:
int[]
list = {10, 20, 30, 40, 50, 60, 70};
System.out.print("The
size of the array is: " + list.length);
//OUTPUT:
//The size of the array is: 7
Valid Indexes - Can be variables,
expressions, or constants
float[]
temps = new float[5];
int
m = 3;
. . . . . .
What is temps[m +
1]
?
What is temps[m] + 1?
public
static final int SIZE = 100;
...
int[]
someArray = new int[SIZE];
Example:
public
static double average(int[] list) {
int sum = 0;
for (int i = 0; i < list.length;
i++) {
sum += list[i];
}
return (double) sum / list.length;
}
for (int i = 0; i
< a.length; i++) {
b[i] = a[i];
}
Note that the above code will not make b an exact copy of a,
unless a and b have the same length. See the method copyArray below.
For the same reason, the equality operator (= =) only tests two arrays to see
if they are stored in the same location in memory; (a == b) does not test
two arrays to see if they contain the same values. Two arrays must be tested to
see if they contain the same elements using for loops as in the method equals below.
public
static int[] incrementArray(int[] a, int increment){
int[] temp =
new int[a.length];
for (int i = 0; i < a.length;
i++)
temp[i] = a[i] + increment;
return temp;
}
The Arrays
class in package java.util has several useful static methods for manipulating
arrays (See http://java.sun.com/javase/6/docs/api/
- select the package java.util and from the lower panel
select the Arrays
class.)
Some of these methods are:
METHOD
NAME |
DESCRIPTION |
binarySearch(array, value) |
returns the index of the given
value in this array (< 0 if not found) |
equals(array1, array2) |
returns true if the two given
arrays contain exactly the same elements in the same order |
fill(array, value) |
sets every element in the array to
have the given value |
sort(array) |
arranges the elements in the array
into ascending order |
toString(array) |
returns a string representing the
array, such as "[100, 130, 175]" |
The Arrays.toString
method is useful when you want to print the elements of an array. The method Arrays.toString
accepts an array as a parameter and returns the String representation, which you can then
print.
Example:
//Test for Arrays class
import java.util.Arrays;
import java.util.Scanner;public class ArraysClass_Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int key, index;
int[] a = {59, 4, 30, 12, 91};
int[] b = new int[a.length];
b[0] = a[0];
for (int i = 1; i < a.length; i++) {
b[i] = a[i - 1] + a[i];
}
System.out.println("Array a is: " + Arrays.toString(a));
System.out.println("Array b is: " + Arrays.toString(b));
System.out.println("\nCalling binarySearch for array b. ");
System.out.print("Enter search key: ");
key = input.nextInt();
index = Arrays.binarySearch(b, key);
if(index < 0)
System.out.println("Key NOT found!");
else
System.out.println("Key found in the element with index " + index);
Arrays.sort(a);
Arrays.sort(b);
System.out.println("The sorted array a is: " + Arrays.toString(a));
System.out.println("The sorted array b is: " + Arrays.toString(b));
Arrays.fill(b, 59);
System.out.println("Array b (after .fill) is: " + Arrays.toString(b));
}
}
OUTPUT:
Array a is: [59, 4, 30, 12, 91]
Array b is: [59, 63, 34, 42, 103]Calling binarySearch for array b.
Enter search key: 34
Key found in the element with index 2
The sorted array a is: [4, 12, 30, 59, 91]
The sorted array b is: [34, 42, 59, 63, 103]
Array b (after .fill) is: [59, 59, 59, 59, 59]
Common
operations with 1-dimensional arrays:
Some of the basic operations performed on one-dimensional arrays are to initialize the array, input data, output data stored in the array (direct and reverse order), find the largest and/or smallest element in the array, initialize with random numbers, and copy. You will find these and other common 1-dim arrays operations below. All the programs below use for loops to process all the elements of the array. Processing arrays with loops is often referred to sequential access of arrays or traversing the arrays.
1. To read in a 1-dim array (of integers):
Import package:
import java.util.Scanner;
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void readArray(int[] list) { |
public static void readArray(int[] list, int size) { |
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void printArray(int[] list) { |
public static void printArray(int[] list, int size) { |
3. To print a 1-dim array in reverse order:
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void printReverse(int[] source) { |
public static void printReverse(int[] source, int size) { |
4. To initialize the array using some expression:
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void initArray(int[] list) { |
public static void initArray(int[] list, int size) { |
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static int
sumArray(int[] list) { |
public static int
sumArray(int[] list, int size) { |
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static int
maxArray(int[] list) { |
public static int
maxArray(int[] list, int size) { |
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static int
minArray(int[] list) { |
public static int
minArray(int[] list, int size) { |
8. To copy a 1-dim array in another array:
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void copyArray(int[] source, int[] dest) { |
public static void copyArray(int[] source, int[] dest, int
s) { |
9. To fill an array with random integers in the range 0 - MAX :
Import package:
import java.util.Random;
Class constants:
public static final int SIZE = 50;
public static final int MAX = 100;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void randArray(int[] list, int up) { |
public static void randArray(int[] list, int size, int up) { |
10. To fill an array with random integers in the range MIN - MAX:
Import package:
import java.util.Random;
Class constants:
public static final int SIZE = 50;
public static final int MIN = 10;
public static final int MAX = 100;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static void randArray(int[] list, int low, int up) { |
public static void randArray(int[] list, int size, int low, int up) { |
Class constants:
public static final int SIZE = 50;
Caller:
int[] a = new int[SIZE]; |
int[] a = new int[SIZE]; |
Method Definition:
public static boolean
equals(int[] l1, int[]
l2) { |
public static boolean
equals(int[] l1, int[]
l2, int s1, int s2) { |
Program #1: Putting together some of the most common operations
//Arrays
and methods
import java.util.Scanner;
import java.util.Random;
public class OneDimArray_Test {
public static final int SIZE = 7;
public static final int MIN = 10;
public static final int MAX = 100;
public static void main(String[] args) {
int[] a = new int[SIZE];
int[] b = new int[SIZE];
int[] c = new int[SIZE];
System.out.println("Initial values/first array:
");
printArray(a, a.length);
System.out.println("Initial values/second array:
");
printArray(b, b.length);
System.out.println("Initial values/third array:
");
printArray(c, c.length);
System.out.print("Enter " + a.length + " integers: ");
readArray(a, a.length);
System.out.println("The first array is: ");
printArray(a, a.length);
//display sum
System.out.println("The sum of the
elements/first array is: " + sumArray(a, a.length));
//display max
System.out.println("Max value/first array is:
" + maxArray(a, a.length));
//display min
System.out.println("Min value/first array is:
" + minArray(a, a.length));
//copy first array into second
copyArray(a, b, a.length);
System.out.println("After copy, the second array
is: ");
printArray(b, b.length);
//generate third array using random numbers
randArray(c, c.length, MIN,
MAX);
System.out.println("The third array (using
random numbers) is: ");
printArray(c, c.length);
System.out.println();
}
//Method to input data from user
public static void readArray(int[]
list, int size) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < size; i++)
list[i] = input.nextInt();
}
//Method to create an array using random numbers
public static void randArray(int[]
list, int size, int low, int up) {
Random rand = new Random();
for (int i = 0; i < size; i++)
list[i] = rand.nextInt(up -
low + 1) + low;
}
//Method to print the array
public static void printArray(int[]
list, int size) {
for (int i = 0; i < size; i++)
System.out.print(list[i] +
" ");
System.out.println();
}
//Method to find sum
public static int sumArray(int[] list, int size) {
int sum = 0;
for (int i = 0; i < size; i++)
sum = sum + list[i];
return sum;
}
//Method to find max
public static int maxArray(int[] list, int size) {
int max = list[0];
for (int i = 1; i < size; i++) {
if(list[i] > max)
max = list[i];
}
return max;
}
//Method to find min
public static int minArray(int[] list, int size) {
int min = list[0];
for (int i = 1; i < size; i++) {
if(list[i] < min)
min = list[i];
}
return min;
}
//Method to copy one array into another array
public static void copyArray(int[]
source, int[] destination, int
size) {
for (int i = 0; i < size; i++)
destination[i] = source[i];
}
}//close class
SAMPLE OUTPUT:
Initial values/first
array:
0 0 0 0 0 0 0
Initial values/second
array:
0 0 0 0 0 0 0
Initial values/third
array:
0 0 0 0 0 0 0
Enter 7 integers: 134
23 56 78 95 12 7
The first array is:
134 23 56 78 95 12 7
The sum of the
elements/first array is: 405
Max value/first array
is: 134
Min value/first array
is: 7
After copy, the second
array is:
134 23 56 78 95 12 7
The third array (using
random numbers) is:
58 24 94 89 67 70 77
Program #2: Common operations with an array of temperatures
//Temperatures
program
import java.util.Scanner;
public class Temps
{
public static final int SIZE = 31;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] temp = new int[SIZE];
int numDays; //input from user
double avg; //average
temp --> return from method
int warmest; //max temp
--> return from method
int coldest; //min temp
--> return from method
do {
System.out.print("How many daily temperatures:
");
numDays = input.nextInt();
if(numDays < 1 || numDays
> SIZE)
System.out.println("INPUT ERROR!!! Should be 1 -
" + SIZE );
} while (numDays < 1 || numDays
>SIZE);
System.out.print("Now enter " + numDays + " temperatures: ");
getTemps(temp, numDays);
System.out.print("You entered: " );
print(temp, numDays);
avg = findAvg(temp, numDays);
warmest = findWarmest(temp, numDays);
coldest = findColdest(temp, numDays);
System.out.printf("Average temperature is:
%.2f\n", avg);
System.out.println("Highest temperature is:
" + warmest);
System.out.println("Lowest temperature is:
" + coldest);
}
//Method to input data from user
public static void getTemps(int[]
list, int size) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < size; i++)
list[i] = input.nextInt();
}
//Method to print the array
public static void print(int[] list, int size) {
for (int i = 0; i < size; i++)
System.out.print(list[i] +
" ");
System.out.println();
}
//Method to find average
public static double findAvg(int[]
list, int size) {
double avg;
int sum = 0;
for (int i = 0; i < size; i++)
sum += list[i];
avg = (double)sum / size;
return avg;
}
//Method to find max
public static int findWarmest(int[] list, int size) {
int max = list[0];
for (int i = 1; i < size; i++) {
if(list[i] > max)
max = list[i];
}
return max;
}
//Method to find min
public static int findColdest(int[] list, int size) {
int min = list[0];
for (int i = 1; i < size; i++) {
if(list[i] < min)
min = list[i];
}
return min;
}
}//close class
SAMPLE OUTPUT:
How many daily
temperatures: 34
INPUT ERROR!!! Should
be 1 - 31
How many daily
temperatures: 8
Now enter 8
temperatures: 89 88 78 67 69 90 67 70
You entered: 89 88 78 67
69 90 67 70
Average temperature
is: 77.25
Highest temperature
is: 90
Lowest temperature is:
67
Additional Resources:
1. (Sun) API specification for version 6 of the Java Platform, Standard
Edition: http://java.sun.com/javase/6/docs/api/
2. (Sun) The Java Tutorials, Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
References:
[1] Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison
Wesley, 2008.
[2] Java Programming: From Problem Analysis to Program Design, by D.S. Malik,
Thomson Course Technology, 2008