You are on page 1of 16

CS 335 Lecture 04

Java Programming – Arrays

Fall 2003
Arrays in Java

z Indexes start at 0
z All data types (primitive and user-defined
objects) can be put into arrays
z Any expression which evaluates to an integer
can be used as the array subscript
z Arrays can be re-allocated to change the
size; they are static once created
Declaring Arrays

z Arrays must be both declared and allocated


(using the new command):

int
int myarray[]
myarray[] == new
new int
int [100]
[100]

int
int myarray[];
myarray[];
myarray
myarray == new
new int[100];
int[100];
Example Declarations

byte bytearray[] = new byte [255]


char chararray[] = new char [255]
MyObj ObjArray[];
ObjArray = new MyObj[10]
byte [] array1, array2;
array1 = new byte[100];
array2 = new byte[200];
Allocating Arrays

z Must allocate with the new command


– null pointer exception!!
z Fixed size after allocation
z The allocated size can be dynamically
determined with an expression:
char
char chararray[];
chararray[];
...
...
chararray
chararray == new
new char
char [size*6];
[size*6];
Dynamic Arrays

z Re-allocation possible:
char myarray[] = new char [255];
char tmparray[] = new char [255];
...
for (int i=0; i<myarray.length; i++)
tmparray[i]= myarray[i];
myarray = new char[255*2];
for (int i=0; i<255; i++)
myarray[i]= tmparray[i];
//
// Fig.
Fig. 7.4:
7.4: InitArray.java
InitArray.java
//
// initializing
initializing anan array
array with
with aa declaration
declaration
import javax.swing.*;
import javax.swing.*;

public
public class
class InitArray
InitArray {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
String
String output
output == "";"";
//
// Initializer
Initializer list
list specifies
specifies number
number ofof elements
elements and
and
// value for each element.
// value for each element.
int
int n[]
n[] == {{ 32,
32, 27,
27, 64,
64, 18,
18, 95,
95, 14,
14, 90,
90, 70,
70, 60,
60, 37
37 };
};

output
output +=
+= "Subscript\tValue\n";
"Subscript\tValue\n";

for
for (( int
int ii == 0;
0; ii << n.length;
n.length; i++i++ ))
output
output += += ii ++ "\t"
"\t" ++ n[
n[ ii ]] ++ "\n";
"\n";

JTextArea
JTextArea outputArea
outputArea == new
new JTextArea(
JTextArea( 11,
11, 10
10 );
);
outputArea.setText(
outputArea.setText( output
output ); );

JOptionPane.showMessageDialog(
JOptionPane.showMessageDialog( null,
null, outputArea,
outputArea,
"Initializing an Array with a Declaration",
"Initializing an Array with a Declaration",
JOptionPane.INFORMATION_MESSAGE
JOptionPane.INFORMATION_MESSAGE );
);

System.exit(
System.exit( 00 );
); }}
}}
//
// Fig.
Fig. 7.5:
7.5: InitArray.java
InitArray.java
//
// initialize array
initialize array nn to
to the
the even
even integers
integers from
from 22 to
to 20
20
import javax.swing.*;
import javax.swing.*;
public
public class
class InitArray
InitArray {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
final
final int
int ARRAY_SIZE
ARRAY_SIZE == 10;
10;
int n[];
int n[]; //
// reference
reference to
to int
int array
array
String output = "";
String output = "";
nn == new
new int[
int[ ARRAY_SIZE
ARRAY_SIZE ]; ]; //
// allocate
allocate array
array
// Set the values in the
// Set the values in the array array
for
for (( int
int ii == 0;0; ii << n.length;
n.length; i++
i++ ))
n[
n[ ii ]] == 22 ++ 22 ** i;
i;
output
output +=
+= "Subscript\tValue\n";
"Subscript\tValue\n";
for
for (( int
int ii == 0;
0; ii << n.length;
n.length; i++i++ ))
output
output += += ii ++ "\t"
"\t" ++ n[
n[ ii ]] ++ "\n";
"\n";
JTextArea
JTextArea outputArea
outputArea == new
new JTextArea(
JTextArea( 11,
11, 10
10 );
);
outputArea.setText( output
outputArea.setText( output ); );

JOptionPane.showMessageDialog(
JOptionPane.showMessageDialog( null,
null, outputArea,
outputArea,
"Initializing
"Initializing to Even Numbers from 22 to
to Even Numbers from to 20",
20",
JOptionPane.INFORMATION_MESSAGE );
JOptionPane.INFORMATION_MESSAGE );
System.exit(
System.exit( 00 );
); }}
}}
//
// Fig.
Fig. 7.8:
7.8: Histogram.java
Histogram.java
//
// Histogram printing program
Histogram printing program
import javax.swing.*;
import javax.swing.*;
public
public class
class Histogram
Histogram {{
public
public static
static void
void main(
main( String
String args[]
args[] ))
{{
int
int n[]
n[] == {{ 19,
19, 3,
3, 15,
15, 7,
7, 11,
11, 9,
9, 13,
13, 5,
5, 17,
17, 11 };
};
String output =
String output = ""; "";

output
output +=
+= "Element\tValue\tHistogram";
"Element\tValue\tHistogram";
for
for (( int
int ii == 0;
0; ii << n.length;
n.length; i++
i++ )) {{
output
output += += "\n"
"\n" ++ ii ++ "\t"
"\t" ++ n[
n[ ii ]] ++ "\t";
"\t";
for
for (( int
int jj == 1;
1; jj <=
<= n[
n[ ii ];
]; j++
j++ )) //
// print
print aa bar
bar
output += "*";
output += "*";
}}

JTextArea
JTextArea outputArea
outputArea == new
new JTextArea(
JTextArea( 11,
11, 30
30 );
);
outputArea.setText( output
outputArea.setText( output ); );

JOptionPane.showMessageDialog(
JOptionPane.showMessageDialog( null,
null, outputArea,
outputArea,
"Histogram Printing Program",
"Histogram Printing Program",
JOptionPane.INFORMATION_MESSAGE
JOptionPane.INFORMATION_MESSAGE );
);
System.exit(
System.exit( 00 );
);
}}
}}
Arrays as Parameters

