Transcript Arrays

Simple Arrays
Arrays of primitives and Strings
Sections 7.1, 7.2
Problem
Write a program to read six integers...
 ...& print them out in reverse order
 For example:

Enter the six numbers below:
5 3 7 2 99 41
In reverse order they are:
41, 99, 2, 7, 3, and 5

Can’t use a single-variable loop
 need to remember all 6 numbers
Reverse6.java
Solution
int n1, n2, n3, n4, n5, n6;
S.o.p(“Enter the six numbers
n1 = kbd.nextInt();
n2 = kbd.nextInt();
n3 = kbd.nextInt();
n4 = kbd.nextInt();
n5 = kbd.nextInt();
n6 = kbd.nextInt();
kbd.nextLine();
S.o.p(“In reverse order they
+ n6 + “, ” + n5 + “, ” +
+ n3 + “, ” + n2 + “, and
below:\n”);
are:\n”
n4 + “, ”
” + n1);
Related Problem
Write a program to read six HUNDRED
integers & print them out in reverse order
 Need 600 ints: declare, input, & output
 Individually named:
Reverse600HardWay.java

int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13,
n14, n15, n16, n17, n18, n19, n20, n21, n22, n23, n24,
n25, n26, n27, n28, n29, n30, n31, n32, n33, n34, n35,
n36, n37, n38, n39, n40, n41, n42, n43, n44, n45, n46,
n47, n48, n49, n50, n51, n52, n53, n54, n55, n56, n57,
n58, n59, n60, n61, n62, n63, n64, n65, n66, n67, n68,
n69, n70, n71, n72, n73, n74, n75, n76, n77, n78, n79,
A Better Way: Arrays
int[] n = new int[600]; // creates 600 ints
 n is called an array (of ints)
 n has 600 components or elements



Their names are:


each one is an int variable
n[0], n[1], n[2], n[3], n[4], ... , n[599]
Number in [brackets] is called the index
Multiple Variables vs. Array
int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9;
int[] n = new int[10];
n0
n
n[0]
n[1]
n[2]
n[3]
n[4]
n[5]
n[6]
n[7]
n[8]
n[9]
n1
n2
n3
n4
n5
n6
n7
n8
n9
Thinking of Array Elements
n[0], n[1], n[2], ... are just better ways to
write n0, n1, n2, ...
 Why?

 because you can say n[i] for the ith n…
 …and then you can put it in a loop
for (int i = 0; i < 600; i++) { Remember this!
… n[i] …
You’ll see it a LOT!
}
Using Arrays

Reading and printing those 600 ints?
n[0] = kbd.nextInt();
n[1] = kbd.nextInt();
n[2] = ...
System.out.print(n[599] + ‘ ’ + n[598] + ‘ ’ …);

No—use loops
for (int i = 0; i < 600; i++)
n[i] = kbd.nextInt();
for (int i = 599; i >= 0; i--)
System.out.print(n[i] + ‘ ’);
Reverse600EasyWay.java
Notes on Array Indices

We declare int[] n = new int[10]; but there is no
element called n[10]
 elements go from 0 to 9
 any other number is out of bounds
» crash with ArrayIndexOutOfBoundsException
» crash message says what the wrong index was
Low numbers are at front or top of the array
 High numbers are at back or bottom

ArrayCrash.java
Notes on Array Indices

Index will usually be a simple variable
 the loop control variable:
for (int i = 0; i < MAX; i++) {
... num[i] ...
}

Index can be any int-valued expression
... num[i + 1] ...
... num[i – 1] ...
... num[10*r + c] ...
in an i loop
in an i loop
in nested r & c loops
See, for example, StudentNames.java
Array Base Types
 Arrays can be of any base type, any size
int[] score = new int[600];
double[] weight = new double[70];
boolean[] answers = new boolean[10];
String[] words = new String[5000];
 …any type at all
Scanner[] scanners = new Scanner[2];
Student[] myStudents = new Student[10];
The text recommends singular names.
I tend to use plural.
Array Sizes

Remember to declare constants for numbers
you use in multiple places
 like in array declaration and loop!
int[] nums = new int[NUM_ITEMS];
for (int i = 0; i < NUM_ITEMS; i++)
nums[i] = kbd.nextInt();

Makes it easy to change the number later
// # elements – change to 600 when debugged!
public static final int NUM_ITEMS = 6;
Arrays Know Their Own Length

Instance variable length
public static final int MAX_WORDS = 200;
…
String[] word = new String[MAX_WORDS];
if (word.length != MAX_WORDS) {
System.err.println(“Your computer is broken!”);
}
NOTE: it’s not a method; it’s a public instance variable
Creating Arrays with Values

