Anda di halaman 1dari 8

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 with…arrays 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.

Let’s 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]; // array having 5 elements

seatwork = new int[7]; // 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:

Page 1 of 8 Prepared by: Lawrence G. Decamora III, scjp

int quiz[] = new int[5];
int seatwork = new int[7];

The Java programming language allows creation of arrays with initial values:

String name[] = // Array declaration

{“Lawrence”, // 1st element
“Dean”, // 2nd element
“Ella”, // 3rd element
“Michelle” }; // 4th element

This is equivalent to this:

String names[] =
new String ("Lawrence"),
new String ("Dean"),
new String ("Ella"),
new String ("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.

Let’s 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:

The value of intArray[ 0 ] = 0

The value of intArray[ 1 ] = 0
The value of intArray[ 2 ] = 0
The value of intArray[ 3 ] = 0
The value of intArray[ 4 ] = 0

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; //ILLEGAL initialization

num2 = num1; //ILLEGAL initialization!

Page 2 of 8 Prepared by: Lawrence G. Decamora III, scjp

if (num2 == num1) //DOES not work as expected
System.out.println(num1); //ILLEGAL extraction!
//output: [I@f7c3b4c1
num1 = num1 + 2; //ILLEGAL arithmetic

Array Limits

All arrays begin with index 0. Let’s take a look at this example:

String coffee[] =
“Mocha chino”};

“Barako” 0
“Espresso” 1 index
“Java” 2
“Mocha chino” 3

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.

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?

Page 3 of 8 Prepared by: Lawrence G. Decamora III, scjp

That’s 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:

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 for
loop created in the previous example can be rewritten this way:

21 String coffee[] =
22 {“Barako”,
23 “Espresso”,
24 “Java”,
25 “Mocha chino”};
27 System.out.println (“The coffee lovers choices are: “)
29 for (String c : coffee)
30 {
31 System.out.println (c);
32 }

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 public class ArrayExample3

2 {
3 public static void main(String args[])
4 {
5 int orig[] = {1, 2, 3, 4, 5};
6 int temp[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

Page 4 of 8 Prepared by: Lawrence G. Decamora III, scjp

7 System.arraycopy(orig, 0, temp, 0, orig.length);
8 orig = temp;
9 temp = null;
10 System.out.println("Printing the NEW orig array:");
11 for (int num : orig)
12 {
13 System.out.print(num + "\t");
14 }
15 }
16 }

Once compiled and run, you will have the following output:

Printing the NEW orig array:

1 2 3 4 5 5 4 3 2 1

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:

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 public class CommandLineArgs1

2 {
3 public static void main(String args[])
4 {
5 System.out.println(args[0]);
6 System.out.println(args[1]);
7 System.out.println(args[2]);
8 }
9 }

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 actually an element of the
args[] array, you just need to separate each String with a space. But if incase you would like to

Page 5 of 8 Prepared by: Lawrence G. Decamora III, scjp

include the space inside the String you can enclose the String with space with a pair of double
quotes. After execution, you will have the following output:

two two

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

The argument list are not dynamically accepted. So we can rewrite our code this way:

public class CommandLineArgs2

public static void main(String args[])
for (int i = 0; i < args.length; i++)

But with the use of the enhanced for loop, it can be rewritten this way as well.

public class CommandLineArgs3

public static void main(String args[])
for (String arg : args)

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 arguments 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?

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);

Page 6 of 8 Prepared by: Lawrence G. Decamora III, scjp

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];

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");

Page 7 of 8 Prepared by: Lawrence G. Decamora III, scjp

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] = new int [3]; // 1

irregularArray[1] = new int [5]; // 2
irregularArray[2] = new int [1]; // 3
irregularArray[3] = new int [4]; // 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.

0 1 2 3 4
0 0 0 0
1 0 0 0 0 0
2 0
3 0 0 0 0

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

Page 8 of 8 Prepared by: Lawrence G. Decamora III, scjp