8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
1/254
Introduction to Java
for OO Developers(Course Code JA311)
Student Exercises SDKERC 1.3
IBM Certified Course Material
.
over
Front cover
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
2/254
Student Exercises
January 2004 Edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an as is basis without
any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer
responsibility and depends on the customers ability to evaluate and integrate them into the customers operational environment. While
each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will
result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
Copyright International Business Machines Corporation 2002, 2004. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission of IBM.
Note to U.S. Government Users Documentation related to restricted rights Use, duplication or disclosure is subject to restrictions
set forth in GSA ADP Schedule Contract with IBM Corp.
Trademarks
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMSOS/390 Rational VisualAge WebSphere
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
3/254
Introduction to Java
for OO Developers(Course Code JA311)
Student Exercises WSADERC 1.3
IBM Certified Course Material
.
over
Front cover
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
4/254
Student Exercises
January 2004 Edition
The information contained in this document has not been submitted to any formal IBM test and is distributed on an as is basis without
any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer
responsibility and depends on the customers ability to evaluate and integrate them into the customers operational environment. While
each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will
result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
Copyright International Business Machines Corporation 2002, 2004. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission of IBM.
Note to U.S. Government Users Documentation related to restricted rights Use, duplication or disclosure is subject to restrictions
set forth in GSA ADP Schedule Contract with IBM Corp.
Trademarks
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase
DB2 Everyplace IMSOS/390 Rational VisualAge WebSphere
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
5/254
Student Exercises
.
OC
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Contents iii
Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Case Study Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Exercise 1. Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
Exercise 2. Java Language Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
Exercise 3. Using Existing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
Exercise 4. Creating Your Own Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1
Exercise 5. Class Methods and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1
Exercise 6. Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
Exercise 7. Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1
Exercise 8. Simple I/O and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
6/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
iv Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
7/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Trademarks v
. .
SGp Trademarks
The reader should recognize that the following terms, which appear in the content of this
training document, are official trademarks of IBM or other companies:
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the
United States, other countries, or both.
Pentium is a trademark of Intel Corporation in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Linux is a registered trademark of Linus Torvalds in the United States and other countries.
Other company, product and service names may be trademarks or service marks of others.
AIX CICS ClearCase DB2 Everyplace IMSOS/390 Rational VisualAge WebSphere
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
8/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
vi Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
9/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Case Study Description vii
.
ef Case Study Description
Certification Unlimited Partnership (CUP) would like to develop a Web-based application
for their Distant Exam Delivery System (DEDS). Currently CUP has many certification
exams for computing professionals to take to be CUP-certified in various fields of study.
Currently to become certified, a test taker (customer) must travel to a designated CUP
testing site and take a written, paper-based, certification test. This test must then be scored
and the results communicated back to the customer.
CUP would like DEDS to be able to allow their customers to complete their certification
exams via the Web. This system should allow people to register to become customers for
the service and allow them to update their profile. A customer would be allowed to select a
specific exam to take (after signing in to the system). Upon completion of the exam, the
results will be graded, and a score report will be delivered to the customer immediately.
Statistics on exam takers and their scores are kept for the purposes of verification,
reporting, exam effectiveness analysis, and so forth.
The generated exam will be a random collection of questions pulled from the selected tests'
pool of questions. Questions are categorized into test categories. This permits the random
generation of exams which all are representative of all major areas of coverage of a test.
Further, exam score reports provide grades on the questions within each category
(subscores) to help a candidate better understand their areas of strengths and
weaknesses.
The system needs to be built to manage customer, test and exam data. In particular,
customer data will include registration, exam transcripts and certification completion
information. Test data will include question and answer pools for both production exams
and exams under review.
Customers register with the system to specify a unique user name and password. They will
log in to take exams or to review their status (certification completion). Customers can also
obtain a transcript of previously taken exams (with scores).
Test developers should also be able to submit new tests and/or questions for review as well
as be able to perform maintenance on existing tests and questions.
CUP also needs a way for Subject Matter Experts (SMEs) to take the complete review
exam and add comments on each question.
Administration staff need to perform a series of analysis tasks including Customer analysis(for example, demographics, progress toward certification, and so forth), Test analysis (for
example, performance measures on questions, sub score areas, and tests); test
maintenance (for example, promoting reviewed exams to production and fixing questions);
and interaction with other systems (for example, publishing reviewed exams to an external
testing service).
CUP would like this system to enhance their customer service and also integrate their
various business processes (test creation, test review, exam delivery, exam scoring,
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
10/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
viii Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
customer record management, customer analysis, test analysis, and test maintenance).
The DEDS system should also be flexible to support future business processes associated
with their certification exam business.
End of Case Study
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
11/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-1
.
Xempty Exercise 1. Hello World
What This Exercise Is About
This exercise is intended to introduce you to Java. You may already
have a background in procedural programming. This exercise willshow you some aspects of the new language on familiar territory. You
will enter source code into a file, compile it, and execute it using the
javac.execompiler and thejava.exevirtual machine.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Write Java source code using Windows Notepad as an editor
Use javac.exe to compile the source code to bytecode
Use java.exe to run the bytecode
Learning Strategy
Individual exercise
Required Materials
Sun J2SE SDK 1.4.2
Windows Notepad or equivalent
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
12/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
You have heard about the compiler and JVM. You're familiar with COBOL, PL/I or some
other procedural language. This exercise introduces you to Java by having you write,
compile, and run a short procedural Java program.
Directions
Any text editor will work for this exercise. These instructions refer to Windows Notepad
when a text editor is being referenced. You will use a text editor to write a simple Java
program. You will compile the program using the javac command from the SDK. The java
command will run the program.
Step A: Write the Source Code
1. Create directories C:\OOPwJava\lab1 if they dont already exist.
2. Create a new source file in Notepad.
a. Open Notepad by selecting Start -> Run...from the task bar.
b. Typenotepadin the Open:field of the Run dialog, and click OK.
3. Create a new public class, HelloWorld, with a main method. The main method should
output the string Hello, World!.
a. Enter the following source code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
4. Save the file as c:\OOPwJava\lab1\HelloWorld.java.
Step B: Compile the Source Code
1. Open a command window.
a. Select Start -> Run...from the task bar.
b. Type cmdin the Open: field of theRundialog, and click OK.
2. In the new cmdwindow, enter the command cd c:\OOPwJava\lab1.
3. Type javac HelloWorld.javain the cmdwindow to compile the source code.
4. If there are any syntax errors, fix them in your HelloWorld.java source file and recompile
the program.
5. Type dirto see the files in this directory. You should see two:
a. HelloWorld.javais the source file you edited above.
b. HelloWorld.classis the byte code for the HelloWorld class.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
13/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 1. Hello World 1-3
.
Xempty Step C: Execute the Result
1. Enter java HelloWorldto execute the bytecodes of the class in a new JVM.
a. You should see the text Hello, World!displayed in the cmdwindow.
b. If there are any run time errors you will need to fix them, recompile, and then rerun
your program.
c. You can now close the cmd window by typing exit.
Summary
You have written, compiled, and run a simple procedural Java program using a text editor
and the SDK. Writing and executing a Hello World program is the traditional introduction
into many languages. Java is an object-oriented language. You wrote a short procedural
program, but it had to exist within a class. When you learn Java language syntax, you will
create your own classes and begin to compose object-oriented programs.
END OF LAB
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
14/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
1-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Sample Output
Hello, World!
Reference Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
File: HelloWord.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
15/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-1
.
Xempty Exercise 2. Java Language Syntax
What This Exercise Is About
This exercise gives you practice using the non-OO, or procedural, side
of Java. You will code all of this exercise in a single main() method of aDriver class.
In this exercise you will also be introduced to working within the
WebSphere Studio Application Developer environment. For the
purposes of this, and future exercises, we will be using WebSphere
Studio Application Developer as a compiler, editor and execution
environment (you will no longer use the Notepad, javac and java
commands).
What You Should Be Able to DoAt the end of the lab, you should be able to:
Use some primitive data types and statements addressed in Java
Use the commonly used operators addressed in Java
Write a simple Java program
Required Materials
Individual exercise
The exercise requires WebSphere Studio Application Developer,
Version 5.1
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
16/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
Throughout this exercise (and future exercises) we will refer to WebSphere Studio
Application Developer as Application Developer. You will create an Application Developer
project for this exercise that will be reused throughout the rest of the exercises for this
course. Within that project you will create a Java package. The package is only used here
as a container used to distinguish your single driver class from other possible classes ofthe same name. The directions will instruct you as to how to create the package.
You will create a Java class called Driver that will hold a single public static void
main(String[ ]) method. All of the executable code for this exercise will be put in the main()
method. The main() method will create and use an array of test scores for which some
statistics will be computed. You will create this array and code the arithmetic mean and the
standard deviation of these scores, displaying the values on the console.
You will need to create an array of doubles. The reference to the array will be called
testScores. You will access the elements in the array with a looping construct and
conditional statements. The four fundamental arithmetic operators will need to be used.
Strings and the concatenation operator will aid you in creating the display data.
Directions
Step A: Create the Project, Package, Driver Class, and Main Method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Startmenu and then select Programs -> IBM WebSphere
Studio -> Application Developer.
b. You may receive a dialog box requesting you enter a directory called a workspace
for the current session. Application Developer stores your work in a workspace. You
can change the workspace each time you start Application Developer, or specify a
directory and check the box in the dialog box to Use this workspace as the
default and do not show this dialog box again. If you receive this dialog box,
note the default workspace location and accept it as your workspace. If you check
the box in the dialog box, you will not see this message during startup again.
2. The default perspective used by Application Developer is determined at installation time
but can be customized at run time. If no other option is selected the default perspectiveis the J2EE perspective. Most of your time this week will be in the Java perspective. If
needed, use the Preferences dialog to update your Application Developer system to
make the Java perspective the default perspective.
a. Open up the Preferencesdialog by selecting menu item Window -> Preferences.
b. Expand the Workbenchtree and select Perspectives.
c. Notice which entry in the Availableperspectiveslist is the default.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
17/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-3
.
Xempty d. If the default is not the Javaperspective, select the Javaperspective from the list
and click MakeDefault.
e. Click OKto close the Preferencesdialog.
3. If needed, switch to the Javaperspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window->Open Perspective->Java. This will open up the Java perspective and switch to it.
4. From the Java perspective create a new java project with a project name of OO
Programming with Java.
a. Use the Create a Java Project toolbar button to open up the New Java Project
wizard.
b. Fill in a project name of OO Programming with Java. Use the default location for
project contents.
c. Click Finish to create the new project.
d. Notice that your Package Explorer view now contains the OO Programming withJavaproject.
5. Create a new package,lab2, in the OO Programming with Javaproject and create a
new class Driver.This new class should extend java.lang.Object and have a main
method.
a. Select theOO Programming with Javaproject from the Package Explorer and
click the Create a Java Package toolbar button to open up the New Java Package
wizard. Make sure the Source Folder field is OO Programming with Javaand type
in a Name value of lab2.
b. Click Finishto create the lab2package.c. Select package lab2in theOO Programming with Javaproject from the Package
Explorerand click the Create a Java Class toolbar button to open up the New
JavaClass wizard. Notice that the Source Folder and Package values have already
been filled in with the project directory and package names. Update the New Java
Class dialogto make sure the class Name is Driver, Modifiers arepublic, and
Superclass is java.lang.Object.
d. Also ensure that the check box labeled public static void main(String[] args)is
selected (checked). This option tells Application Developer to create a stub main
method in your new class.
e. Make sure that the Constructors from superclasscheck box is not selected. Sinceour Driver class is just a procedural program, we do not need constructors defined
for this class.
f. Make sure that the Inherited abstract methodscheck box is not selected. It adds
class stubs of any abstract methods from superclasses or methods of interfaces that
need to be implemented.
g. Click Finishto have the wizard create the newDriverclass in package lab2 in
project OO Programming with Java.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
18/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step B: Create the Data
1. When you created the Driverclass, the Java editorwas opened on the new class in
the center of the Javaperspective. The Outlineview shows you the package
statement, import statements, fields, and methods that exist in your class. If you select
a field or method in the Outlineview the Java editorwill scroll to that method. Select
the mainmethod in the Outlineview and notice that the highlighted area in the Java
editorwindow is updated to indicate the scope of the main method.
Information:If the Outlineview is not displayed or if it gets closed you can open it by
using the menu option Window -> Show View -> Outline.
2. Edit the mainmethod and have it define the data that is necessary for testing. You will
need an array, testScores, that you need to initialize to a set of test score values. You
will also need an int, testCount, set to the size of the testScores array. You will need
two double variables, totalScoreand meanScore. Finally, you will need an int, index.
These variables should all be defined at the top of your main method. After typing in
your code, you can right click anywhere in the Java editorand select Source ->
Format to organize your new code.
a. The main method should have been created for you when the class was created. If
the main method does not exist you can create it by typing it into the editor. The
main method should look as follows:
public static void main(String[] args) {
}
b. Select the main method and edit the main method so it definestestScoresas a
reference to an array of doubles, an int testCountinitialized to the length of thetestScores, totalScoreand meanScorevariables of type double, and an int
index.
Our solution follows:
double[] testScores = { 16.0, 22.0, 24.0, 24.0, 27.0,
28.0, 29.0, 30.0 };
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
double meanScore = 0.0;
int index;
Step C: Compute and Display the Arithmetic Mean of the Scores
1. In the main method, after you have declared your variables, sum the scores stored in
the array, testScores, and then divide by the number of scores. Store the arithmetic
mean in the variable meanScore.
a. Our solution follows:
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
19/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 2. Java Language Syntax 2-5
.
Xempty // Compute the mean (arithmetic average) test score
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
2. Next, display the mean along with simple explanatory text. Use
System.out.println(String)to display text on the console.
a. Our solution follows:
System.out.println("The arithmetic mean is " + meanScore);
Note: The that the "+" operator is the concatenation operator for Strings.
Step D: Compute and Display the Standard Deviation of the Scores
1. As you update your main method, add your new code at the bottom of the main method
after the code you added in the steps above. For each score, compute the square of its
difference from the mean. Sum these terms in a variable. Don't worry about the sign ofthe difference. The squaring operation will make all terms positive.
a. Our solution follows:
double sum = 0.0;
for (index = 0; index < testCount; index++) {
// Compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;
// Accumulate its square
double distFromMeanSquared = distFromMean * distFromMean;
sum += distFromMeanSquared;}
2. Compute the arithmetic mean of the sum.
a. Our solution is as follows:
double meanOfSquares = sum / testCount;
3. Take the square root of the result to obtain the standard deviation. Use the
Math.sqrt(aDouble)function.
a. Our solution is as follows:
double stdDeviation = Math.sqrt(meanOfSquares);
4. Display the standard deviation along with explanatory text.
a. Our solution is as follows:
System.out.println("The standard deviation is " +
stdDeviation);
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
20/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
5. Save your main() method by either clicking Ctrl+sor by using the right mouse button in
the Java editorand selectingSave(it is towards the bottom of the list).
Step E: Test the Program
1. Verify that your class and method have no syntax errors.
a. Verify that the Driver class has no X in front of it. If it has a red X, something is
incorrect in the class declaration or in the main method. If there are errors they will
be displayed at the bottom of the Java perspective in the Tasksview. If you do not
see the Tasksview you can select Window -> Show View -> Tasks.
b. If you double-click an error in the Tasksview the Driverclass will scroll to the line
that contains the error.
2. Run the Driverclass.
a. Select the class Driver class from thePackage Explorer and click the Runtoolbar
button. The first time you run your Driver class the Launch Configurationsdialog
will open up. Select Java Applicationfrom the Launch configurations list and
click New.
b. The Driver class should be the only class listed in the Launch Configurations
dialog. Click Runto run the Driver class. Notice that the Console view will show the
output from your application. If you double-click the title area of the Console view it
will expand to fill the entire Application Developer window. Double-click again the
Console title area to restore it to its previous size
3. Application Developer can be configured to switch over to the Debugperspective.
Select Window-> Preferencesand select Debug. Verify that the Default perspective
for Runis set to Debug, then run the Driverclass again.
4. You can use the shortcut bar (toward the top on the left of the main Application
Developer window) to switch between perspectives. More information about workbench
fundamentals can be found in the Navigating the workbench under Help -> Help
Contents -> Application developer information->Getting Started -> Tutorial:
Workbench basics.
Summary
Your two display statements should display the mean and standard deviation, respectively.
If you use the test score values shown in the hints in step B, you should get a mean of 25.0,and a standard deviation of 4.2720 (your result may have more digits of output).
You used arithmetic, assignment, and concatenation operators in this exercise. You
initialized an array of literal primitive double values and then accessed the array to perform
computations on its contents. You coded two loops to carry this out. You used a Math
method and a System print method without understanding their meaning. You will learn
these things later. You placed your class in a package without understanding Java
packages. You will learn this later as well.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
21/254
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
22/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Code:
package lab2;
public class Driver {
public static void main(String[] args) { double[] testScores = {16.0, 22.0, 24.0, 24.0, 27.0,
28.0, 29.0, 30.0};
int testCount = testScores.length; // number of scores
double totalScore = 0.0;
double meanScore = 0.0;
int index;
for (index = 0; index < testCount; index++) {
totalScore = totalScore + testScores[index];
}
meanScore = totalScore / testCount;
System.out.println("The arithmetic mean is " + meanScore);
double sum = 0.0;
for (index = 0; index < testCount ; index++) {
// compute each score's difference from the mean
double distFromMean = testScores[index] - meanScore;
// Accumulate its square double distFromMeanSquared = distFromMean * distFromMean;
sum += distFromMeanSquared;
}
double meanOfSquares = sum / testCount;
double stdDeviation = Math.sqrt(meanOfSquares);
System.out.println("The standard deviation is " +
stdDeviation); }
}
Driver.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
23/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-1
.
Xempty Exercise 3. Using Existing Classes
What This Exercise Is About
Java comes with many classes already defined. This exercise
introduces you to some of those classes. You will learn how to usethem and, by extension, other classes defined in Java.
What You Should Be Able to Do
At the end of the lab, you should be able to:
Instantiate objects
Send messages to objects
Receive return values from message sends
Use the main features of the String and Vector classes
Required Materials
WebSphere Studio Application Developer, Version 5.1
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
24/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Exercise Instructions
You will use your existing OO Programming with Javaproject for this exercise. Within the
project you will create a Java package called lab3.
You will create a class called Driverthat will define a public static void main(String[])
method. All the executable code that you will write in this exercise will be within this main()
method.
In the scenario for this exercise you will:
Accept test statistics (corresponding name and score pairs) from the command line.
Validate number of parameters passed in.
Parse and store each parameter in a vector.
Find the high and low score.
Print the name and score pair that corresponds to the high and low scores.
Directions
Step A: Create the package, driver class, and main method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Startmenu and then select Programs -> IBM WebSphere
Studio -> Application Developer.
2. If needed, switch to the Javaperspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window->Open Perspective ->Java. This will open up the Java perspective and switch to it.
3. Close any old edit windows.
a. Menu File -> Close All.
4. Create a new class Driverin a new package named lab3within the existing OO
Programming with Javaproject. The new Driverclass needs a main method.
a. Select the OO Programming with Javaproject from the Package Explorer.
b. Use the Create a Java Class toolbar button to open up theNew Java Class dialog.
c. Notice that the Source Folder field contains the directory for the OO Programming
with Java project.
d. Fill in a Package value of lab3. Since this package does not exist, the New Java
Classwizard will create it for you.
e. Update the New Java Class dialogto make sure the class Name is Driver, the
Modifiers are public, and Superclass is java.lang.Object.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
25/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-3
.
Xempty f. Also ensure that the check box labeled public static void main(String[] args)is
selected. This option tells Application Developer to create a stub main method in
your new class.
g. Make sure that the Constructors from superclasscheck box is not selected.
h. Make sure that the Inherited abstract methodscheck box is not selected.
i. Click Finishto have the wizard create the newDriverclass in package lab3 in
project OO Programming with Java.
Step B: Validate the command-line arguments
1. Make sure your new Driver class has a main method. If it doesnt you need to create a
new main method.
a. The main method should have been created for you in the Javaeditorwhen the
class was created. If the main method does not exist you can create it by typing it
into the Java editor. The main method should look as follows:
public static void main(String[] args) {}
2. Update the main method. If there are no command-line arguments detected, display an
explanatory message that the arguments should be name/score pairs and then exit.
The command line arguments are passed in via the String[ ] argsparameter for the
main() method.
Hint:the expression args. lengthevaluates to the number of arguments.
Hint:a statement of the form System.exit(int); terminates the JVM.
a. Our solution is as follows:
if (args.length == 0) {
System.out.println
("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
3. Display an explanatory message and exit if the number of command-line parameters is
odd (The parameters should be a sequence of name/score pairs.).
Hint:Using the remainder operator, %, will allow you to determine if an int is even or
odd. someInt % 2evaluates to 0 if someInt contains an even number.
a. Our solution is as follows:
if ((args.length % 2) > 0) {
System.out.println("You must have an even number of arguments.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
26/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step C: Insert each parameter value into its corresponding instance of
java.util.Vector
1. Create a reference to a java.util.Vector. Label it names. Initialize it to be a new empty
java.util.Vector. This vector will hold the collection of names passed on the command
line.
Hint:new SomeClass() creates an instance of SomeClassusing the no-argumentconstructor.
a. Our solution is as follows:
java.util.Vector names = new java.util.Vector();
2. Create another reference to a java.util.Vector. Label it scores. It will hold the collection
of scores passed on the command line. The position of each score element in the
scoresvector will correspond to the position of each name element in the names
vector after you populate the vectors.
a. Our solution is as follows:
java.util.Vector scores = new java.util.Vector();
3. Copy each command-line argument to its corresponding vector. That is, a name
argument should be added to the namesvector, while a score argument should be
added to the scoresvector.
Hint:namestrings and scorestrings are alternating elements of the String[] args
String array parameter of main().
Hint:the addmethod of java.util.Vectorappends an Objectreference to the end of its
vector.
Hint:the expression args.lengthevaluates to the number of command lineparameters.
Hint:the expression index++increments the contents of an index int variable after it is
used in an expression.
Hint:a while(expression) { } loop enters each iteration of its body only while
expressionevaluates to true.
a. Our solution is as follows:
int index = 0;
while (index < args.length) {
names.add(args[index]);index++;
scores.add(args[index]);
index++;
}
A shorter version of this loop could be coded as:
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
27/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-5
.
Xempty int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
When you use the suffix operator, as in index++, the value is evaluated first andthen incremented. The statement:
names.add(args[index++]);
has the same result as the following two statements:
names.add(args[index]);
index++;
Step D: Find the element indices of the high and low scores1. Create intvariables named hiScoreIndexand lowScoreIndex. Initialize them to 0.
These will contain the indices of the high score and low score within the vectors.
a. Our solution follows:
int hiScoreIndex = 0;
int lowScoreIndex = 0;
2. Create intvariables named hiScoreand lowScore. Initialize hiScoreto 0. Initialize
lowScoreto be the largest possible int value, Integer.MAX_VALUE.
a. Our solution follows:
int hiScore = 0;
int lowScore = Integer.MAX_VALUE;
3. Examine each element of the scoresvector. Use the Integer class to access the String
value as an intvalue. Conditionally update hiScoreor lowScorescores as you
encounter each element. Whenever you update either variable, store the current
element index in hiScoreIndexor lowScoreIndexas appropriate.
Hint:the size()method of java.util.Vectorreturns the number of elements stored in the
vector.
Hint:the get(int)method of java.util.Vectorreturns an element stored in the vector atan int, zero-based, offset.
Hint:convert a numeric String value to an int using this form: Integer.parseInt(String);
a. Here is our solution:
for (index = 0; index < scores.size(); index++) {
//Get the score string
String scoreString = (String) scores.get(index);
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
28/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
//Convert scoreString to an int
int score = Integer.parseInt(scoreString);
// Accumulate index of low and high scores
if (score < lowScore) {
lowScore = score;lowScoreIndex = index;
}
if (score > hiScore) {
hiScore = score;
hiScoreIndex = index;
}
}
Step E: Display the results1. In your main method, after the end of the for loop you created above, add code to
display the high-scoring persons name and score. Use String concatenation to present
a meaningful sentence.
Hint:use get(int)on each vector, passing the corresponding low or high score index.
a. Our solution follows:
//Print results
System.out.println("High scorer was " + names.get(hiScoreIndex) +
" with a score of " + scores.get(hiScoreIndex));
2. Display the low-scoring persons name and score. Again use String concatenation to
present a meaningful sentence.
a. Our solution is as follows:
System.out.println("Low scorer was " + names.get(lowScoreIndex) +
" with a score of " + scores.get(lowScoreIndex));
3. Save the main() method. If the method has errors, fix the errors based on the errormessages.
Step F: Test the program
1. Run the Driverclass, which will cause the JVM to execute the main() method. Pass a
series of name, score pairs on the command line. Previously we were able to just run
the main() method, this time we will have to pass parameters.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
29/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 3. Using Existing Classes 3-7
.
Xempty a. Make sure the Driverclass in lab3is selected in the Package Explorerand click
the Run dropdown menu. Select Run ...
b. This opens up the Launch Configurations dialog.
c. Verify that the Main class indicates lab3.Driver. If not, type Driver into the Main class
box and select the Search button. Select the lab3 - OO Programming with Java
package for themain type to launch.
d. Select the Argumentstab.e. Insert name, score pairs in the Program Argumentsfield. Use:
Adam 18 Bob 23 Charlene 19 Doug 20 Elaine 21
f. Click Applyand then Run.
2. Check the console window for correct results. The values "Adam 18 Bob 23 Charlene
19 Doug 20 Elaine 21" should yield a display with values like these:
High scorer was Bob with a score of 23
Low scorer was Adam with a score of 18
3. Try varying parameters to test your initial test conditions. You can do this by selecting
Run -> Run...from the workbench, change the program arguments and then run your
class.
Summary
In this exercise you passed name/score test statistics on the command line. You validated
the number of parameters, and whether there was an even number of them. You extracted
the parameters from the argument array of the main method, storing each in a
corresponding java.lang.Vector instance. You examined each score to find the high and low
score index. You then used that index to display the name and score of the high and low
scoring persons. Finally you printed the name and score pair that corresponded to the high
and low scores.
You practiced using existing classes String and Vector. You used methods of the
java.lang.System class to exit the JVM and to display results. You instantiated instances of
classes, sent messages to instances, and received results. In the course of completing this
exercise you became more familiar with main features of the String, Vector, and System
classes.
END OF LAB
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
30/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Source Code
package lab3;
public class Driver {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println
("Please pass test statistics on the command line.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
if ((args.length % 2) > 0) {
System.out.println("You must have an even number of arguments.");
System.out.println("Format: name1 score1 name2 score2 ...");
System.exit(1);
}
java.util.Vector names = new java.util.Vector();
java.util.Vector scores = new java.util.Vector();
int index = 0;
while (index < args.length) {
names.add(args[index++]);
scores.add(args[index++]);
}
int hiScoreIndex = 0;
int lowScoreIndex = 0;
int hiScore = 0;
int lowScore = Integer.MAX_VALUE;
for (index = 0; index < scores.size() ; index++) {
// Get the score stringString scoreString = (String) scores.get(index);
// Convert scoreString to an int
int score = Integer.parseInt(scoreString);
if (score < lowScore) {
lowScore = score;
lowScoreIndex = index;
}
Driver.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
31/254
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
32/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
3-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
33/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-1
.
Xempty Exercise 4. Creating Your Own Classes
What This Exercise Is About
You will create three classes used to authenticate a customer who
wishes to access a test using the Distant Exam Delivery System(DEDS). The UML class diagram shown below depict the classes that
you will create in this exercise.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
34/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Create your own class
Create instance variables
Create methods Create constructors
Create accessors
Learning Strategy
Individual exercise
Required Materials WebSphere Studio Application Developer, Version 5.1
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
35/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-3
.
Xempty Exercise Instructions
You will code the appropriate constructors, methods, instance variables, and accessors for
the classes shown in the UML class diagram. The Customerclass represents a customer
of DEDS. A customer has name and e-mail address attributes. It also has an associated
instance of a Profileclass. A Profile has user ID and password attributes. You will code a
main method for the Driver class that will instantiate a Customerand its associatedProfileinstance. You will then ask the Customer instance to log in a user having supplied user ID
and password. Finally you will display the results.
Directions
Step A: Create the package, driver class, and main method
1. If WebSphere Studio Application Developer is already running, skip this step and
proceed to step 2 below. Otherwise, start up WebSphere Studio Application Developer.
a. Select the Windows Startmenu and then select Programs -> IBM WebSphereStudio -> Application Developer.
2. If needed, switch to the Javaperspective. The current perspective is shown in the title
bar of Application Developer.
a. If the current perspective is not Java, select menu Window -> Open Perspective ->
Java. This will open up the Java perspective and switch to it.
3. Close any old edit windows.
a. Menu File -> Close All.
4. Create a package namedlab4 within the existing OO Programming with Javaprojectwith the Driverclass inside of it. The Driverclass needs to have a main method.
a. Select the OO Programming with Javaproject from the Package Explorer.
b. Use the Create a Java Class toolbar button to open up theNew Java Class dialog.
c. Notice that the Source Folder field contains the directory for the OO Programming
with Java project.
d. Fill in a Package value of lab4. Since this package does not exist, the New Java
Classwizard will create it for you.
e. Update the New Java Class dialogto make sure the class Name is Driver,Modifiers arepublic, and Superclass is java.lang.Object.
f. Also ensure that the check box labeled public static void main(String[] args)is
selected (checked). This option tells Application Developer to create a stub main
method in your new class.
g. Make sure that the Constructors from superclasscheck box is not selected.
h. Make sure that the Inherited abstract methodscheck box is not selected.
i. Click Finishto have the wizard create the newDriverclass in package lab4 in
project OO Programming with Java.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
36/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
5. You will come back and add code to the main(String[ ]) method of the Driver class in a
future step.
Information: From now on the detailed steps for creating packages and classes will be
omitted. If you need help in the future, please refer back to these detailed instructions.
Step B: Create the Customer and Profile classes
This step will create the Customer and Profile classes. They will just be empty classes (with
no fields and the default constructor) at the end of this step. You will add fields and
methods in following steps.
1. Refer to the UML class diagram to see the Customer and Profile classes.
2. Create the public Customerclass within the lab4package. Make its superclass be the
default of java.lang.Object. The only method stub option that should be selected is the
Constructors from superclassoption.
Note:the detailed steps have been omitted per earlier note.
3. Create the public Profileclass within thelab4package. Make its superclass be thedefault of java.lang.Object. The only method stub option that should be selected is the
Constructors from superclassoption.
4. When Application Developer creates some stub methods, it may suggest what code
needs to be added using a TODO task item and an accompanying Java comment such
as// TODO Auto-generated constructor stub. The task item will appear in the Tasks
view until the comment has been deleted. The comments have been replaced with code
in all solutions from now on.
Step C: Define the fields and accessor methodsThis step will define the fields (the attributes) for the Customer and Profile classes. You will
use Application Developer to generate getter and setter methods for the fields.
1. Add the private field name of type Stringfor the Customer class. Use the Generate
Getter and Setter option of the Outline view to create getter and setter methods for the
field.
a. Edit the Customerclass within package lab4.
b. In the class (after the class clause and before the constructor) create a new, private,
field nameof type String. Our solution (in bold) follows:
package lab4;
public class Customer {
private String name;
/**
* Constructor for Customer
*/
public Customer () {
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
37/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-5
.
Xempty super();
}
}
c. Select the new field, name, in the Outlineview and bring up a context menu ( right
click). Select Source -> Generate Getter and Setterand have Application
Developer create the getter and setter methods for the name field. Notice that in theGenerate Getter and Setter confirmation dialog box you can uncheck methods you
do not want to create. Click OKto continue. Look at the Customer.java class within
the edit window to see what Application Developer has generated for you.
Information: The methods getName() and setName(String)have been generated
for you. These are getterandsetter methods that are used to retrieve the name
field's value, and set thename field's value. Note that the field name itself is marked
as private. Only methods within this class, Customer,can access this private field.
Other classes must send the getName()or setName(String)messages in order to
access this field.
2. Add the private field eMailof type String for the Customer class, and have Application
Developer generate getter and setter methods for you (repeat steps similar to 1b
through 1d).
3. Add the private field profileof type Profile for the Customerclass, have Application
Developer generate getter and setter methods for you (repeat steps similar to 1b
through 1d).
4. Now edit the Profileclass. Add the private fielduserIdof type Stringfor the Profile
class, have Application Developer generate getter and setter methods for you (repeat
steps similar to 1b through 1d(repeat steps similar to 1b through 1d): make sure you
select the Profile class).
5. Add the private fieldpasswordof type Stringfor the Profileclass, have Application
Developer generate the getter and setter methods for you.
6. Note that the getter and setter methods for the eMailfield in the Customerclass are
getEMail and setEMail. The names of the getting and setting methods are derived from
the field name. If you use a prefix or suffix for fields (for example, fValue, _value,
val_m), you can specify the suffixes and prefixes in the Code Generation preference
page (Windows > Preferences > Java > Code Generation).
7. Save your Customerand Profileclasses and fix any syntax errors you have before youcontinue.
Note that any Java files that have been edited but not saved will have an asterisk (*) in
front of the file name displayed in the tab for the editor view.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
38/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-6 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step D: Update the Driver class and test your classes
In this step, you will create an instance of the Customerclass, and an instance of the
Profileclass. You will then associate the profile with the customer. You will then print
information about the customer and profile to the Console window.
1. Modify the main(String[ ]) method of the Driverclass in package lab4to create an
instance of Customer and store a reference to the instance in a variable calledtheCustomer.
a. Select the main(String[ ])method of the lab4.Driverclass (Note:If you do not have
a main(String[ ]) method you will have to create one).
b. Type into the main method body the Java code needed to create an instance of the
Customer class and store a reference to the instance in a variable named
theCustomer.
The code should look like:
Customer theCustomer = new Customer();
2. Send the message setNameto theCustomerpassing in a value of Adam. Also send
theCustomerthe message setEMailwith a value of [email protected].
a. After the statement you added above, send the message setName(String)to
theCustomerpassing "Adam" as the parameter.
The code should look like:
theCustomer.setName("Adam");
b. Send the messagesetEMail(String)totheCustomerpassing
"[email protected]" as the parameter (sample code omitted).
3. Display the information (name and eMail) about theCustomerto the Console window
(using System.out.println).
a. Use System.out.println(String) to print thetheCustomer'sinformation out to the
Console window.
The code should look like:
System.out.println("The customer's name is: " +
theCustomer.getName() +
", and the eMail address is: " +
theCustomer.getEMail());Information: Remember that white space is irrelevant, this line of code could exist all
on one line. The formatting above is done simply to make the code more readable
within this exercise.
4. Save your changes to the Driver class.
a. Save the main(String[ ])method by clicking Ctrl+S(or selecting Savefrom the
pop-up menu).
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
39/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-7
.
Xempty b. There should be no syntax errors in any of the classes in the lab4 package. Fix any
syntax errors before you continue.
5. Test your code by running the Driver class.
a. Run themain(String[ ])method by clicking Run -> Run As -> Java Application
from themenu ( or click the dropdown button next to the Runner button).
b. The Debug Perspective will open and the Console window should display thefollowing text:
The customer's name is: Adam, and the eMail address is:
6. Now update your Driver class mainmethod to create an instance of Profile and store a
reference to the instance in a local variable called theProfile. Set the userId to ADAM
and set the password to ADAM123. Finally, display the contents of theProfile to the
output Console.
a. Switch back to the Javaperspective and edit the Driverclass.
b. Immediately before the System.out.println() statement in the main method, createan instance of Profileand store its reference in a variable calledtheProfile.
c. Send the message setUserId(String)totheProfilepassing "ADAM" as the
parameter.
d. Send the message setPassword(String)to theProfile passing "ADAM123" as the
parameter.
e. After the other System.out.println() statement, use another
System.out.println(String) statement to print the theProfile object'sinformation out
to the Console window.
f. The code within yourmain(String[ ])method for theDriverclass should look like
the following:Customer theCustomer = new Customer();
theCustomer.setName("Adam");
theCustomer.setEMail("[email protected]");
Profile theProfile = new Profile();
theProfile.setUserId("ADAM");
theProfile.setPassword("ADAM123");
System.out.println("The customer's name is: " +
theCustomer.getName() +
", and the eMail address is: " +
theCustomer.getEMail());System.out.println("The profile's userId is: " +
theProfile.getUserId() +
", and the password is: " +
theProfile.getPassword());
7. Save your changes, fix any syntax errors and test your improved Driver class.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
40/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-8 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
a. Save the main(String[ ]) method by clicking Ctrl+S (or selecting Savefrom the
pop-up menu).
b. Run the main(String[ ])method by clicking theRuntoolbar button (the "runner"
picture).
c. The Console window should contain the following text:
The customer's name is: Adam, and eMail address is:
[email protected] profile's userId is: ADAM, and the password is: ADAM123
Step E: Associate a Profile with a Customer
In this step you will associate the instance of Profile with the instance of Customer. You will
then see how you can access the profile through the customer.
1. Modify the main(String[ ])method in the Driver class so that after the instance of
Profileis created and initialized, the setProfile(Profile)method of Customeris called
to associate theProfilewith theCustomer.
a. After the theProfile.setPassword("ADAM123"); statement send the
setProfile(Profile)message totheCustomer passing theProfile as the parameter.
Our solution looks like this:
theCustomer.setProfile(theProfile);
2. Modify the output of the theProfile'sinformation. Rather than directly referencing the
theProfilevariable, modify the code so that it accesses the instance of Profile
associated withtheCustomervia the getProfile()message.
a. In the System.out.println() statement for printing theProfile'sinformation change
"theProfile"to be"theCustomer.getProfile()".
Our solution looks like this:
System.out.println(
"The profile's userId is: " +
theCustomer.getProfile().getUserId() +
", and the password is: " +
theCustomer.getProfile().getPassword());
Information: This is called message chaining. ThegetProfile()message is sent to
theCustomer, the instance of Profilethat is associated with theCustomeris
returned, then the messagegetUserId()is sent to this instance of Profile.
Functionally the two are equivalent, but with this option you no longer need to retain
a reference to the profile after it is associated with the customer.
3. Save your changes and rerun the Driver class.
a. Save the main(String[ ])method by clicking Ctrl-s (or selectingSavefrom the
pop-up menu).
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
41/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-9
.
Xempty Note:How can you tell if a class has been saved or not? If changes have been
made to a class that have not been saved, the class file name (up in the tab) will
have an asterisk (*) in front of it.
b. Run the main(String[ ])method by clicking the Runtoolbar button.
c. The Consolewindow should display the same information that was previously
displayed. If you would like to debug the code with breakpoints, you could use the
Java editorto add breakpoints by double clicking in the marker bar on the left handside of the line of code, and then click the bug button on the toolbar.
Step F: Create constructors for customer and profile classes
If you look at the Java code within themain(String[ ])method of the Driver class, you have
written a lot of code to initialize the instances of Customerand Profile. You will add some
new methods to the CustomerandProfileclasses that will enable us to initialize the
variables without having to do it manually. These methods are called constructors.
1. Your Customerand Profileclasses should already have constructors that take no
arguments. These were created for you by Application Developer when you created theclasses. Look at the Customer class and see the Customer constructor that takes no
input parameters. Note the zero-argument constructor in the Profile class as well.
2. Add a constructor to theCustomer class that will take two String parameters, the name,
and the eMail (name them theNameand theEMail). Initialize thename field to be the
name passed in, and the eMailfield to be the eMail passed in.
a. Edit the Customerclass within the package lab4.
b. Type in a new Constructor that takes the two input parameters, both of type String.
The first one is named theName and the second parameter is named theEMail.
Our solution follows:
public Customer(String theName, String theEMail) {
super();
}
c. Now update the new constructor to initialize the name and eMail fields in the
Customer class to the parameter values.
Our solution looks like (new code is in bold):
public Customer(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
42/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-10 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
3. Add a constructor to the Profile class that will take two String parameters, the userId,
and the password (named theUserId and thePassword). Initialize the userId field to be
the userId passed in, and the password field to be the password passed in.
a. Edit the Profile class within the package lab4.
b. Add the new constructor to the Profile class that takes the two input parameters for
the user ID and the password.
Our solution looks like:
public Profile(String theUserId, String thePassword) {
super();
}
c. Update the new constructor to set the values for the user id and password fields
from the input parameters.
Our solution looks as follows (new code is in bold):
public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
Step G: Modify Driver's main(string[ ]) method to use the new
constructors
In this step you will modify the main(String[ ])to use the two constructors you created in
the previous step.
1. Modify the statement that creates the instance of Customerto use the two-argument
constructor. Remove the two set statements fornameand eMail.
a. Delete the two statements that send the setName()and setEMail()messages to
theCustomer.
Our solution looks like:
Customer theCustomer = new Customer("Adam", "[email protected]");
2. Modify the statement that creates the instance of Profileto use the two argument
constructor. Remove the two "set" statements for userIdand password.
a. Delete the two statements that send the setUserId()andsetPassword()messages
to theProfile.
Our solution looks like:
Profile theProfile = new Profile("ADAM", "ADAM123");
3. Save your classes (Driver, Profile and Customer) and fix any syntax errors.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
43/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-11
.
Xempty 4. Run the Driver class and check the Console output from the Debug perspective, it
should display the same information that was previously displayed.
Step H: Create the login and authenticate methods
So far all of our methods for the Customerand Profileclasses have been dealing with
setting data, getting data or initializing data. Now you will add some actual business
functionality. You will add alogin()method to Customerthat will allow us to authenticatethe customer. The purpose of the Profile class is to authenticate customers (validate their
user ID and password).
1. Add the public authenticate(String, String)method to the Profileclass. The first
parameter is the user ID and the second parameter is the password. This method will
have a return type of boolean.
a. Edit the Profileclass within the packagelab4.
b. Within the body of the Profile class enter your new authenticate method. We have
used theUserId as the name of the first parameter and have used thePassword as
the name of the second parameter.
Our solution follows:
public boolean authenticate(String theUserId, String thePassword) {
}
2. Write the source code for theauthenticate(String, String)method. The method should
returntrueif the provided userId and password (the two parameters) match the
Profile object'suser ID and password, otherwise it will return false.
a. First test to see if either of the input parameters is null. If either is you need to return
false. Next test to see if theUserId is equal to userId AND thePasswordis equal topassword.
Our solution looks like:
public boolean authenticate
(String theUserId, String thePassword) {
if (theUserId == null || thePassword == null) {
return false;
}
return ( theUserId.equals(userId) &&
thePassword.equals(password) );}
3. Add the method login(String, String)method to the Customer class. The first
parameter is the user ID to be logged in and the second parameter is the password.
This method will have a return type of boolean.
a. Edit the Customerclass within the package lab4.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
44/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-12 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
b. Create a new method, login(String, String) of type public that returns back a
boolean. Our solution uses the names theUserId and thePassword for the
parameters. Our solution follows:
public boolean login(String theUserId, String thePassword) {
}
4. Write the source code for thelogin(String, String)method. The method should sendthe message authenticate(String, String)to the customer's profile and return the
result.
a. Our solution looks like:
public boolean login(String theUserId, String thePassword) {
return profile.authenticate(theUserId, thePassword);
}
Step I: Modify Driver's main(string[ ]) method to log the customer in.
In this step you will create another customer and profile. You will log the first customer in
and verify that the login was successful. You will then log the second customer in, using an
incorrect password, and verify that the login was unsuccessful.
1. Remove the System.out.println() statements of the main(String[ ]).
2. Where the System.out.println() statements were removed, create a boolean variable
called loginSuccessfuland initialize it tofalse.
3. Send the login(String, String)message, using the correct values, to theCustomer
and assign the result into the loginSuccessful variable.
4. Print the result out to the Console identifying the customer's name, and whether or notthe login was successful.
5. Create a new Customer assign it to a variable called anotherCustomer.
6. Create a newProfileassign it to a variable called anotherProfile.
7. Set the profile of anotherCustomer to be anotherProfile.
8. Send thelogin(String, String)message, using incorrect values, to anotherCustomer
and assign the result into the loginSuccessful variable.
9. Print the result to the Console identifying the customer's name, and whether or not the
login was successful.
10.Our solution to all of the above looks as follows (the completemain(String[ ]) method
text):
Customer theCustomer = new Customer("Adam", "[email protected]");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
45/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-13
.
Xempty boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful) {
System.out.println(theCustomer.getName() +
" logged in successfully");
} else {
System.out.println(theCustomer.getName() +" did not log in successfully");
}
Customer anotherCustomer = new Customer("Charlene",
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR",
"WRONGPASSWORD");if (loginSuccessful) {
System.out.println(anotherCustomer.getName() +
" logged in successfully");
} else {
System.out.println(anotherCustomer.getName() +
" did not log in successfully");
}
11. Save your classes (Driver, Profile and Customer) and fix any syntax errors.
12.Run the Driver class and check the Console output in the debug perspective and make
sure it displays the following:
Adam logged in successfully
Charlene did not log in successfully
Summary
This was an exercise in coding Java classes and their four essential ingredients:
constructors, methods, instance variables (also called fields or attributes), and access
methods (also called getters and setters, or accessors). You learned to encapsulate
instance data with accessor methods such that clients of a class could access that data
through a method call on the instance of the class. You also began to use practical Java
coding skills.
END OF LAB
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
46/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-14 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Reference Classes
package lab4;
public class Driver {
public static void main(String[] args) {Customer theCustomer = new Customer("Adam","[email protected]");
Profile theProfile = new Profile("ADAM", "ADAM123");
theCustomer.setProfile(theProfile);
boolean loginSuccessful = false;
loginSuccessful = theCustomer.login("ADAM", "ADAM123");
if (loginSuccessful) {
System.out.println(theCustomer.getName() +
" logged in successfully");
} else {
System.out.println(theCustomer.getName() +
" did not log in successfully");
}
Customer anotherCustomer = new Customer("Charlene","[email protected]");
Profile anotherProfile = new Profile("CHAR", "CHAR321");
anotherCustomer.setProfile(anotherProfile);
loginSuccessful = anotherCustomer.login("CHAR", "WRONGPASSWORD");
if (loginSuccessful) {
System.out.println(anotherCustomer.getName() +
" logged in successfully");
} else {System.out.println(anotherCustomer.getName() +
" did not log in successfully");
}
}
}
Driver.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
47/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-15
.
Xempty
package lab4;
public class Customer {
private String name;private String eMail;
private Profile profile;
/**
* Constructor for Customer
*/
public Customer() {
super();
}
/**
* Create a new Customer from the specified parameters
* @param theName The name to set
* @param theEMail The eMail to set
*/
public Customer(String theName, String theEMail) {
super();
setName(theName);
setEMail(theEMail);
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return name;
}
/**
* Sets the name* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}
/**
Customer.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
48/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-16 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
* Gets the eMail
* @return Returns a String
*/
public String getEMail() {
return eMail;
}
/*** Sets the eMail
* @param mail The eMail to set
*/
public void setEMail(String mail) {
eMail = mail;
}
/**
* Gets the profile* @return Returns a Profile
*/
public Profile getProfile() {
return profile;
}
/**
* Sets the profile
* @param profile The profile to set
*/
public void setProfile(Profile profile) {this.profile = profile;
}
/**
* Log in with the specified user ID and password.
* @param theUserId User ID to use for the login request
* @param thePassword Password to use for the login request
* @return boolean True if login was a success.
*/
public boolean login(String theUserId, String thePassword) {return profile.authenticate(theUserId, thePassword);
}
}
Profile.java
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
49/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 4. Creating Your Own Classes 4-17
.
Xempty
package lab4;
public class Profile {
private String userId;
private String password;
/**
* Constructor for Profile*/
public Profile() {
super();
}
/**
* Create the Profile
* @param theUserId The user id to set
* @param thePassword The password to set.
*/public Profile(String theUserId, String thePassword) {
super();
setUserId(theUserId);
setPassword(thePassword);
}
/**
* Gets the userId
* @return Returns a String
*/
public String getUserId() {
return userId;
}
/**
* Sets the userId
* @param userId The userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
50/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
4-18 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;}
/**
* Authenticate the user ID and password
* @param theUserId The user ID to be authenticated
* @param thePassword The password to be authenticated
* @return Returns true if the user ID and password are valid
*/
public boolean authenticate(String theUserId, String
thePassword) {if (theUserId == null || thePassword == null) {
return false;
}
return (theUserId.equals(userId) &&
thePassword.equals(password));
}
}
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
51/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2002, 2004 Exercise 5. Class Methods and Variables 5-1
.
Xempty Exercise 5. Class Methods and Variables
What This Exercise Is About
In this exercise you will reuse the CustomerandProfile classes that
you created in exercise 12. In addition you will create CupboardandTestclasses. The Cupboard class is a static repository that contains a
collection of Customer references and a collection of Test instances.
The UML class diagrams shown below depict the classes that you will
create in this exercise.
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
52/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-2 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
What You Should Be Able to Do
At the end of the lab, you should be able to:
Use class methods and variables
Declare class (static) variables
Write class (static) methods
Learning Strategy
Individual exercise
Required Materials
WebSphere Studio Application Developer, Version 5.1
Solutions tolab4 (Creating Classes exercise)
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
53/254
8/11/2019 Introduction to Java for OO Developers - Student Exercises JA311
54/254
Student Exercises
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
5-4 Intro to Java for OO Developers Copyright IBM Corp. 2002, 2004
Step B: Reuse existing classes
In this step, you will copy your existing classes to your new package so that you can
continue building upon them.
1. Make sure you are in the Package Explorerview of the Javaperspective. Copy the
Driver, Profile,and Cus