Arrays of Objects in Java

Arrays of Objects in Java

Object Oriented Programming (OOP) gives programmers tools to model concepts that exist in the 'real world'. We create classes with properties and methods, then we instantiate those classes to represent specific entities. Sometimes an real world concept is best represented as an array of objects. This tutorial explains some basic techniques for creating and manipulating arrays of objects.

First, we demonstrate techniques for declaring and initializing arrays of objects. Next, we present some sample code for manipulating those objects. Sample code is presented in the Java programing language, but these examples can easily be ported to other OOP languages as well. That exercise is left to the reader. Source code is provided for all the classes that are discussed.

We use Eclipse as our development platform
We use Eclipse as our development platform

Project Architecture

We use Eclipse as our development platform. In the interest of simplicity, we created a package called DemoPackage into which we placed all our classes. We created a class called Main to contain the entry point for the program.

We created another class called Student, which represents an individual student attending a college. This class is not intended to be complete or even adequate: it is simply a necessary component of this tutorial.

We could have tucked the Main( ) class into the Student class, but in our experience it improves understanding when the project entry point is easily located by anyone who wishes to study or maintain the project. Certainly an Eclipse project may have multiple entry points in multiple classes: our strategy does not preclude that.

Analysis of the Main class

As listed below, the Main class provides example code that exercises our Student class and demonstrates techniques for manipulating an array of objects.

Line 12: declare and instantiate an single object, named s, in order to have something to play with. We use the Student constructor to initialize the first and last name of the object.

Line 15: declare and initiate an array of Student objects. We arbitrarily assign the array a length of 5. Note that we have not yet put any objects into the array: we have only set aside space for 5 references to student objects.

Line 18: this line is commented out because it will cause a run-time error. In our experience this is a common error that frustrates many Java programmers. The array of Student objects contains placeholder for object references but those placeholders are not yet initialized. The references are null, implying that they cannot be used to refer to Student objects. We strongly suggest that students uncomment this line of code and execute the program to experience first-hand the error that occurs.

Line 20: assign the reference stored in s to the reference stored in sArray[0]. We provide this code to illustrate the difference between an object and a reference to an object. Refer to lines 25 through 27: note that the output of the program is the same for both lines 26 and 27. Both of these references refer to the same physical location in memory.

Lines 30-31: clobber the contents of the object referred to by the s reference. This also changes the object pointed to by sArray[0] because of what we did in line 21, above. Lines 34-36 illustrate this point by printing through both references again.

Lines 39-44: Initialize the entire array of objects, each with a new and unique reference. This loop uses the 'default' constructor defined in the Student class. Each object is instantiated, but the first name and last name strings are empty. In line, 42-43 we immediately initialize the first and last name fields with generic data. Note that the reference in sArray[0] no longer refers to the same object as s (see line 20, above), but the object referred to by s is still viable and has not been affected by this loop.

Lines 45-49: Print the contents of the objects referred to by the array. This logic simply 'proves' that we have 5 unique objects.

Arrays of Objects in Java
Arrays of Objects in Java

Conclusion

We have demonstrated basic techniques for manipulation of arrays of objects in Java.

Supplemental Work

Objects often occur in the real world as conceptual groupings that should be logically tied together in software as arrays. Other data structures can also be used to manipulate groups of objects. Collections, vectors, stacks, queues, and ArrayLists are potential candidates for grouping and manipulating objects. Java provides a rich set of data structures that can be adapted for these purposes.

The Student Class
The Student Class
The Main class
The Main class
The output of the program
The output of the program

Source Code for the Student Class

// (c) nicomp 2011
// Published on HubPages.com
package DemoPackage;

public class Student {
	private String lastName;
	private String firstName;
	
	// Constructor
	public Student (String lastName, String firstName){
		setLastName(lastName);
		setFirstName(firstName);
	}
	// Constructor
	public Student() {}
	
	// Public methods - 'getters' and 'setters'
	public String getLastName() {return lastName;}
	public String getFirstName() {return firstName;}
	public String setLastName(String lastName) {this.lastName = lastName; return lastName;}
	public String setFirstName(String firstName) {this.firstName = firstName; return firstName;}

	// toString
	public String toString(){
		return(lastName + ", " + firstName);
	}
	
}

Source code for the Main class

// (c) nicomp 2011
// Published on HubPages.com
package DemoPackage;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Declare and instantiate a single student object
		Student s = new Student("Cheaney", "Calbert");
		
		// Declare and instantiate an array of Student objects
		Student sArray[] = new Student[5];
		
		// This will cause a run-time error. sArray[0] has not been instantiated
		//sArray[0].setFirstName("Damon");	

		// store the reference to s into the first element of the array
		sArray[0] = s;
		
//		============================================================		
		// Use sArray[0] and s to print the object
		System.out.println("Accessing the same object two different ways...");
		System.out.println("Student = " + s.toString());
		System.out.println("Student = " + sArray[0].toString());		
	
		// Change the object using s, then print it again
		s.setFirstName("Todd");
		s.setLastName("Leary");
		
		// Print it again
		System.out.println("After the change...");
		System.out.println("Student = " + s.toString());
		System.out.println("Student = " + sArray[0].toString());		
//		============================================================		

//		Use a loop to initialize the array of objects: each array element will be a unique reference
		for (int i = 0; i < sArray.length; i++) {
			sArray[i] = new Student();
			sArray[i].setFirstName("Student " + i + " first name");
			sArray[i].setLastName("Student " + i + " last name");
		}
//		Print out the array of objects just make sure it works
		for (int i = 0; i < sArray.length; i++) {
			System.out.println(i + ": " + sArray[i].toString());
		
		}
	}
}

More by this Author


Comments 3 comments

psychicdog.net profile image

psychicdog.net 5 years ago

Interesting...I've been thinking about learning Java - b/c it's the program that runs Android apps so worth doing if you want to make an app. Thanks for the OOPsy info.


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@psychicdog.net : me too. We had an Open House last week where I teach and a prospective student said the same thing.


sparkster profile image

sparkster 5 years ago from United Kingdom

Very informative, I've also been looking into learning Java in order to develop Android apps.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working