z Java treats arrays as objects. When the


actual parameter is an array, it is passed to
the method by reference:
int a[] = { 1, 2, 3, 4, 5};
...
modifyArray ( a );
...
public void modifyArray (int b[]) {
...
}
Arrays as Parameters

z When elements in an array are primitive data


types, the elements can be passed by value:

int
int a[]
a[] == {{ 1,
1, 2,
2, 3,
3, 4,
4, 5};
5};
...
...
modifyElement
modifyElement (( a[4]
a[4] );
);
...
...
public
public void
void modifyElement
modifyElement (int
(int elem)
elem) {{
...
...
}}
Example: Binary Search
//
// Binary
Binary search
search
public
public int binarySearch(
int binarySearch( int
int array[],
array[], int
int key
key ))
{{
int
int low
low == 0;
0; //
// low
low subscript
subscript
int
int high = array.length - 1; // high subscript
high = array.length - 1; // high subscript
int middle;
int middle; //
// middle subscript
middle subscript
while
while (( low
low <=
<= high
high )) {{
middle
middle == (( low
low ++ high
high )) // 2;
2;
if
if (( key
key ==
== array[
array[ middle
middle ]] )) //
// match
match
return middle;
return middle;
else
else ifif (( key
key << array[
array[ middle
middle ]] ))
high
high == middle
middle -- 1;
1; //// search
search low
low end
end of
of array
array
else
else
low
low == middle
middle ++ 1;1; // // search
search high
high end
end of
of array
array
}}

return
return -1;
-1; //
// searchKey
searchKey not
not found
found
}}
Multi-Dimensional Arrays

z Java supports single arrays whose elements


are also single arrays, thus achieving the
effect of double-subscripted arrays:

int
int my2darray[][]
my2darray[][] == {{ {1,
{1, 2},
2}, {3,
{3, 4}};
4}};
……
exprResult
exprResult == my2darray[0][0]*my2darray[1][0];
my2darray[0][0]*my2darray[1][0];
Multi-Dimensional Arrays

z Arrays of objects must have each slot


allocated with the new command:
int
int b[][];
b[][];
bb == new
new int
int [4][6];
[4][6];
……
JButton
JButton board[][];
board[][];
board
board == new
new Jbutton[4][6];
Jbutton[4][6];
……
for
for (int
(int ii == 0;
0; ii << board.length;
board.length; i++)
i++)
for
for (int
(int jj == 0;
0; jj << board[i].length;
board[i].length; j++)
j++)
board[i][j]
board[i][j] == new new JButton();
JButton();
Example Game: “Memory”

z Basic constructs: arrays, buttons, objects


z Simple GUI http://www.lizardpoint.com/fun/java/conc/Memory.html

You might also like