Você está na página 1de 9

Chapter 5: Ouch! Arrays!

(3 hrs)
Chapter Objectives:
Discover what an array is and its use and importance.
Create, declare and initialize primitive and object reference arrays.
Introduce the length attribute for arrays in determining the number of elements in an array.
Introduce the enhanced for-loop capability of version 5.0
Create a rectangular and a non rectangular multi-dimensional array.
Write a code that copies an array value from one array to another.
Well, to start witharrays is a data structure in Java that is used to group common data
together. It is a homogeneous collection, which means that the data type of one element is the
same data type of the other elements. It has a fix size and once the size has been set, it cannot
be changed to accommodate other elements. There is also a heterogeneous array, but we will not
discuss heterogeneous arrays in this chapter, lets discuss that on the next chapter.
Lets say your instructor gave you five short quizzes for your midterms, instead of
declaring them as:
int quiz1, quiz2, quiz3, quiz4, quiz5;
You may want to declare them as:
int quiz[] = new int[5];
This means that you are declaring and creating an array of quizzes of type integer that
can have 5 integer values. Let s now determine the parts of the given array:
data type
int quiz[];
array name
Sometimes you might need more that one array. Consider this statement:
int quiz[], seatwork[];
This is also equivalent to:
int[] quiz, seatwork;
Once the [] notation follows the type, all variables in the declaration are arrays,
otherwise, the [] must follow after the variables. You can declare arrays of any type, either
primitive data type or of reference type. Arrays in Java are treated as objects therefore we can
construct our arrays by using the new keyword.
quiz = new int[5];
seatwork = new int[7];

// array having 5 elements


// array having 7 elements

You have now created an array of quizzes and an array of seatwork of type integer
having 5 and 7 elements respectively.
Array declaration and array creation is usually done in one statement:
int quiz[] = new int[5];
Page 1 of 9

Prepared by: Lawrence G. Decamora III, scjp

int seatwork = new int[7];


The Java programming language allows creation of arrays with initial values:
String name[] =
{Lawrence,
Dean,
Ella,
Michelle };

//
//
//
//
//

Array declaration
1st element
2nd element
3rd element
4th element

This is equivalent to this:


String names[] =
{
new String
new String
new String
new String
};

("Lawrence"),
("Dean"),
("Ella"),
("Michelle")

Upon the creation of arrays initial values are automatically assigned to them. Elements of
integral arrays are all set to zero. Boolean arrays are all set to false. And arrays of objects, such
as Strings, are all set to null.
Lets take a look at this example:
public class Array
{
public static void main(String[] args)
{
int intArray[] = new int [5];
for (int i = 0; i < intArray.length; i++)
System.out.println("The value of intArray[ "
+ i + " ] = " + intArray[i]);
}
}
As you take a look in line 1 an array of integer was created but there are no initial values
assigned to it. Nevertheless since it is an array of integral value zero will be assigned to each
element. As the code loop through the for loop body it will give us an output of:
Sample Output:
The
The
The
The
The

value
value
value
value
value

of
of
of
of
of

intArray[
intArray[
intArray[
intArray[
intArray[

0
1
2
3
4

]
]
]
]
]

=
=
=
=
=

0
0
0
0
0

Why did we have 0's as the values of the array intArray? It is because all arrays are
automatically initialized upon creation. The table below shows the initial value of the array
element after creation:

Page 2 of 9

Prepared by: Lawrence G. Decamora III, scjp

Array Data Type

Initial Values

byte, short, int

long

0L

float

0.0F

double

0.0

char

'\u0000'

boolean

false

Reference types (ie: String,


Account, Person etc)

null

Unlike the fundamental (atomic) types (char, int, float, double, etc.), arrays are
composites. It consists of several values. Consequently, many of the operations used on
fundamental types do not work as expected with arrays. Consider the following array operations:
int num2[ ] = num1;
num2 = num1;
if (num2 == num1)
System.out.println(num1);
num1 = num1 + 2;

//ILLEGAL initialization
//ILLEGAL initialization!
//DOES not work as expected
//ILLEGAL extraction!
//output: [I@f7c3b4c1
//ILLEGAL arithmetic