Create an array object by listing elements
int[] arr = new int[]{2, 3, 5, 7, 11};

It knows its own length!
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + “ ”);
}
2 3 5 7 11

Can change the array later
arr = new int[]{13, 17, 19, 23};
Initialize.java
What Do We Use Arrays For?

Lists, mostly
 when we need to remember the earlier values
after we’ve read the later ones
» otherwise we can just use one variable in a loop

Example:
 read a list of numbers, calculate its average,
then say how different each number is from the
average
Average and Differences
// read and sum the numbers
int[] num = new int[NUM_ITEMS];
int sum = 0;
S.o.p(“Enter the ” + NUM_ITEMS + “ items below”);
for (int i = 0; i < NUM_ITEMS; i++) {
num[i] = kbd.nextInt();
// remember the #
sum += num[i];
// add it to sum
}
// calculate the average
double ave = (double)sum / (double)NUM_ITEMS;
// print the difference from the average of each
for (int i = 0; i < NUM_ITEMS; i++) {
S.o.p((num[i] – ave));
}
WeeklyTemps.java
Exercise

Declare this array of Strings:
word
“to”
“be”
“or”
“not”
“to”
“be”
 print it out on one line (with spaces between)
 DON’T COUNT THE WORDS!
Java Arrays Created at Run Time

Can ask the user how big to make an array
» can’t do that in C++
System.out.print(“How many students? ”);
int numStu = kbd.nextInt();
kbd.nextLine();
String[] name = new String[numStu];
System.out.println(“What are their names?”);
for (int s = 0; s < numStu; s++) {
name[s] = kbd.nextLine();
}
StudentNames.java
Array Lengths are Final

Can’t change the size of an array after you
create it(*)
int[] n = new int[10];
System.err.println(“Oops! Need it bigger!”);
n.length = 20;
// illegal

(*) But you can change the variable to point
to a new (larger) array!
int[] n = new int[10];
System.err.println(“Oops! Need it bigger!”);
n = new int[20];
// OK!
Bigger.java
But What About…
New, larger array is all zeroes!
 If you want to keep the old values, you need
to copy them into the new array

int[] num = new int[]{1,2,3,4,5};
int[] bigger = new int[2 * num.length];
for (int i = 0; i < num.length; i++) {
bigger[i] = num[i];
}
num = bigger; bigger
num
1 2 3 4 5
01 02 03 04 05 0 0 0 0 0
BetterBigger.java
Command Line Arguments

Remember how we declare main?
public static void main(String[] args)




never really explained String[] args
it’s an array of Strings...
...passed into your program...
...from the “command line”
prompt] java PrintArgs command line arguments
My 3 command line arguments were:
0: “command”
1: “line”
2: “arguments”
Command Line Arguments

Add words after the name of the class
prompt] java PrintArgs command line
My 2 command line arguments were:
0: “command”
1: “line”

They get passed to the program
» (unless they start with < or >, or ...)

Appear in the String[] parameter of main
 each word is a separate array element
NetBeans & the Command Line

File > Project Properties…
 or right-click on project name in Projects pane
Command Line Arguments

You can use args like any other array
 ask it its length
 loop thru its elements
 ask for some element
System.out.println(“My ” + args.length + “ arguments:”);
for (int i = 0; i < args.length; i++) {
System.out.println(i + “:\t\"” + args[i] + “\"”);
args }
My 2 arguments:
“command”
0: "command"
“line”
1: "line"
args is a String[]

OK to have a String[]
 can have an array of anything (pretty much)

Even if you type in numbers!
prompt] java PrintArgs 5 10
My 2 command line arguments were:
0: “5”
1: “10”
» you can use Integer.parseInt(args[i]) to get the
integer value of args[i]
see AddArgs.java
Arrays as Parameters
args is a String[] parameter for main
 Other methods can have [] parameters, too

 just declare the parameter to be an array!
public static int sumArray(int[] arr)

It’s just like any other parameter
 gets its value from the method call

It’s just like any other array
 it knows how long it is
Method to Sum an Array

Array comes from caller
int[] n = new int[]{2, 3, 5, 7, 11};
int addedUp = sumArray(n);

Method adds up its elements
public static int sumArray(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
ArrayMethod.java
Exercise

Write a method that receives an array of
words and prints them out one per line.

Write a method that receives an array of
doubles and returns the largest value in it
Returning Arrays

Methods can return arrays
 return type is an array type
public int[] dice(int howMany) { … }
public String[] wordsFrom(String line) { … }

The array to be returned is (usually) new
int[] result = new int[howMany];
for (int d = 0; d < howMany; ++d) {
result[i] = 1 + (int)(6 * Math.random());
}
return result;
ArrayReturn.java
Exercise

Make a method that returns a specified
number of copies of a word in an array
 for example:
String[] items = copies(6, "Hello");
items
“hello”
“hello”
“hello”
“hello”
“hello”
“hello”
Printing an Array

Can’t just use System.out.print:
int[] a = new int[]{1,2,3,4};
[I@1db9742
System.out.println(a);
 they don’t have a toString method of their own
 we can’t add one to them

Could write a method
 but we’d need lots of them…
 …and that’s such a pain.
The Arrays Class

java.util.Arrays has helper methods:
 toString method for arrays
int[] a = new int[]{1,2,3,4};
System.out.println(Arrays.toString(a)); [1, 2, 3, 4]
 works for any kind of array!
 needs to be imported

[1.0, 2.2]
[word1, word2]
java.util.Arrays also includes methods to
copy, search, fill, compare and sort arrays!
Sorting an Array
Just give the array to Arrays.sort
 It’ll come back sorted

int[] a = new int[]{4, 2, 7, 1, 9, 9, 4};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
[1, 2, 4, 4, 7, 9,
9]

Works for (almost) any kind of array
 works for Strings – sort of
» it’s not quite what you’d expect
ArraySorter.java
Modifying Arrays

Arrays can be modified by methods
int[] a = new int[] {1, 2, 3, 4};
doubleEachElement(a);
System.out.println(Arrays.toString(a)); [2, 4, 6, 8]

Just a normal method
public static void doubleEachElement(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
arr[i] *= 2;
}
}
ArrayDoubler.java
Reference Types

Variables in Java are references
» except primitive types like int, double, boolean, …
 they point to objects
int[] a = new int[]{1, 2, 3, 4};
Student s = new Student(“Jo”);
String word = “Hi!”;
a
1
2
3
4
&
s
&
A00000001
“Jo”
0
word
&
“Hi!”
Co-Reference

Two variables can refer to the same object
Car myCar = new Car(blue);
Car stevesCar = new Car(blue);
Car disCar = myCar;
disCar.setColor(green);
Car variables
// new Car
// new Car, same colour
// same Car as myCar
// myCar is now green
Car objects
myCar: &
disCar: &
stevesCar: &
disCar and myCar are not two
different cars. They’re two
different names for the same car.
Array (and Object) Parameters

Method call passes reference to object
 parameter points to same object as argument
 thus method can change the object
int[] a = new int[] {1, 2, 3, 4}; a
doubleEachElement(a);
21
&
…
42
public static void doubleEachElement(int[] arr) {
63
for (int i = 0; i < arr.length; ++i) {
84
arr[i] *= 2;
arr
}
&
}
ArrayDoubler.java
Doesn’t Work for Primitives

Method call passes actual value
 parameter has same value as argument
 thus method cannot change argument variable
int a = 3;
a
doubleValue(a);
3
…
public static void doubleValue(int n) {
n *= 2;
}
n
63
ArrayDoubler.java
Can’t Change Argument Variable

Method call passes reference to object
 parameter points to same object as argument
 but it’s NOT the same variable!
int[] a = new int[] {1, 2, 3, 4}; a
changeTheArray(a);
1
&
…
2
public static void changeTheArray(int[] arr) {
3
arr = int[] {5, 6, 7, 8};
5
4
}
6 arr
7 &
ArrayDoubler.java
8
Variable vs. Object

Usually think of them as the same thing
 but they’re not actually the same thing

Variable is used to refer to an object
 essentially a name we use for the object

The object is a separate thing
 it has the data in it
 it’s the one you talk to when you use the dot (.)
» but before the dot is the name we use for the object
Null References

A reference variable can refer to nothing
int[] a = null;
Student s = null;
String word = null;
 it’s not pointing at any object
 can make it point to an object later
a = new int[]{3, 4, 5};
a
&
/
s
/
word
/
3
4
5
Null Pointer Exception

Can’t talk to things that don’t exist
» Java won’t let you
 can’t use . with a null variable
» can’t use […] either
» program will crash
int[] a = null;
for (int i = 0; i < a.length; ++i) {
a[i] = (i + 1);
}
a
/
Exception in thread "main" java.lang.NullPointerException
Array Exceptions You Might See

ArrayIndexOutOfBoundsException
 you tried to get an array element …
 … but that element doesn’t exist

NullPointerException
 you tried to get an array element …
 … but that array doesn’t exist

When your program crashes, read the
message and try to understand it!
Questions