Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 20: Initializing and processing arrays of objects

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala

Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Initializing and processing arrays of objects


Java requires that all the elements within an array be of the same type. In the previous lesson, we constructed arrays in which all the elements were of the same primitive type (boolean, float, char, etc.).

In this lesson, we will construct arrays in which all the elements are of the same non-primitive, class type (such as String or StringBuffer). Such arrays are called object arrays.

Object arrays

  • Are declared with the class name as the type. For example,

String[] names = new String[5];

Constructs an array of 5 String object references. It is important to understand that no String objects are created by this declaration. We have simply created an array of null object references which may later be assigned to individual String objects (as shown by the following diagram).


Heap space







The statement

names[3] = new String("Hello World!");

would instantiate a String object and assign it to the fourth element in the names array (which would look like the following).


Heap space







"Hello World!"

To display the value of this particular String object, one might code


which retrieves the String object referenced by the fourth element in the names array.

  • Are arrays of object references. Each element is either the reference of an instantiated object or is null. The general syntax to access an instance method of the object being referenced is


For example, to determine the length of the encapsulated string in the fourth element of the names array one would code the expression


  • Can result in runtime errors if improperly used. In addition to an ArrayIndexOutOfBoundsException, it is possible for a NullPointerException to occur if an attempt is made to reference an object when the object reference is null.

Example: Attempting to call an instance method of an object that doesn't exist.

public class App {
public static void main(String[] args) {
String[] names = new String[5];
System.out.println("Length of first string: " + names[0].length());

  • Can be constructed from a value list. This requires the instantiation or the existence of the objects to be referenced by each array element. For example,

String aString = new String("def");
String[] x = {new String("abc"), aString, "xyz"};

creates a three element array of String object references. The first element references a String object having the value "abc", the second element references a String object having the value "def", and the third references the String object in the literal pool having the value "xyz".

Sample program

The following program allows a user to specify the number of elements and element values for an array of String objects where each object encapsulates a person's name. After all names have been entered, they are displayed in their original order. The array is then sorted into the alphabetical order of the names being referenced and the sorted list of names is displayed. The user is then asked if they want to do another array.

public class App {
public static void main(String[] args) {

// Loop control variable.

char again = 'y';

// Main loop. One array is entered and processed in each iteration.


while (again == 'Y' || again =='y') {

// Local variables for performing array processing.

String[] names;
int noElements;
boolean didSwap;
int sortPasses;

// Prompt for and read how many names the array is to contain.

Utility.separator(40, '=');
System.out.print("How many names will you enter? " );
noElements = Keyboard.readInt();

// If the number of elements is invalid, display an error message
// and continue the main loop from the beginning.

if (noElements <= 0) {
System.out.println(" Invalid number of elements");
continue another;

// Instantiate the array and loop to load its elements with values
// entered by the user.

names = new String[noElements];
for (int i = 0; i < noElements; i++) {
System.out.print("Element (" + i + "): ");
names[i] = Keyboard.readString();

// Display a message saying that loading is complete.

System.out.println(" Loading is complete.");
System.out.println(" The unsorted array contains:");

// Loop through the entire array to display the value of each
// element.

for (int i = 0; i < noElements; i++) {
System.out.println(" " + names[i]);

// Sort the array. This is accomplished by passing through the
// entire array comparing adjacent element values. If the second
// of the two elements should come first, they are swapped and an
// indicator set that specifies that a swap occurred. Additional
// passes are made until no swap occurs.

sortPasses = 0;
do {

// When a new pass begins, no swap has occurred.

didSwap = false;

// Loop through the entire array to compare adjacent elements.

for (int i = 0; i < names.length - 1; i++) {

// If the second of the two elements should come first,
// swap them and indicate that a swap occurred.

if (names[i + 1].compareTo(names[i]) < 0) {
String temp = names[i];
names[i] = names[i + 1];
names[i + 1] = temp;
didSwap = true;

// Increment the counter of the number of sort passes and
// continue looping as long as a swap occurred.

} while (didSwap);

// Display sort statistics.

System.out.println(" Sort required " + sortPasses + " pass(es).");
System.out.println(" The sorted array contains:");

// Display the sorted array's contents by looping through the
// entire array to display the value of each element.

for (int i = 0; i < noElements; i++) {
System.out.println(" " + names[i]);

// Ask the user if they want to do it again and repeat the loop as
// requested.

Utility.separator(40, '=');
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();

Note: There are many sorting techniques. The one shown here is not necessarily the best, but is fairly straightforward.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Which of the statements below are true after executing the following? (choose three)

String[] s = new String[10];

  1. s.length is 10

  2. s[0] is null

  3. s[0].length() is 0

  4. s[0] == s[1]

  5. s[0].equals(s[1])

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

String[] x = {"a", "bc", "def"};
if (x.length == x[2].length())
System.out.println("not equal");
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compiles and runs to display "equal"

  5. Compiles and runs to display "not equal"

  1. How many objects are created by the following statement?

StringBuffer[] zBuffers = new StringBuffer[10];

  1. none

  2. one

  3. ten

  4. eleven

  1. Assume that table is an array of String object references where no element is null (each element references an instantiated String object). Code a single statement to extract the first character of the first String object referenced by the array and assign it to a previously defined char variable named first.

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy