ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Arrays of Objects in Java

Updated on April 30, 2011

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());
		
		}
	}
}
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)