Array Limits
All arrays begin with index 0. Lets take a look at this example:
String coffee[] = {Barako,
Espresso,
Java,
Mocha chino};
coffee[]
Barako
Espresso
Java
Mocha chino

0
1
2
3

index

The index of array coffee[] starts with 0 and ends with 3. So if you want to access
Java, you would do it like this:
System.out.println (I love + coffee[2]);
This will give you an output like this:
I love Java
How about if you would like to access the last element of your array without you knowing
exact number of elements in your array? Since arrays in Java are objects, it has a length
attribute that returns the actual length of your array.

Page 3 of 9

Prepared by: Lawrence G. Decamora III, scjp

To access the last element of any array you can do it this way:
System.out.println (My last coffee for the day is
+ coffee[coffee.length-1]);
The output will be like this:
My last coffee for the day is Mocha chino
coffee.length returns the number of elements in array coffee which is 4.
Therefore, we need to use coffee.length-1 in order to access the last element of array
coffee, otherwise it will throw an ArrayIndexOutOfBoundsException. It means you are
attempting to access a subscript that is beyond the array bounds in this case beyond 0 to 3.
But how am I going to print all the elements of array coffee?
Thats easy. You can use a for loop or any type of loop to do it for you;
System.out.println (The coffee lovers choices are: )
for (int i = 0; i < coffee.length; i++)
{
System.out.println (coffee[i]);
}
The output would be like this:
The coffee lovers choices are:
Barako
Espresso
Java
Mocha chino
Using an integer variable i as an index, you can access all the elements of array
coffee from the first element until the last element (coffee.length-1).
Now, drink up!..
The Enhanced for loop
The enhanced for loop is new for version 5 also called as the for-each loop. The
enhanced for loop is primarily created for Collections, which is another data type. We will go
into Collections some other time, but for now our focus is arrays. The enhanced for loop can
be used for both Collections and arrays. As per which construct executes faster at runtime?
Well, its the enhanced for loop.
The noticable difference between the two is that in the traditional for loop, you can freely
access the control variable (usually its the variable i), but you do not have that in the enhanced
for loop. Secondly, by using the traditional for loop, you can iterate over the array (or over the
Collections) from the first element down to the last and vice versa. In the enhanced for loop
you could only iterate thru your Collections from the first element down to the last.
The for loop created in the previous example can be rewritten this way:
Page 4 of 9

Prepared by: Lawrence G. Decamora III, scjp

21
22
23
24
25
26
27
28
29
30
31
32

String coffee[] =
{Barako,
Espresso,
Java,
Mocha chino};
System.out.println (The coffee lovers choices are: )
for (String c : coffee)
{
System.out.println (c);
}

Copying Arrays
If you need to put the elements of one array to another array, there's a convenient
method for this. We can use the System.arraycopy() method. Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public class ArrayExample3


{
public static void main(String args[])
{
int orig[] = {1, 2, 3, 4, 5};
int temp[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
System.arraycopy(orig, 0, temp, 0, orig.length);
orig = temp;
temp = null;
System.out.println("Printing the NEW orig array:");
for (int num : orig)
{
System.out.print(num + "\t");
}
}
}
Once compiled and run, you will have the following output:
Printing the NEW orig array:
1
2
3
4
5

In line 7, System.arraycopy(orig, 0, temp, 0, orig.length); we need to


pass five parameters to the System.arraycopy() method.
The first parameter is the original method, followed by the starting point then the third one
is the destination array, the four argument is the starting point where you will start putting the
copied elements and the last argument is the number of elements to be copied.
Command Line Arguments
In your main method, you have the following method signature:

Page 5 of 9

Prepared by: Lawrence G. Decamora III, scjp

public static void main(String args[])


Some of you may ask, what is the String args[] for? It is actually Java's way to
accept inputs via command-line.
Consider this first example:
1
2
3
4
5
6
7
8
9

public class CommandLineArgs1


{
public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
}
}

