Working With Arrays


Arrays in Java are similar to C++ in their syntax, but are first-class objects with better security and more features. This Magercise shows some examples of array use.

Each of the tasks is intended to be an incrementental extension of the previous. After typing them into the scrapbook, execute them to examine their behavior. Note that you may use the VisualAge Inspector to inspect the arrays.

Additionally, you should know that some array operations can raise exceptions if errors occur, such as referencing an array past its boundary. There will be several Magercises later that cover exceptions in detail, but if you have the time, you may want to intentionally raise some to see what happens when they are not caught.

Arrays are discussed in detail in the course notes.

Tasks

Perform the following tasks:

  1. Starting with an empty Scrapbook page, define an array of strings called colors containing the values yellow, red, and blue. Then write the Java statements needed to print the length and contents of the array to the Console.

  2. Extend the example further by creating a new array, and initializing it with the contents of the colors array. Use either a for loop, as in C++, or System.arraycopy. To use arraycopy, refer to the API for System. Then visualize the array with the inspector by including a return statement.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.