After compiling it, you can run it by providing command line arguments like this:
java CommandLineArgs1 one two two three
The Strings that comes after the file name are command line arguments that are passed
to the main method's array of String parameter. And each String is an element of the args[]
array. You just need to separate each String with a space. But if incase you would like to
include the space inside the String you can enclose them with a pair of double quotes. After
execution, you will have the following output:
one
two two
three
What problem do you see in this example?
What if I would like to pass less than three arguments? Or say, pass more that three
arguments? Say...
java CommandLineArgs1 one two two three four five
You will have the same output. Your code is not that dynamic. It does not accommodate
other String values.
The argument list are not dynamically accepted. We need to rewrite our code this way:
public class CommandLineArgs2
{
public static void main(String args[])
{
for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
}
But with the use of the enhanced for loop, it can also be rewritten this way as well.
Page 6 of 9

Prepared by: Lawrence G. Decamora III, scjp

public class CommandLineArgs3


{
public static void main(String args[])
{
for (String arg : args)
{
System.out.println(arg);
}
}
}
But we must remember that when we pass arguments via command line, we are passing
String values, even if we pass integers or other data types. As a rule, all argument list passed
via command line are Strings.
So, let's say, we would like to pass integer values via command line and then compute for
the sum and the average of the integer parameters, how are we suppose to do this?
Consider this code for example:
public class CommandLineArgs4
{
public static void main(String args[])
{
int sum = 0;
for (String arg : args)
{
sum += Integer.parseInt(arg);
}
System.out.println("Sum: " + sum);
System.out.println("Ave: " + (double)sum / args.length);
}
}
When we compile and run this code with the following command line values, you will
have the following output:
java CommandLineArgs4 1 22 3 4 5 6 7
Sum: 48
Ave: 6.857142857142857
Two-dimensional Arrays
In Java, a two-dimensional array is also known as an array of array. You can have a
rectangular "normal" two-dimensional array or a non-rectangular array. Let's first take a look at
the "normal" two-dimensional array. Consider this example:
Object[][] objectArray = new Object[3][];
objectArray[0] = new Integer[2];
objectArray[1] = new Long[2];
objectArray[2] = new Double[2];
Page 7 of 9

Prepared by: Lawrence G. Decamora III, scjp

What happens here is that you have declared an array of arrays (two-dimensional array)
such that objectArray[0] is an array of object Integer, and objectArray[2] which is an
array of object Long and objectArray[3] is of type Double.
As we have discussed, an array is a homogeneous collection, but an array of arrays is
also a collection of homogeneous collection. Your objectArray[0] is a collection of Integer
objects so as objectArray[1] and objectArray[2] which are arrays of Long objects and
Double objects.
You can also create a two-dimensional array having one common data type (whether
primitive or reference) in all its column and row elements. Take a look at this example:
public class MultiplicationTable {
public static void main(String[] args) {
int mTable[][] = new int [5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
mTable[i][j] = (i + 1) * (j + 1);
System.out.print(mTable[i][j] + "\t");
}
System.out.println();
}
}

This is a sample of the multiplication table having 5 columns and 5 rows. As you notice,
all the data type in their columns and rows are of the same type. Here is its output once you
compile and run this:
1
2
3
4
5

2
4
6
8
10

3
6
9
12
15

4
8
12
16
20

5
10
15
20
25

Non-Rectangular Arrays
Since you are allowed to declare an array of arrays, you can also create non-rectangular
array of arrays. This means you can declare arrays this way.
int irregularArray[][] = new int [4][];
irregularArray[0]
irregularArray[1]
irregularArray[2]
irregularArray[3]

=
=
=
=

new
new
new
new

int
int
int
int

[3];
[5];
[1];
[4];

//
//
//
//

1
2
3
4

As you notice array irregularArray[0][] can only hold 3 integer values while array
irregularArray[1][] can hold up to 5 integer values. Even though it is a non-rectangular
array their respective default values will still be assigned upon creation.

Page 8 of 9

Prepared by: Lawrence G. Decamora III, scjp

0
1
2
3

used.

0
0
0
0
0

1
0
0

2
0
0

This type of array declaration is tedious that is why the rectangular array is commonly

Page 9 of 9

Prepared by: Lawrence G. Decamora III, scjp

Você também pode gostar