Object-Oriented Programming (OOP) With Java (PDFDrive)
Object-Oriented Programming (OOP) With Java (PDFDrive)
Java
By:
Richard Baldwin
Object-Oriented Programming (OOP) with
Java
By:
Richard Baldwin
Online:
< http://cnx.org/content/col11441/1.121/ >
CONNEXIONS
4 Programming Fundamentals
4.1 Jb0103 Preface to Programming Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
4.2 Jb0105: Java OOP: Similarities and Dierences between Java and C++ . . . . . . . . . . . . . . . . . . . 342
4.3 Jb0110: Java OOP: Programming Fundamentals, Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . 346
4.4 Jb0110r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
4.5 Jb0115: Java OOP: First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . 356
4.6 Jb0120: Java OOP: A Gentle Introduction to Java Programming . . . . . . . . . . . . . . . . . . . . . . . . . . 361
4.7 Jb0120r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
4.8 Jb0130: Java OOP: A Gentle Introduction to Methods in Java . . . . . . . . . . . . . . . . .. . . . . . . . . . . . 372
4.9 Jb0130r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
4.10 Jb0140: Java OOP: Java comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
4.11 Jb0140r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
4.12 Jb0150: Java OOP: A Gentle Introduction to Java Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
4.13 Jb0150r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
4.14 Jb0160: Java OOP: Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . 418
4.15 Jb0160r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
4.16 Jb0170: Java OOP: A little more information about classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
4.17 Jb0170r: Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
4.18 Jb0180: Java OOP: The main method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
4.19 Jb0180r Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
4.20 Jb0190: Java OOP: Using the System and PrintStream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
4.21 Jb0190r: Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
iv
Preface
• Miscellaneous (p. 3)
1.1.2 Welcome
Welcome to my collection titled Object-Oriented Programming (OOP) with Java .
During the past eighteen years, I have published hundreds of Java and OOP programming tutorials on
a variety of dierent topics and websites. I have also developed the teaching materials for several dierent
college-level programming courses in Java/OOP.
A work in progress
This is a work in progress. I am currently combining selected content from those earlier endeavors
with new material that I am developing to create a freely downloadable E-book that covers Java/OOP
programming from programming fundamentals to very advanced OOP concepts.
Among other things, the collection contains the material that I use to teach the following three courses
at Austin Community College in Austin Texas:
1
2 CHAPTER 1. PREFACE
Because it is a work in progress, the collection is growing on a daily basis. If you don't nd what you need
today, come back and take another look in a week or two and you may nd what you need then.
Download options
I encourage you to take advantage of all of the download options (most of which are free) that cnx.org
7 has to oer. You can also customize this material for use in your organized courses or for personal self
study.
Feedback is appreciated
And if you nd the material useful, I would like to hear more about how you are using it.
• The Java Development Kit (JDK) and Java Runtime Engine (JRE)
• The Java API documentation
• A suitable text editor
6 http://cnx.org/content/m45179
7 http://cnx.org/
8 http://docs.oracle.com/javase/7/docs/
9 http://www.oracle.com/technetwork/java/javase/downloads/index.html
10 http://docs.oracle.com/javase/7/docs/webnotes/install/index.html
11 http://docs.oracle.com/javase/tutorial/essential/environment/paths.html
12 http://docs.oracle.com/javase/7/docs/api/index.html
13 http://cnx.org/content/m45117
1.1.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
14 http://cnx.org/content/m45137
15 http://www.jcreator.com/
16 http://drjava.sourceforge.net/
17 http://www.jgrasp.org/
18 http://www.bluej.org/
Objects First
• Software (p. 7)
2.1.2 Preface
If you are new to programming and want to learn how to program, or if you have programming experience
but are new to object-oriented programming (OOP) and want to learn OOP, I can't think of a better way
to take that rst step than through the use of Greenfoot
2 .
Greenfoot provides a set of interactive visual tools coupled with the Java programming language that
makes learning to program both interesting and productive.
(Note that descriptions of the Greenfoot website contained herein are current as of 02/19/13.)
1 This content is available online at <http://cnx.org/content/m45790/1.1/>.
2 http://www.greenfoot.org/door
5
6 CHAPTER 2. OBJECTS FIRST
2.1.3 Overview
2.1.3.1 A visual interactive programming environment
The greenfoot overview
3 page describes Greenfoot as an Interactive Visual World that "...teaches object
orientation with Java."
When programming with Greenfoot, you "Create 'actors' which live in 'worlds' to build games, simula-
tions, and other graphical programs."
Greenfoot is both instructive and enjoyable because it is visual and interactive. Visualization and inter-
action tools are built into the programming environment.
Unlike Scratch
4 and Alice 5
(two programming environments for beginners that use a drag-and-drop
approach to programming) , Greenfoot actors "are programmed in standard textual Java code, providing
a combination of programming experience in a traditional text-based language with visual execution."
According to Wikipedia
6 ,
"Greenfoot is an interactive Java development environment designed primarily for educational pur-
poses at the high school and undergraduate level. It allows easy development of two-dimensional graphical
applications, such as simulations and interactive games.
Greenfoot is being developed and maintained at the University of Kent 7 and La Trobe University 8
, with support from Oracle 9 . It is free software, released under the GPL license. Greenfoot is available
for Microsoft Windows 10 , Mac OS X 11 , Linux 12 , Sun Solaris 13 , and any recent JVM 14
."
Continuing with Wikipedia
15 ,
"Greenfoot aims to motivate learners quickly by providing easy access to animated graphics, sound
and interaction. The environment is highly interactive and encourages exploration and experimentation.
Pedagogically, the design is based on constructivist and apprenticeship approaches.
Secondly, the environment is designed to illustrate and emphasize important abstractions and concepts
of object-oriented programming. Concepts such as the class/object relationship, methods, parameters, and
object interaction are conveyed through visualizations and guided interactions. The goal is to build and
support a mental model that correctly represents modern object-oriented programming systems."
• Ants
19 by mik
3 http://www.greenfoot.org/overview
4 http://scratch.mit.edu/
5 http://www.alice.org/
6 http://en.wikipedia.org/wiki/Greenfoot
7 http://en.wikipedia.org/wiki/University_of_Kent
8 http://en.wikipedia.org/wiki/La_Trobe_University
9 http://en.wikipedia.org/wiki/Oracle
10 http://en.wikipedia.org/wiki/Microsoft_Windows
11 http://en.wikipedia.org/wiki/Mac_OS_X
12 http://en.wikipedia.org/wiki/Linux
13 http://en.wikipedia.org/wiki/Sun_Solaris
14 http://en.wikipedia.org/wiki/Java_Virtual_Machine
15 http://en.wikipedia.org/wiki/Greenfoot
16 http://www.greenfoot.org/home
17 http://www.greenfoot.org/home
18 http://www.greenfoot.org/scenarios
19 http://www.greenfoot.org/scenarios/1016
• Wave-Lab
20 by delmar
• Birds and Trees
21 by polle
(Click a link given above to download and run a simulation. When the simulation window appears, click
the Run button on the simulation window to start the simulation running.)
You can view more than 7500 scenarios (Greenfoot programs are commonly referred to as scenarios) by
clicking the Scenarios link at the top of the home page
22 . Some of the scenarios are impressive. Some
are not so impressive. Many, possibly most, were written by beginning programmers.
(Note that you must have Java applets enabled on your computer to run these simulations. Alternatively,
if you have Greenfoot installed on your computer, you can click the "Open in Greenfoot" button to cause
the program to be downloaded for compilation and execution locally on your computer.)
2.1.4 Software
The Greenfoot software and the Java Development Kit (JDK), both of which run on Windows, Mac, and
Linux, are available for free download
25 .
• You want to run Greenfoot on a computer for which you don't have installation privileges, such as in
a public library or a college computer lab.
20 http://www.greenfoot.org/scenarios/597
21 http://www.greenfoot.org/scenarios/267
22 http://www.greenfoot.org/home
23 http://www.greenfoot.org/home
24 http://www.greenfoot.org/scenarios
25 http://www.greenfoot.org/download
26 http://www.greenfoot.org/download
• You don't already have the Java JDK installed on your computer and would prefer not to go through
the eort to download and install it.
• You want to run Greenfoot, but you don't want to install anything on your computer.
• BlueJ
27
(a more advanced Java programming environment)
• Greenfoot (the programming environment of interest in this module)
• jdk (the Java Development Kit)
• userhome (not sure the purpose of this folder)
You will nd a le named Greenfoot.exe inside the Greenfoot folder. It will have an icon of a small
green footprint. Double click this le to start the Greenfoot program running.
Once the program is running, you can select the Greenfoot Tutorial item on the Help menu to open
a webpage containing a variety of educational tutorials. (I will have more to say about this later.) The
Help menu also provides access to several other useful items, such as documentation for both Greenfoot
and the Java JDK.
Because I believe in the top down model on which the textbook is based, I can recommend this textbook as
a very good way to get started learning computer programming in general and object-oriented programming
in particular. (I am not aliated with the author or the publisher and receive no compensation from the
sale of this textbook.)
30 http://www.greenfoot.org/doc/tut-1
31 http://www.greenfoot.org/doc/tut-2
32 http://www.greenfoot.org/doc/tut-3
33 http://www.greenfoot.org/doc/tut-4
34 http://www.greenfoot.org/doc/tut-5
35 http://www.greenfoot.org/doc/howto-1
36 http://www.joyofcode.org/
37 http://www.youtube.com/user/18km?ob=5#g/u
38 http://www.greenfoot.org/doc/kinect
39 http://www.greenfoot.org/doc/pico
40 http://www.greenfoot.org/doc/sense
41 http://www.greenfoot.org/doc/nch
42 http://www.greenfoot.org/doc/native_loader
43 http://www.greenfoot.org/doc/gamepad
44 http://www.greenfoot.org/doc/csunplugged
45 http://www.greenfoot.org/doc/ap
46 http://sinepost.wordpress.com/
2.1.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
47 http://www.bluej.org/
OOP Self-Assessment
3.1.1 Welcome
Welcome to my group of modules titled OOP Self-Assessment .
This is a self-assessment test designed to help you determine how much you know about object-oriented
programming (OOP) using Java.
In addition to being a self-assessment test, it is also a major learning tool. Each module consists of about
ten to twenty questions with answers and explanations on two or three specic topics. In many cases, the
explanations are extensive. You may nd those explanations to be very educational in your journey towards
understanding OOP using Java.
To give you some idea of the scope of this self-assessment test, when you can successfully answer most of
the questions in modules Ap0010
2 through Ap0140 3 , your level of knowledge will be roughly equivalent to
that of a student who has successfully completed an AP Computer Science course in a U.S. high school up
to but not including data structures. This is based on my interpretation of the College Board's Computer
Science A Course Description
4 .
3.1.2 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
11
12 CHAPTER 3. OOP SELF-ASSESSMENT
I also want you to know that I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 13) , 2 (p. 13) , 3 (p. 13) , 4 (p. 14) , 5 (p. 14) , 6 (p. 15) , 7 (p. 16) , 8 (p. 17) , 9 (p. 18)
, 10 (p. 19)
· 11 (p. 20) , 12 (p. 21) , 13 (p. 23) , 14 (p. 23) , 15 (p. 25) , 16 (p. 27) , 17 (p. 27) , 18 (p. 28)
3.2.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
Questions and answers
The test consists of a series of questions (p. 13) with answers (p. 30) and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
Programming challenge questions
The module also contains a section titled Programming challenge questions (p. 20) . This section provides
specications for one or more programs that you should be able to write once you understand the answers to
all of the questions. (Note that it is not always possible to conne the programming knowledge requirement
to this and earlier modules. Therefore, you may occasionally need to refer ahead to future modules in order
to write the programs.)
Unlike the other questions, solutions are not provided for the Programming challenge questions .
However, in most cases, the specications will describe the output that your program should produce.
Listings
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 29) to easily nd and view the listings while you are reading about them.
3.2.3 Questions
3.2.3.1 Question 1 .
What output is produced by the program in Listing 1 (p. 13) ?
• A. Compiler error
• B. Runtime error
• C. Hello World
• D. Goodbye Cruel World
class Worker{
public void hello(){
System.out.println("Hello World");
}//end hello()
}//end class definition
3.1
3.2.3.2 Question 2 .
What is the largest (algebraic) value of type int?
• A. 32767
• B. 2147483647
• C. -2147483647
• D. -32768
3.2.3.3 Question 3 .
What is the smallest (algebraic) value of type int?
• A. -2147483648
• B. -2147483647
• C. 32767
• D. -32768
3.2.3.4 Question 4 .
What two values are displayed by the program in Listing 2 (p. 14) ?
• A. -2147483648
• B. 1.7976931348623157E308
• C. -2147483647
• D. 4.9E-324
class Worker{
public void printDouble(){
System.out.println(
Double.MAX_VALUE);
System.out.println(
Double.MIN_VALUE);
}//end printDouble()
}//end class definition
3.2
3.2.3.5 Question 5 .
What output is produced by the program in Listing 3 (p. 15) ?
• A. true
• B. false
• C. 1
• D. 0
class Worker{
private boolean myVar;
public void printBoolean(){
System.out.println(myVar);
}//end printBoolean()
}//end class definition
3.3
3.2.3.6 Question 6 .
What output is produced by the program shown in Listing 4 (p. 16) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. false
class Worker{
public void printBoolean(){
boolean myVar;
System.out.println(myVar);
}//end printBoolean()
}//end class definition
3.4
3.2.3.7 Question 7 .
What output is produced by the program shown in Listing 5 (p. 17) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. false
class Worker{
public void printBoolean(){
boolean myVar = true;
myVar = false;
System.out.println(myVar);
}//end printBoolean()
}//end class definition
3.5
3.2.3.8 Question 8 .
The plus (+) character can be used to perform numeric addition in Java. What output is produced by the
program shown in Listing 6 (p. 18) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. 2
• E. 1
class Worker{
public void printBoolean(){
boolean myVar = true;
System.out.println(1 + myVar);
}//end printBoolean()
}//end class definition
3.6
3.2.3.9 Question 9 .
The plus (+) character can be used to perform numeric addition in Java. What output is produced by the
program shown in Listing 7 (p. 19) ?
• A. Compiler Error
• B. Runtime Error
• C. 6
• D. 6.0
class Worker{
public void printMixed(){
double x = 3;
int y = 3;
System.out.println(x+y);
}//end printMixed()
}//end class definition
3.7
3.2.3.10 Question 10 .
The slash (/) character can be used to perform numeric division in Java. What output is produced by the
program shown in Listing 8 (p. 20) ?
• A. Compiler Error
• B. Runtime Error
• C. 0.33333334
• D. 0.3333333333333333
class Worker{
public void printMixed(){
System.out.println(1.0/3);
}//end printMixed()
}//end class definition
3.8
Instructions to student:
This program refuses to compile without errors.
ITSE
2321
**********************************************************/
public class Ap0010a1{
public static void main(String args[]){
System.out.println("ITSE");
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
Class Worker{
public void doIt(){
System.out.println("2321");
}//end doIt()
}//end class definition
//=======================================================//
3.9
3.2.4.2 Question 12
Write the program described in Listing 10 (p. 22) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Receives and displays an incoming parameter of type int.
484495695
484495695
**********************************************************/
//Student is not expected to understand import directives
// at this point.
import java.util.Random;
import java.util.Date;
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.10
3.2.4.3 Question 13
Write the program described in Listing 11 (p. 23) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that returns the largest value of type
int as type float.
class Worker{
//-----------------------------------------------------//
//Insert the method named doIt between these lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.11
3.2.4.4 Question 14
Write the program described in Listing 12 (p. 24) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Receives an incoming parameter of type double.
2. Converts that value to type int.
3. Returns the int
6.672032181818181E8
667203218
**********************************************************/
//Student is not expected to understand import directives
// at this point.
import java.util.Random;
import java.util.Date;
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.12
3.2.4.5 Question 15
Write the program described in Listing 13. (p. 26)
Instructions to student:
This program refuses to compile without errors.
-1.30240579E8
-1.30240579E8
**********************************************************/
//Student is not expected to understand import directives
// at this point.
import java.util.Random;
import java.util.Date;
class Worker{
public void doIt(double val){
int var = val;
System.out.println(var);
}//end doIt()
}//end class definition
//=======================================================//
3.13
3.2.4.6 Question 16
Write the program described in Listing 14 (p. 27) .
Instructions to student:
Beginning with the code shown below, modify the
code in the method named doIt so that the program
displays
3.3333333333333335 instead of 3
3.3333333 instead of 3
**********************************************************/
public class Ap0010f1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
public void doIt(){
System.out.println(10/3);
}//end doIt()
}//end class definition
//=======================================================//
3.14
3.2.4.7 Question 17
Write the program described in Listing 15 (p. 28) .
Instructions to student:
Beginning with the code shown below, modify the
code in the method named doIt so that the program
displays
class Worker{
public void doIt(int val){
System.out.println(val/6);
}//end doIt()
}//end class definition
//=======================================================//
3.15
3.2.4.8 Question 18
Write the program described in Listing 16 (p. 29) .
Instructions to student:
This program refuses to compile without errors.
false
**********************************************************/
class Worker{
public void doIt(){
boolean var;
System.out.println(var);
}//end doIt()
}//end class definition
//=======================================================//
3.16
3.2.5 Listings
• Listing 1 (p. 13) . Listing for Question 1.
• Listing 2 (p. 14) . Listing for Question 4.
• Listing 3 (p. 15) . Listing for Question 5.
• Listing 4 (p. 16) . Listing for Question 6.
• Listing 5 (p. 17) . Listing for Question 7.
• Listing 6 (p. 18) . Listing for Question 8.
• Listing 7 (p. 19) . Listing for Question 9.
• Listing 8 (p. 20) . Listing for Question 10.
• Listing 9 (p. 21) . Listing for Question 11.
• Listing 10 (p. 22) . Listing for Question 12.
• Listing 11 (p. 23) . Listing for Question 13.
• Listing 12 (p. 24) . Listing for Question 14.
• Listing 13 (p. 26) . Listing for Question 15.
3.2.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.2.7 Answers
3.2.7.1 Answer 10 .
D. 0.3333333333333333
3.2.7.1.1 Explanation 10
Divide oating type by integer type
This program divides the literal oating value of 1.0 by the literal integer value of 3 (no decimal point
is specied in the integer literal value) .
Automatic conversion from narrow to wider type
To begin with, whenever division is performed between a oating type and an integer type, the integer
type is automatically converted (sometimes called promoted) to a oating type and oating arithmetic is
performed.
What is the actual oating type, oat or double?
The real question here is, what is the type of the literal shown by 1.0 (with a decimal point separating
the 1 and the 0) double
. Is it a or a oat ?
Type double is the default
3.2.7.2 Answer 9 .
D. 6.0
3.2.7.2.1 Explanation 9
Declare and initialize two local variables
This program declares and initializes two local variables, one of type double and the other of type
int . Each variable is initialized with the integer value 3.
Automatic conversion to oating type double
double
However, before the value of 3 is stored in the variable, it is automatically converted to type
double .
Automatic conversion in mixed-type arithmetic
Numeric addition is performed on the two variables. Whenever addition is performed between a oating
type and an integer type, the integer type is automatically converted to a oating type and oating arithmetic
is performed.
A oating result
This produces a oating result. When this oating result is passed to the println method for display,
a decimal point and a zero are displayed to indicate a oating type, even though in this case, the fractional
part of the result is zero.
Back to Question 9 (p. 18)
3.2.7.3 Answer 8 .
A. Compiler Error
3.2.7.3.1 Explanation 8
Initialize boolean variable to true
boolean variable with the value true . Then it attempts to
This program declares and initializes a
boolean variable named myVar .
add the literal value 1 to the value stored in the
Arithmetic with boolean values is not allowed
As mentioned earlier, unlike C++, boolean types in Java cannot participate in arithmetic expressions.
Therefore, this program will not compile. The compiler error produced by this program under JDK 1.3
reads partially as follows:
note:
3.2.7.4 Answer 7 .
D. false
3.2.7.4.1 Explanation 7
Format for variable initialization
This program declares a local boolean variable and initializes it to the value true . All variables,
local or otherwise, can be initialized in this manner provided that the expression on the right of the equal
sign evaluates to a value that is assignment compatible with the type of the variable. (I will have more to
say about assignment compatibility in a future module) .
Value is changed before display
println
However, before calling the method to display the initial value of the variable, the program
uses the assignment operator (=) to assign the value false to the variable. Thus, when it is displayed, the
value is false .
Back to Question 7 (p. 16)
3.2.7.5 Answer 6 .
A. Compiler Error
3.2.7.5.1 Explanation 6
A local boolean variable
myVar
In this program, the primitive variable named is a local variable belonging to the method
named printBoolean .
Local variables are not automatically initialized
Unlike instance variables, if you fail to initialize a local variable, the variable is not automatically initial-
ized.
Cannot access value from uninitialized local variable
If you attempt to access and use the value from an uninitialized local variable before you assign a value
to it, you will get a compiler error. The compiler error produced by this program under JDK 1.3 reads
partially as follows:
note:
3.2.7.6 Answer 5 .
B. false
3.2.7.6.1 Explanation 5
The boolean type
In this program, the primitive variable named myVar is an instance variable of the type boolean .
What is an instance variable?
An instance variable is a variable that is declared inside a class, outside of all methods and constructors
of the class, and is not declared static. Every object instantiated from the class has one. That is why it is
called an instance variable.
Cannot use uninitialized variables in Java
One of the great things about Java is that it is not possible to make the mistake of using variables that
have not been initialized.
Can initialize when declared
All Java variables can be initialized when they are declared.
Member variables are automatically initialized
If the programmer doesn't initialize the variables declared inside the class but outside of a method (often
referred to as member variables as opposed to local variables) , they are automatically initialized to a default
boolean variable is false.
value. The default value for a
Did you know the boolean default value?
I wouldn't be overly concerned if you had selected the answer A. true, because I wouldn't necessarily
expect you to memorize the default initialization value.
Great cause for concern
However, I would be very concerned if you selected either C. 1 or D. 0.
Java has a true boolean type
Unlike C++, Java does not represent true and false by the numeric values of 1 and 0. (At least the
numeric values that represent true and false are not readily accessible by the programmer.)
Thus, you cannot include boolean types in arithmetic expressions, as is the case in C++.
Back to Question 5 (p. 14)
3.2.7.7 Answer 4 .
• B. 1.7976931348623157E308
• D. 4.9E-324
3.2.7.7.1 Explanation 4
Floating type versus integer type
If you missed this one, shame on you!
I didn't expect you to memorize the maximum and minimum values represented by the oating type
double, but I did expect you to be able to distinguish between the display of a oating value and the display
of an integer value.
Both values are positive
Note that both of the values given above are positive values.
Unlike the integer types discussed earlier, the constants named MAX_VALUE and MIN_VALUE
don't represent the ends of a signed number range for type double . Rather, they represent the largest
and smallest (non-zero) values that can be expressed by the type.
An indication of granularity
MIN_VALUE is an indication of the degree of granularity of values expressed as type double .
Any double value can be treated as either positive or negative.
Two oating types are available
Java provides two oating types: oat and double . The double type provides the greater range,
or to use another popular terminology, it is the wider of the two.
What is the value range for a oat?
In case you are interested, using the same syntax as above, the value range for type oat is from 1.4E-45
to 3.4028235E38
Double is often the default type
There is another thing that is signicant about type double . In many cases where a value is automat-
ically converted to a oating type, it is converted to type double rather than to type oat. This will come
up in future modules.
Back to Question 4 (p. 14)
3.2.7.8 Answer 3 .
A. -2147483648
3.2.7.8.1 Explanation 3
Could easily have guessed
As a practical matter, you had one chance in two of guessing the correct answer to this question, already
having been given the value of the largest algebraic value for type int.
And the winner is ...
Did you answer B. -2147483647? WRONG
If so, you may be wondering why the most negative value isn't equal to the negative version of the most
positive value?
A twos-complement characteristic
Without going into the details of why, it is a well-known characteristic of binary twos-complement notation
that the value range extends one unit further in the negative direction than in the positive direction.
What about the other two values?
Do the values of -32768 and 32767 in the set of multiple-choice answers to this question represent anything
in particular?
Yes, they represent the extreme ends of the value range for a 16-bit binary number in twos-complement
notation.
Does Java have a 16-bit integer type?
short type in Java is represented in 16-bit binary twos-complement
Just in case you are interested, the
signed notation, so this is the value range for type short.
What about type byte?
byte
Similarly, a value of type is represented in 8-bit binary twos-complement signed notation, with a
value range extending from -128 to 127.
Back to Question 3 (p. 13)
3.2.7.9 Answer 2 .
B. 2147483647
3.2.7.9.1 Explanation 2
First question on types
This is the rst question on Java types in this group of self-assessment modules.
32-bit signed twos-complement integers
int are stored as 32-bit signed integers in twos-complement notation.
In Java, values of type
Can you calculate the values?
There are no unsigned integer types in Java, as there are in C++. If you are handy with binary notation,
you could calculate the largest positive value that can be stored in 32 bits in twos-complement notation.
See documentation for the Integer class
3.2.7.10 Answer 1 .
C. Hello World
3.2.7.10.1 Explanation 1
The answer to this rst question is intended to be easy. The purpose of the rst question is to introduce you
to the syntax that will frequently be used for program code in this group of self-assessment modules.
The controlling class and the main method
In this example, the class namedAp001 is the controlling class . It contains a method named main
, with a signature that matches the required signature for the main method. When the user executes this
main in the controlling class.
program, the Java virtual machine automatically calls the method named
Create an instance of Worker
The main method uses the new operator along with the default constructor for the class named
Worker to create a new instance of the class named Worker (an object of the Worker class) . This is
often referred to as instantiating an object.
A reference to an anonymous object
new operator and
The combination of the the default constructor for the Worker class returns a
reference to the new object. In this case, the object is instantiated as an anonymous object , meaning that
the object's reference is not saved in a named reference variable. (Instantiation of a non-anonymous object
will be illustrated later.)
Call hello method on Worker object
The main method contains a single executable statement.
main method calls
As soon as the reference to the new object is returned, the single statement in the
the hello method on that reference.
Output to standard output device
This causes the hello method belonging to the new object (of the class named Worker ) to execute.
The code in the hello method calls the println method on the static variable of the System class
named out .
Lots of OOP embodied in the hello method
I often tell my students that I can tell a lot about whether a student really understands object-oriented
programming in Java by asking them to explain everything that they know about the following statement:
System.out.println("Hello World");
I would expect the answer to consume about ten to fteen minutes if the student really understands Java
OOP.
The one-minute version
When the virtual machine starts a Java application running, it automatically instantiates an I/O stream
object linked to the standard output device (normally the screen) and stores a reference to that object in
the static variable named out belonging to the class named System .
Call the println instance method on out
Calling the println method on that reference, and passing a literal string ("Hello World") to that
method causes the contents of the literal String object to be displayed on the standard output device.
Display Hello World on the screen
In this case, this causes the words Hello World to be displayed on the standard output device. This is
the answer to the original question.
Time for main method to terminate
6 http://cnx.org/content/m45117
When the hello method returns, the main method has nothing further to do, so it terminates. When
the main method terminates in a Java application, the application terminates and returns control to the
operating system. This causes the system prompt to reappear.
A less-cryptic form
A less cryptic form of this program is shown in Listing 17 (p. 36) .
3.17
· 1 (p. 37) , 2 (p. 38) , 3 (p. 39) , 4 (p. 40) , 5 (p. 41) , 6 (p. 42) , 7 (p. 43) , 8 (p. 44) , 9 (p. 45)
, 10 (p. 46) , 11 (p. 47) , 12 (p. 48) , 13 (p. 49) , 14 (p. 50) , 15 (p. 51)
· 16 (p. 52) , 17 (p. 53) , 18 (p. 54) , 19 (p. 55) , 20 (p. 56) , 21 (p. 57) , 22 (p. 58)
3.3.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
Questions and answers
The test consists of a series of questions (p. 37) with answers (p. 60) and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
Programming challenge questions
The module also contains a section titled Programming challenge questions (p. 52) . This section provides
specications for one or more programs that you should be able to write once you understand the answers to
all of the questions. (Note that it is not always possible to conne the programming knowledge requirement
to this and earlier modules. Therefore, you may occasionally need to refer ahead to future modules in order
to write the programs.)
Unlike the other questions, solutions are not provided for the Programming challenge questions .
However, in most cases, the specications will describe the output that your program should produce.
Listings
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 59) to easily nd and view the listings while you are reading about them.
3.3.3 Questions
3.3.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 38) ?
• A. Compiler Error
• B. Runtime Error
• C. 3.0
• D. 4.0
• E. 7.0
7 This content is available online at <http://cnx.org/content/m45286/1.3/>.
class Worker{
public void doAsg(){
double myVar;
myVar = 3.0;
myVar += 4.0;
System.out.println(myVar);
}//end doAsg()
}//end class definition
3.18
3.3.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 39) ?
• A. Compiler Error
• B. Runtime Error
• C. 2.147483647E9
• D. 2.14748365E9
class Worker{
public void doAsg(){
double myDoubleVar;
//Integer.MAX_VALUE = 2147483647
int myIntVar = Integer.MAX_VALUE;
myDoubleVar = myIntVar;
System.out.println(myDoubleVar);
}//end doAsg()
}//end class definition
3.19
3.3.3.3 Question 3
What output is produced by the following program?
• A. Compiler Error
• B. Runtime Error
• C. 2147483647
• D. 2.147483647E9
class Worker{
public void doAsg(){
//Integer.MAX_VALUE = 2147483647
double myDoubleVar =
Integer.MAX_VALUE;
int myIntVar;
myIntVar = myDoubleVar;
System.out.println(myIntVar);
}//end doAsg()
}//end class definition
3.20
3.3.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 41) ?
• A. Compiler Error
• B. Runtime Error
• C. 2147483647
• D. 2.147483647E9
class Worker{
public void doAsg(){
//Integer.MAX_VALUE = 2147483647
double myDoubleVar =
Integer.MAX_VALUE;
int myIntVar;
myIntVar = (int)myDoubleVar;
System.out.println(myIntVar);
}//end doAsg()
}//end class definition
3.21
3.3.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 42) ?
• A. Compiler Error
• B. Runtime Error
• C. 4.294967294E9
• D. 4294967294
class Worker{
public void doMixed(){
//Integer.MAX_VALUE = 2147483647
int myIntVar = Integer.MAX_VALUE;
System.out.println(2.0 * myIntVar);
}//end doMixed()
}//end class definition
3.22
3.3.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 43) ?
• A. Compiler Error
• B. Runtime Error
• C. 2147483649
• D. -2147483647
class Worker{
public void doMixed(){
//Integer.MAX_VALUE = 2147483647
int myVar01 = Integer.MAX_VALUE;
int myVar02 = 2;
System.out.println(
myVar01 + myVar02);
}//end doMixed()
}//end class definition
3.23
3.3.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 44) ?
• A. Compiler Error
• B. Runtime Error
• C. 33.666666
• D. 34
• E. 33
class Worker{
public void doMixed(){
int myVar01 = 101;
int myVar02 = 3;
System.out.println(
myVar01/myVar02);
}//end doMixed()
}//end class definition
3.24
3.3.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 45) ?
• A. Compiler Error
• B. Runtime Error
• C. Innity
• D. 11
class Worker{
public void doMixed(){
int myVar01 = 11;
int myVar02 = 0;
System.out.println(
myVar01/myVar02);
}//end doMixed()
}//end class definition
3.25
3.3.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 46) ?
• A. Compiler Error
• B. Runtime Error
• C. Innity
• D. 11
class Worker{
public void doMixed(){
double myVar01 = 11;
double myVar02 = 0;
System.out.println(
myVar01/myVar02);
}//end doMixed()
}//end class definition
3.26
3.3.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 47) ?
• A. Compiler Error
• B. Runtime Error
• C. 2
• D. -2
class Worker{
public void doMod(){
int myVar01 = -11;
int myVar02 = 3;
System.out.println(
myVar01 % myVar02);
}//end doMod()
}//end class definition
3.27
3.3.3.11 Question 11
What output is produced by the program shown in Listing 11 (p. 48) ?
• A. Compiler Error
• B. Runtime Error
• C. 2
• D. 11
class Worker{
public void doMod(){
int myVar01 = -11;
int myVar02 = 0;
System.out.println(
myVar01 % myVar02);
}//end doMod()
}//end class definition
3.28
3.3.3.12 Question 12
What output is produced by the program shown in Listing 12 (p. 49) ?
• A. Compiler Error
• B. Runtime Error
• C. -0.010999999999999996
• D. 0.010999999999999996
class Worker{
public void doMod(){
double myVar01 = -0.11;
double myVar02 = 0.033;
System.out.println(
myVar01 % myVar02);
}//end doMod()
}//end class definition
3.29
3.3.3.13 Question 13
What output is produced by the program shown in Listing 13 (p. 50) ?
• A. Compiler Error
• B. Runtime Error
• C. 0.0
• D. 1.5499999999999996
class Worker{
public void doMod(){
double myVar01 = 15.5;
double myVar02 = 1.55;
System.out.println(
myVar01 % myVar02);
}//end doMod()
}//end class definition
3.30
3.3.3.14 Question 14
What output is produced by the program shown in Listing 14 (p. 51) ?
• A. Compiler Error
• B. Runtime Error
• C. Innity
• D. NaN
class Worker{
public void doMod(){
double myVar01 = 15.5;
double myVar02 = 0.0;
System.out.println(
myVar01 % myVar02);
}//end doMod()
}//end class definition
3.31
3.3.3.15 Question 15
What output is produced by the program shown in Listing 15 (p. 52) ?
• A. Compiler Error
• B. Runtime Error
• C. -3 2
• D. -3 -2
class Worker{
public void doMod(){
int x = 11;
int y = -3;
System.out.println(
x/y + " " + x % y);
}//end doMod()
}//end class definition
3.32
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the proper use of the combined
arithmetic/assignment operators such as the following
operators:
+=
*=
**********************************************************/
public class Ap0020a1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.33
3.3.4.2 Question 17
Write the program described in Listing 17 (p. 54) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the detrimental impact of integer arithmetic
overflow.
**********************************************************/
public class Ap0020b1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.34
3.3.4.3 Question 18
Write the program described in Listing 18 (p. 55) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the effect of integer truncation that
occurs with integer division.
**********************************************************/
public class Ap0020c1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.35
3.3.4.4 Question 19
Write the program described in Listing 19 (p. 56) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the effect of double divide by zero.
2. Illustrates the effect of integer divide by zero.
**********************************************************/
public class Ap0020d1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.36
3.3.4.5 Question 20
Write the program described in Listing 20 (p. 57) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the effect of the modulus operation with
integers.
**********************************************************/
public class Ap0020e1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.37
3.3.4.6 Question 21
Write the program described in Listing 21 (p. 58) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the effect of the modulus operation with
doubles.
**********************************************************/
public class Ap0020f1{
public static void main(String args[]){
new Worker().doIt();
}//end main()
}//end class definition
//=======================================================//
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.38
3.3.4.7 Question 22
Write the program described in Listing 22 (p. 59) .
Instructions to student:
Beginning with the code fragment shown below, write a
method named doIt that:
1. Illustrates the concatenation of the following strings
separated by space characters.
"This"
"is"
"fun"
class Worker{
//-----------------------------------------------------//
//Student: insert the method named doIt between these
// lines.
//-----------------------------------------------------//
}//end class definition
//=======================================================//
3.39
3.3.5 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.3.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.3.7 Answers
3.3.7.1 Answer 15
C. -3 2
3.3.7.1.1 Explanation 15
String concatenation
This program uses String concatenation, which has not been previously discussed in this group of
self-assessment modules.
In this case, the program executes both an integer divide operation and an integer modulus operation,
usingString concatenation to display both results on a single line of output.
Quotient = -3 with a remainder of 2
Thus, the displayed result is the integer quotient followed by the remainder.
What is String concatenation?
If either operand of the plus (+) operator is of type String , no attempt is made to perform arithmetic
addition. Rather, the other operand is converted to a String , and the two strings are concatenated.
A space character, " "
The string containing a space character (" ") in this expression appears as the right operand of one plus
operator and as the left operand of the other plus operator.
If you already knew about String concatenation, you should have been able to gure out the correct
answer to the question on the basis of the answers to earlier questions in this module.
Back to Question 15 (p. 51)
3.3.7.2 Answer 14
D. NaN
3.3.7.2.1 Explanation 14
Floating modulus operation involves oating divide
The modulus operation with oating operands and 0.0 as the right operand produces NaN , which
stands for Not a Number .
What is the actual value of Not a Number?
Double.NaN
A symbolic constant that is accessible as species the value that is returned in this case.
Be careful what you try to do with it. It has some peculiar behavior of its own.
Back to Question 14 (p. 50)
3.3.7.3 Answer 13
D. 1.5499999999999996
3.3.7.3.1 Explanation 13
A totally incorrect result
Unfortunately, due to oating arithmetic inaccuracy, the modulus operation in this program produces an
entirely incorrect result.
The result should be 0.0, and that is the result produced by my hand calculator.
Terminates one step too early
However, this program terminates the repetitive subtraction process one step too early and produces an
incorrect remainder.
Be careful
This program is included here to emphasize the need to be very careful how you interpret the result of
performing modulus operations on oating operands.
Back to Question 13 (p. 49)
3.3.7.4 Answer 12
C. -0.010999999999999996
3.3.7.4.1 Explanation 12
Modulus operator can be used with oating types
In this case, the program returns the remainder that would be produced by dividing a double value of
-0.11 by a double value of 0.033 and terminating the divide operation at the beginning of the fractional part
of the quotient.
Say that again
Stated dierently, the result of the modulus operation is the remainder that results after
• subtracting the right operand from the left operand an integral number of times, and
• terminating the repetitive subtraction process when the result of the subtraction is less than the right
operand
3.3.7.5 Answer 11
B. Runtime Error
3.3.7.5.1 Explanation 11
Integer modulus involves integer divide
The modulus operation with integer operands involves an integer divide.
Therefore, it is subject to the same kind of problem as an ordinary integer divide when the right operand
has a value of zero.
Program produces a runtime error
In this case, the program produced a runtime error that terminated the program. The error produced
by JDK 1.3 is as follows:
note:
3.3.7.6 Answer 10
D. -2
3.3.7.6.1 Explanation 10
What is a modulus operation?
In elementary terms, we like to say that the modulus operation returns the remainder that results from
a divide operation.
In general terms, that is true.
3.3.7.7 Answer 9
C. Innity
3.3.7.7.1 Explanation 9
Floating divide by zero
double value of 11 by the double
This program attempts to divide the value of zero.
No runtime error with oating divide by zero
In the case of oating types, an attempt to divide by zero does not produce a runtime error. Rather, it
println
returns a value that the method interprets and displays as Innity.
What is the actual value?
The actual value returned by this program is provided by a static nal variable in the Double class
named POSITIVE_INFINITY .
(There is also a value for NEGATIVE_INFINITY, which is the value that would be returned if one of
the operands were a negative value.)
Is this a better approach?
Is this a better approach than throwing an exception as is the case for integer divide by zero?
I will let you be the judge of that.
In either case, you can test the right operand before the divide to assure that it isn't equal to zero.
Cannot use exception handling in this case
For oating divide by zero, you cannot handle the problem by using try-catch.
However, you can test the result following the divide to see if it is equal to either of the innity values
mentioned above.
Back to Question 9 (p. 45)
3.3.7.8 Answer 8
B. Runtime Error
3.3.7.8.1 Explanation 8
Dividing by zero
This program attempts to divide theint value of 11 by the int value of zero.
Integer divide by zero is not allowed
This produces a runtime error and terminates the program.
The runtime error is as follows under JDK 1.3:
note:
note:
java.lang.ArithmeticException.
The code in the catch block can be designed to deal with the problem if it occurs. (Exception handling will
be discussed in a future module.)
Back to Question 8 (p. 44)
3.3.7.9 Answer 7
E. 33
3.3.7.9.1 Explanation 7
Integer truncation
This program illustrates the integer truncation that results when the division operator is applied to
operands of the integer types.
The result of simple long division
We all know that when we divide 101 by 3, the result is 33.666666 with the sixes extending out to the
limit of our arithmetic accuracy.
The result of rounding
If we round the result to the next closest integer, the result is 34.
Integer division does not round
However, when division is performed using operands of integer types in Java, the fractional part is simply
discarded (not rounded) .
The result is the whole number result without regard for the fractional part or the remainder.
Thus, with integer division, 101/3 produces the integer value 33.
If either operand is a oating type ...
If either operand is one of the oating types,
3.3.7.10 Answer 6
D. -2147483647
3.3.7.10.1 Explanation 6
Danger, integer overow ahead!
This program illustrates a very dangerous situation involving arithmetic using operands of integer types.
This situation involves a condition commonly known as integer overow .
The good news
The good news about doing arithmetic using operands of integer types is that as long as the result is
within the allowable value range for the wider of the integer types, the results are exact (oating arithmetic
often produces results that are not exact) .
The bad news
The bad news about doing arithmetic using operands of integer types is that when the result is not
within the allowable value range for the wider of the integer types, the results are garbage, having no usable
relationship to the correct result (oating arithmetic has a high probability of producing approximately
correct results, even though the results may not be exact).
For this specic case ...
As you can see by the answer to this question, when a value of 2 was added to the largest positive value
that can be stored in type int , the incorrect result was a very large negative value.
The result is simply incorrect. (If you know how to do binary arithmetic, you can gure out how this
happens.)
No safety net in this case just garbage
Furthermore, there was no compiler error and no runtime error. The program simply produced an
incorrect result with no warning.
You need to be especially careful when writing programs that perform arithmetic using operands of
integer types. Otherwise, your programs may produce incorrect results.
Back to Question 6 (p. 42)
3.3.7.11 Answer 5
C. 4.294967294E9
3.3.7.11.1 Explanation 5
Mixed-type arithmetic
This program illustrates the use of arithmetic operators with operands of dierent types.
Declare and initialize an int
The method named doMixed declares a local variable of type int named myIntVar and initializes
it with the largest positive value that can be stored in type int .
Evaluate an arithmetic expression
An arithmetic expression involving myIntVar is evaluated and the result is passed as a parameter to
the println method where it is displayed on the computer screen.
Multiply by a literal double value
The arithmetic expression uses the multiplication operator (*) to multiply the value stored in myIntVar
by 2.0 (this literal operand is type double by default) .
Automatic conversion to wider type
When arithmetic is performed using operands of dierent types, the type of the operand of the narrower
type is automatically converted to the type of the operand of the wider type, and the arithmetic is performed
on the basis of the wider type.
Result is of the wider type
The type of the result is the same as the wider type.
In this case ...
Because the left operand is type double , the int value is converted to type double and the
arithmetic is performed as type double .
This produces a result of type double , causing the oating value 4.294967294E9 to be displayed on
the computer screen.
Back to Question 5 (p. 41)
3.3.7.12 Answer 4
C. 2147483647
3.3.7.12.1 Explanation 4
Uses a cast operator
This program, named Ap013.java , diers from the earlier program named Ap012.java in one
important respect.
This program uses a cast operator to force the compiler to allow a narrowing conversion in order to
assign a double value to an int variable.
The cast operator
The statement containing the cast operator is shown below for convenient viewing.
note:
myIntVar = (int)myDoubleVar;
3.3.7.13 Answer 3
A. Compiler Error
3.3.7.13.1 Explanation 3
Conversion from double to int is not automatic
This program attempts to assign a value of type double to a variable of type int .
Even though we know that the specic double value involved would t in the int variable with no loss
double
of precision, the conversion from to int is not a widening conversion.
This is a narrowing conversion
In fact, it is a narrowing conversion because the allowable value range for an int is less than the
allowable value range for a double .
The conversion is not allowed by the compiler. The following compiler error occurs under JDK 1.3:
note:
3.3.7.14 Answer 2
C. 2.147483647E9
3.3.7.14.1 Explanation 2
Declare a double
The method named doAsg rst declares a local variable of type double named myDoubleVar
without providing an initial value.
Declare and initialize an int
Then it declares anint variable named myIntVar and initializes its value to the integer value
2147483647 (you learned about Integer.MAX_VALUE in an earlier module) .
Assign the int to the double
Following this, the method assigns contents of the int variable to the double variable.
An assignment compatible conversion
This is an assignment compatible conversion. In particular, the integer value of 2147483647 is auto-
matically converted to a double double variable.
value and stored in the
double representation of that value is what appears on the screen
The later when the value of
myDoubleVar is displayed.
What is an assignment compatible conversion?
An assignment compatible conversion for the primitive types occurs when the required conversion is a
widening conversion.
What is a widening conversion?
A widening conversion occurs when the allowable value range of the type of the left operand of the
assignment operator is greater than the allowable value range of the right operand of the assignment operator.
A double is wider than an int
Since the allowable value range of type double is greater than the allowable value range of type int
, assignment of an int value to a double variable is allowed, with conversion from int to double
occurring automatically.
A safe conversion
It is also signicant to note that there is no loss in precision when converting from an int to a double
.
An unsafe but allowable conversion
However, a loss of precision may occur when an int is assigned to a oat , or when a long is
assigned to adouble .
What would a oat produce ?
The value of 2.14748365E9 shown for selection D is what you would see for this program if you were
to change the double variable to a oat variable. (Contrast this with 2147483647 to see the loss of
precision.)
Widening is no guarantee that precision will be preserved
The fact that a type conversion is a widening conversion does not guarantee that there will be no loss
of precision in the conversion. It simply guarantees that the conversion will be allowed by the compiler. In
some cases, such as that shown above (p. 67) , an assignment compatible conversion can result in a loss of
precision, so you always need to be aware of what you are doing.
Back to Question 2 (p. 38)
3.3.7.15 Answer 1
E. 7.0
3.3.7.15.1 Explanation 1
Declare but don't initialize a double variable
The method named doAsg begins by declaring a double variable named myVar without initializing
it.
Use the simple assignment operator
The simple assignment operator (=) is then used to assign the double value 3.0 to the variable.
Following the execution of that statement, the variable contains the value 3.0.
Use the arithmetic/assignment operator
The next statement uses the combined arithmetic/assignment operator (+=) to add the value 4.0 to the
value of 3.0 previously assigned to the variable. The following two statements are functionally equivalent:
note:
myVar += 4.0;
• +=
• -=
• *=
• /=
• %=
In all ve cases, you can construct a functionally equivalent arithmetic and assignment statement in the
same way that I constructed the functionally equivalent statement for += above.
Back to Question 1 (p. 37)
-end-
· 1 (p. 69) , 2 (p. 70) , 3 (p. 71) , 4 (p. 72) , 5 (p. 73) , 6 (p. 74) , 7 (p. 75) , 8 (p. 76) , 9 (p. 77)
, 10 (p. 78) , 11 (p. 79) , 12 (p. 80) , 13 (p. 81) , 14 (p. 82) , 15 (p. 83)
3.4.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 84) to easily nd and view the listings while you are reading about them.
3.4.3 Questions
3.4.3.1 Question 1 .
Given: The use of String concatenation in the argument list of the call to the println method in the
program shown in Listing 1 (p. 70) will cause seven items to be displayed on the screen, separated by spaces.
True or False? The program produces the output shown below:
note:
class Worker{
public void doRelat(){
int a = 1, b = 2, c = 3, d = 2;
System.out.println(
(a == b) + " " +
(b == d) + " " +
(b != d) + " " +
(c < a) + " " +
(b <= d) + " " +
(c > d) + " " +
(a >= c));
}//end doRelat()
}//end class definition
3.40
3.4.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 71) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. false
class Worker{
public void doRelat(){
Dummy x = new Dummy();
Dummy y = new Dummy();
System.out.println(x == y);
}//end doRelat()
}//end class definition
class Dummy{
int x = 5;
double y = 5.5;
String z = "A String Object";
}//end class Dummy
3.41
3.4.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 72) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. false
class Worker{
public void doRelat(){
Dummy x = new Dummy();
Dummy y = new Dummy();
System.out.println(x.equals(y));
}//end doRelat()
}//end class definition
class Dummy{
int x = 5;
double y = 5.5;
String z = "A String Object";
}//end class Dummy
3.42
3.4.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 73) ?
• A. Compiler Error
• B. Runtime Error
• C. true false
• D. false true
• E. true true
class Worker{
public void doRelat(){
Dummy x = new Dummy();
Dummy y = x;
System.out.println(
(x == y) + " " + x.equals(y));
}//end doRelat()
}//end class definition
class Dummy{
int x = 5;
double y = 5.5;
String z = "A String Object";
}//end class Dummy
3.43
3.4.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 74) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. false
class Worker{
public void doRelat(){
Dummy x = new Dummy();
Dummy y = new Dummy();
System.out.println(x > y);
}//end doRelat()
}//end class definition
class Dummy{
int x = 5;
double y = 5.5;
String z = "A String Object";
}//end class Dummy
3.44
3.4.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 75) ?
• A. Compiler Error
• B. Runtime Error
• C. 5 5 8.3 8.3
• D. 6 4 9.3 7.300000000000001
class Worker{
public void doIncr(){
int w = 5, x = 5;
double y = 8.3, z = 8.3;
w++;
x--;
y++;
z--;
3.45
3.4.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 76) ?
• A. Compiler Error
• B. Runtime Error
• C. Hello
• D. None of the above
class Worker{
public void doIf(){
int x = 5, y = 6;
if(x - y){
System.out.println("Hello");
}//end if
}//end doIf()
}//end class definition
3.46
3.4.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 77) ?
• A. Compiler Error
• B. Runtime Error
• C. World
• D. Hello World
• E. None of the above
class Worker{
public void doIf(){
int x = 5, y = 6;
if(x < y){
System.out.print("Hello ");
}//end if
System.out.println("World");
}//end doIf()
}//end class definition
3.47
3.4.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 78) ?
• A. Compiler Error
• B. Runtime Error
• C. Hello World
• D. Goodbye World
• E. None of the above
class Worker{
public void doIf(){
int x = 5, y = 6;
if(x == y){
System.out.println(
"Hello World");
}else{
System.out.println(
"Goodbye World");
}//end else
}//end doIf()
}//end class definition
3.48
3.4.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 79) ?
• A. Compiler Error
• B. Runtime Error
• C. x = 4
• D. x = 5
• E. x = 6
• F. x != 4,5,6
• G. None of the above
class Worker{
public void doIf(){
int x = 2;
if(x == 4){
System.out.println("x = 4");
}else if (x == 5){
System.out.println("x = 5");
}else if (x == 6){
System.out.println("x = 6");
}else{
System.out.println("x != 4,5,6");
}//end else
}//end doIf()
}//end class definition
3.49
3.4.3.11 Question 11
What output is produced by the program shown in Listing 11 (p. 80) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 1 2 3 4
• D. 1 2 3 4 5
• E. None of the above
class Worker{
public void doLoop(){
int cnt = 0;
while(cnt<5){
cnt++;
System.out.print(cnt + " ");
cnt++;
}//end while loop
System.out.println("");
}//end doLoop()
}//end class definition
3.50
3.4.3.12 Question 12
What output is produced by the program shown in Listing 12 (p. 81) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 1 2 3 4 5
• D. 1 2 3 4 5 5
• E. None of the above
class Worker{
public void doLoop(){
int cnt;
for(cnt = 0; cnt < 5; cnt++){
System.out.print(cnt + " ");
}//end for loop
System.out.println(cnt + " ");
}//end doLoop()
}//end class definition
3.51
3.4.3.13 Question 13
What output is produced by the program shown in Listing 13 (p. 82) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 1 2 3 4 5
• D. 1 2 3 4 5 5
• E. None of the above
class Worker{
public void doLoop(){
for(int cnt = 0; cnt < 5; cnt++){
System.out.print(cnt + " ");
}//end for loop
System.out.println(cnt + " ");
}//end doLoop()
}//end class definition
3.52
3.4.3.14 Question 14
What output is produced by the program shown in Listing 14 (p. 83) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 1 2 3 3
• D. 0 1 2 3 4
• E. None of the above
class Worker{
public double doLoop(){
for(int cnt = 0; cnt < 5; cnt++){
System.out.print(cnt + " ");
if(cnt == 3){
System.out.println(cnt);
return cnt;
}//end if
}//end for loop
//return 3.5;
}//end doLoop()
}//end class definition
3.53
3.4.3.15 Question 15
What output is produced by the program shown in Listing 15 (p. 84) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 1 2 3 3
• D. 0 1 2 3 4
• E. None of the above
class Worker{
public void doLoop(){
for(int cnt = 0; cnt < 5; cnt++){
System.out.print(cnt + " ");
if(cnt == 3){
System.out.println(cnt);
return;
}//end if
}//end for loop
}//end doLoop()
}//end class definition
3.54
3.4.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.4.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.4.6 Answers
3.4.6.1 Answer 15
C. 0 1 2 3 3
3.4.6.1.1 Explanation 15
No return statement is required
A method with a signature that species a void return type does not require a return statement.
However, such a method may contain a return statement, provided that it is terminated immediately
with a semicolon(no expression between the word return and the semicolon) .
(Every method whose return type is not void must contain at least one return statement.)
Multiple return statements are allowed
Any method may contain any number of return statements provided that they make sense from a
syntax viewpoint, and provided the expression (or lack thereof) between the word return and the
semicolon evaluates to the type specied in the method signature (or a type that will be automatically
converted to the type specied in the method signature) .
A return statement terminates a method immediately
Whenever the execution stream encounters any return statement, the method is terminated immedi-
ately, and control is returned to the method that called that method.
Back to Question 15 (p. 83)
3.4.6.2 Answer 14
A. Compiler Error
3.4.6.2.1 Explanation 14
Missing return statement
This program produces the following compiler error under JDK 1.3:
note:
Even though this program contains a return statement inside the for loop, it is still necessary to place
a return statement at the end of the method to satisfy the compiler. (The one shown in the code is a
comment.)
The method named doLoop must return a value of type double . Apparently the compiler assumes
that the return statement inside the for loop may never be executed (although that isn't true in this
case) .
Both of the return statements must return a value that satises the double type requirement given
in the method signature.
Returning a value of type int in the for loop will satisfy the type requirement because type int
will be automatically converted to type double as it is returned. (Conversion from type int to type
double is a widening conversion.)
Back to Question 14 (p. 82)
3.4.6.3 Answer 13
A. Compiler Error
3.4.6.3.1 Explanation 13
The scope of a local variable
In general, the scope of a local variable extends from the point at which it is declared to the curly brace
that signals the end of the block in which it is declared.
This applies to for loop in an interesting way
While it is allowable to declare a variable within the rst clause of a for loop, the scope of that variable
is limited to the block of code contained in the loop structure.
The variable cannot be accessed outside the loop.
Attempts to access variable out of scope
This program attempts to access the value of the variable named cnt after the loop terminates.
The program displays the following compiler error under JDK 1.3. This error results from the attempt
to display the value of the counter after the loop terminates.
note:
3.4.6.4 Answer 12
C. 0 1 2 3 4 5
3.4.6.4.1 Explanation 12
A simple for loop structure
This program illustrates a simple for loop that displays the value of its counter using a call to the
print method inside the loop.
After the loop terminates, the program displays the value of the counter one last time using a call to
println .
Three clauses separated by semicolons
The rst line of a for loop structure always contains three clauses separated by semicolons.
The rst and third clauses may be empty, but the semicolons are required in any case.
The rst clause ...
The rst clause is executed once and only once at the beginning of the loop.
It can contain just about any valid Java expression.
It can even contain more than one expression with the individual expression separated by commas.
When the rst clause contains more than one expression separated by commas, the expressions are
evaluated in left-to-right order.
The second clause
The second clause is a conditional clause. It must contain an expression that returns a boolean value.
(Actually, this clause can also be empty, in which case it is apparently assumed to be true. This leads
to an innite loop unless there is some code inside the loop to terminate it, perhaps by executing a return
or a break statement.)
An entry-condition loop
The for loop is an entry condition loop, meaning that the conditional expression is evaluated once
immediately after the rst clause is executed, and once per iteration thereafter.
Behavior of the for loop
If the conditional expression returns true, the block of code following the closing parenthesis is executed.
If it returns false, the block of code is skipped, and control passes to the rst executable statement
following the block of code.
(For the case where the block contains only one statement, the matching curly brackets can be omitted.)
The third clause
The third clause can contain none, one, or more valid expressions separated by commas.
If there are more than one, they are evaluated in left-to-right order.
When they are evaluated
The expressions in the third clause are evaluated once during each iteration.
However, it is very important to remember that despite the physical placement of the clause in the rst
line, the expressions in the third clause are not evaluated until after the code in the block has been evaluated.
Typically an update clause
The third clause is typically used to update a counter, but this is not a technical requirement.
This clause can be used for just about any purpose.
However, the counter must be updated somewhere within the block of code or the loop will never termi-
nate.
(Stated dierently, something must occur within the block of code to eventually cause the conditional
expression to evaluate to false. Otherwise, the loop will never terminate on its own. However, it is possible
to execute a return or break within the block to terminate the loop.)
Note the rst output value for this program
Because the update in the third clause is not executed until after the code in the block has been executed,
the rst value displayed (p. 87) by this program is the value zero.
Back to Question 12 (p. 80)
3.4.6.5 Answer 11
E. None of the above
3.4.6.5.1 Explanation 11
And the answer is ...
The output produced by this program is:
135
A simple while loop
This program uses a simple while loop to display the value of a counter, once during each iteration.
Behavior of a while loop
As long as the relational expression in the conditional clause returns true, the block of code immediately
following the conditional clause is executed.
When the relational expression returns false, the block of code following the conditional clause is skipped
and control passes to the next executable statement following that block of code.
An entry-condition loop
Thewhile loop is an entry condition loop, meaning that the test is performed once during each iteration
before the block of code is executed.
If the rst test returns false, the block of code is skipped entirely.
An exit-condition loop
There is another loop, known as a do-while loop, that performs the test after the block of code has
been executed once. This guarantees that the block of code will always be executed at least once.
Just to make things interesting ...
Two statements using the increment operator were placed inside the loop in this program.
Therefore, insofar as the conditional test is concerned, the counter is being incremented by twos. This
causes the output to display the sequence 1 3 5.
Nested while loops
Thewhile loop control structure can contain loops nested inside of loops, which leads to some interesting
behavior.
Back to Question 11 (p. 79)
3.4.6.6 Answer 10
F. x != 4,5,6
3.4.6.6.1 Explanation 10
A multiple-choice structure
This is a form of control structure that is often used to make logical decisions in a multiple-choice sense.
This is a completely general control structure. It can be used with just about any type of data.
A switch structure
There is a somewhat more specialized, control structure named switch that can also be used to make
decisions in a multiple choice sense under certain fairly restrictive conditions.
However, the structure shown in this program can always be used to replace a switch. Therefore, I nd
that I rarely use the switch structure, opting instead for the more general form of multiple-choice structure.
Back to Question 10 (p. 78)
3.4.6.7 Answer 9
D. Goodbye World
3.4.6.7.1 Explanation 9
An if-else control structure
This program contains a simple if-else control structure.
Behavior of if-else structure
If the expression in the conditional clause returns true, the block of code following the conditional clause
is executed, and the block of code following the word else is skipped.
If the expression in the conditional clause returns false, the block of code following the conditional clause
is skipped, and the block of code following the word else is executed.
This program executes the else block
In this program, the expression in the conditional clause returns false.
Therefore, the block of code following the word else is executed, producing the words Goodbye World
on the computer screen.
Can result in very complex structures
While the structure used in this program is relatively simple, it is possible to create very complex control
structures by nesting additional if-else structures inside the blocks of code.
Back to Question 9 (p. 77)
3.4.6.8 Answer 8
D. Hello World
3.4.6.8.1 Explanation 8
A simple if statement
This program contains a simple if statement that
3.4.6.9 Answer 7
A. Compiler Error
3.4.6.9.1 Explanation 7
Not the same as C and C++
Unlike C and C++, which can use an integer numeric expression in the conditional clause of an if
statement, Java requires the conditional clause of an if statement to contain an expression that will return
a boolean result.
Bad conditional expression
That is not the case in this program, and the following compiler error occurs under JDK 1.3:
note:
3.4.6.10 Answer 6
D. 6 4 9.3 7.300000000000001
3.4.6.10.1 Explanation 6
Postx increment and decrement operators
This program illustrates the use of the increment (++) and decrement () operators in their postx form.
Behavior of increment operator
Given a variablex , the following two statements are equivalent:
note:
x++;
x = x + 1;
note:
x--;
x = x - 1;
Inaccurate results
Regarding the program output, you will note that there is a little arithmetic inaccuracy when this program
is executed using JDK 1.3. (The same is still true with JDK version 1.7.)
Ideally, the output value 7.300000000000001 should simply be 7.3 without the very small additional
fractional part, but that sort of thing often happens when using oating types.
Back to Question 6 (p. 74)
3.4.6.11 Answer 5
A. Compiler Error
3.4.6.11.1 Explanation 5
Cannot use > with reference variables
The only relational operator that can be applied to reference variables is the == operator.
As discussed in the previous questions, even then it can only be used to determine if two reference
variables refer to the same object.
This program produces the following compiler error under JDK 1.3:
note:
3.4.6.12 Answer 4
E. true true
3.4.6.12.1 Explanation 4
Two references to the same object
In this case, the reference variables named x and y both refer to the same object. Therefore, when
tested for equality, using either the == operator or the default equals method, the result is true.
Back to Question 4 (p. 72)
3.4.6.13 Answer 3
D. false
3.4.6.13.1 Explanation 3
Read question 2
In case you skipped it, you need to read the explanation for the answer to Question 2 (p. 70) before
reading this explanation.
Objects appear to be equal
These two objects are of the same type and contain the same values. Why are they reported as not being
equal?
Did not override the equals method
When I dened the class namedDummy used in the programs for Question 2 (p. 70) and Question 3
equals .
(p. 71) , I did not override the method named
Therefore, my class named Dummy simply inherited the default version of the method named equals
that is dened in the class named Object .
3.4.6.14 Answer 2
D. false
3.4.6.14.1 Explanation 2
Use of the == operator with references to objects
This program illustrates an extremely important point about the use of the == operator with objects
and reference variables containing references to objects.
You cannot determine...
You cannot determine if two objects are "equal" by applying the == operator to the reference variables
containing references to those objects.
Rather, that test simply determines if two reference variables refer to the same object.
Two references to the same object
Obviously, if there is only one object, referred to by two dierent reference variables, then it is "equal"
to itself.
Objects of same type containing same instance values
On the other hand, two objects of the same type could contain exactly the same data values, but this
test would not indicate that they are "equal." (In fact, that is the case in this program.)
So, how do you test two objects for equal?
In order to determine if two objects are "equal", you must devise a way to compare the types of the two
objects and actually compare the contents of one object to the contents of the other object. Fortunately,
there is a standard framework for doing this.
The equals method
In particular, the class named Object denes a default version of a method named equals that is
inherited by all other classes.
Class author can override the equals method
The intent is that the author of a new class can override the equals method so that it can be called to
determine if two objects instantiated from that class are "equal."
What does "equal" mean for objects?
Actually, that is up to the author of the class to decide.
After having made that decision, the author of the class writes that behavior into her overridden version
of the method named equals .
Back to Question 2 (p. 70)
3.4.6.15 Answer 1
The answer is True.
3.4.6.15.1 Explanation 1
Not much to explain here
There isn't much in the way of an explanation to provide for this program.
Evaluate seven relational expressions
Each of the seven relational expressions in the argument list for the println method is evaluated and
boolean value.
returns either true or false as a
Concatenate the individual results, separated by a space
The seven boolean results are concatenated, separated by space characters, and displayed on the
computer screen.
Brief description of the relational operators
Just in case your aren't familiar with the relational operators, here is a brief description.
Each of these operators returns the boolean value true if the specied condition is met. Otherwise, it
returns false.
note:
· 1 (p. 94) , 2 (p. 94) , 3 (p. 95) , 4 (p. 96) , 5 (p. 97) , 6 (p. 98) , 7 (p. 99) , 8 (p. 100) , 9 (p.
101) , 10 (p. 102)
3.5.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 103) to easily nd and view the listings while you are reading about them.
3.5.3 Questions
3.5.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 94) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. B
• E. None of the above
class Worker{
public void doLogical(){
int x = 5, y = 6;
if((x > y) || (y < x/0)){
System.out.println("A");
}else{
System.out.println("B");
}//end else
}//end doLogical()
}//end class definition
3.55
3.5.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 95) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. B
• E. None of the above
class Worker{
public void doLogical(){
int x = 5, y = 6;
if((x < y) || (y < x/0)){
System.out.println("A");
}else{
System.out.println("B");
}//end else
}//end doLogical()
}//end class definition
3.56
3.5.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 96) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. B
• E. None of the above
class Worker{
public void doLogical(){
int x = 5, y = 6;
if(!(x < y) && !(y < x/0)){
System.out.println("A");
}else{
System.out.println("B");
}//end else
}//end doLogical()
}//end class definition
3.57
3.5.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 96) ?
• A. Compiler Error
• B. Runtime Error
• C. true
• D. 1
• E. None of the above
class Worker{
public void doCast(){
boolean x = true;
int y = (int)x;
System.out.println(y);
}//end doCast()
}//end class definition
3.58
3.5.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 98) ?
• A. Compiler Error
• B. Runtime Error
• C. 4 -4
• D. 3 -3
• E. None of the above
class Worker{
public void doCast(){
double w = 3.7;
double x = -3.7;
int y = (int)w;
int z = (int)x;
System.out.println(y + " " + z);
}//end doCast()
}//end class definition
3.59
3.5.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 99) ?
• A. Compiler Error
• B. Runtime Error
• C. 4 -3
• D. 3 -4
• E. None of the above
class Worker{
public void doCast(){
double w = 3.5;
double x = -3.499999999999;
System.out.println(doIt(w) +
" " +
doIt(x));
}//end doCast()
3.60
3.5.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 100) ?
• A. Compiler Error
• B. Runtime Error
• C. 3.5/9/true
• D. None of the above
class Worker{
public void doConcat(){
double w = 3.5;
int x = 9;
boolean y = true;
String z = w + "/" + x + "/" + y;
System.out.println(z);
}//end doConcat()
}// end class
3.61
3.5.3.8 Question 8
Which of the following best approximates the output from the program shown in Listing 8 (p. 101) ?
• A. Compiler Error
• B. Runtime Error
• C. Dummy@273d3c
• D. Joe 35 162.5
class Worker{
public void doConcat(){
Dummy y = new Dummy();
System.out.println(y);
}//end doConcat()
}// end class
class Dummy{
private String name = "Joe";
private int age = 35;
private double weight = 162.5;
}//end class dummy
3.62
3.5.3.9 Question 9
Which of the following best approximates the output from the program shown in Listing 9 (p. 102) ?
• A. Compiler Error
• B. Runtime Error
• C. C. Dummy@273d3c
• D. Joe Age = 35 Weight = 162.5
class Worker{
public void doConcat(){
Dummy y = new Dummy();
System.out.println(y);
}//end doConcat()
}// end class
class Dummy{
private String name = "Joe";
private int age = 35;
private double weight = 162.5;
3.63
3.5.3.10 Question 10
Which of the following best approximates the output from the program shown in Listing 10 (p. 103) ?
(Note the use of the constructor for the Date class that takes no parameters.)
• A. Compiler Error
• B. Runtime Error
• C. Sun Dec 02 17:35:00 CST 2012 1354491300781
• D. Thur Jan 01 00:00:00 GMT 1970
• 0
• None of the above
import java.util.*;
public class Ap048{
public static void main(
String args[]){
new Worker().doConcat();
}//end main()
}//end class definition
class Worker{
public void doConcat(){
Date w = new Date();
String y = w.toString();
System.out.print(y);
System.out.println(" " + w.getTime());
}//end doConcat()
}// end class
3.64
3.5.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.5.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.5.6 Answers
3.5.6.1 Answer 10
C. Sun Dec 02 17:35:00 CST 2012 1354491300781
3.5.6.1.1 Explanation 10
The noarg constructor for the Date class
The Date class has a constructor that takes no parameters and is described in the documentation as
follows:
"Allocates a Date object and initializes it so that it represents the time at which it was allocated,
measured to the nearest millisecond."
In other words, this constructor can be used to instantiate a Date object that represents the current
date and time according to the system clock.
A property named time of type long
The actual date and time information encapsulated in a Date object is apparently stored in a property
named time as a long integer.
Milliseconds since the epoch
The long integer encapsulated in a Date object represents the total number of milliseconds for the
encapsulated date and time, relative to the epoch, which was Jan 01 00:00:00 GMT 1970.
Earlier dates are represented as negative values. Later dates are represented as positive values.
An overridden toString method
Date class has an overridden toString
An object of the method that converts the value in milliseconds
to a form that is more useful for a human observer, such as:
Sun Dec 02 17:35:00 CST 2012
Instantiate a Date object with the noarg constructor
This program instantiates an object of the Date class using the constructor that takes no parameters.
Call the overridden toString method
Then it calls the overridden toString method to populate a String object that represents the Date
object.
Following this, it displays that String object by calling the print method, producing the rst part of
the output shown above. (The actual date and time will vary depending on when the program is executed.)
Get the time property value
getTime method to get and display the value of the time
Then it calls the property.
This is a representation of the same date and time shown above (p. 104) , but in milliseconds:
1354491300781
Back to Question 10 (p. 102)
3.5.6.2 Answer 9
D. Joe Age = 35 Weight = 162.5
3.5.6.2.1 Explanation 9
Upgraded program from Question 8
The program used for this question is an upgrade to the program that was used for Question 8 (p. 100) .
Dummy class overrides the toString method
In particular, in this program, the class namedDummy overrides the toString method in such a
way as to return a String representing the object that would be useful to a human observer.
The String that is returned contains the values of the instance variables of the object: name, age, and
weight.
Overridden toString method code
The overriddentoString method for the Dummy class is shown below for easy reference.
3.5.6.3 Answer 8
C. Dummy@273d3c
3.5.6.3.1 Explanation 8
Display an object of the Dummy class
This program instantiates a new object of the Dummy class, and passes that object's reference to
the method named println .
The purpose of the println method is to display a representation of the new object that is meaningful
to a human observer. In order to do so, it requires a String representation of the object.
The toString method
The class named Object denes a default version of a method named toString .
All classes inherit the toString method.
A child of the Object class
Those classes that extend directly from the class named Object inherit the default version of the
toString method.
Grandchildren of the Object class
Those classes that don't directly extend the class named Object also inherit a version of the toString
method.
May be default or overridden version
toString method may be
The inherited the default version, or it may be an overridden version,
depending on whether the method has been overridden in a superclass of the new class.
The purpose of the toString method
toString method dened in the Object
The purpose of the class is to be overridden in new classes.
The body of the overridden version should return a reference to a String object that represents an
object of the new class.
Whenever a String representation of an object is required
Whenever aString representation of an object is required for any purpose in Java, the toString
method is called on a reference to the object.
The String that is returned by the toString method is taken to be a String that represents the
object.
When toString has not been overridden
When thetoString method is called on a reference to an object for which the method has not been
overridden, the default version of the method is called.
The default String representation of an object
The String returned by the default version consists of the following:
• The name of the class from which the object was instantiated
• The @ character
• A hexadecimal value that is the hashcode value for the object
As you can see, this does not include any information about the values of the data stored in the object.
Other than the name of the class from which the object was instantiated, this is not particularly useful
to a human observer.
Dummy class does not override toString method
Dummy extends the Object class directly, and doesn't override
In this program, the class named
the toString method.
Therefore, when the toString method is called on a reference to an object of the Dummy class, the
String that is returned looks something like the following:
Dummy@273d3c
Note that the six hexadecimal digits at the end will probably be dierent from one program to the next.
Back to Question 8 (p. 100)
3.5.6.4 Answer 7
C. 3.5/9/true
3.5.6.4.1 Explanation 7
More on String concatenation
This program illustrates String concatenation.
The plus (+) operator is what is commonly called an overloaded operator .
What is an overloaded operator?
An overloaded operator is an operator whose behavior depends on the types of its operands.
Plus (+) as a unary operator
The plus operator can be used as either a unary operator or a binary operator. However, as a
unary operator, with only one operand to its right, it doesn't do anything useful. This is illustrated by the
following two statements, which are functionally equivalent.
x = y;
x = +y;
Plus (+) as a binary operator
As a binary operator, the plus operator requires two operands, one on either side. (This is called inx
notation.) When used as a binary operator, its behavior depends on the types of its operands.
Two numeric operands
If both operands are numeric operands, the plus operator performs arithmetic addition.
If the two numeric operands are of dierent types, the narrower operand is converted to the type of the
wider operand, and the addition is performed as the wider type.
Two String operands
If both operands are references to objects of type String , the plus operator creates and returns a new
String object that contains the concatenated values of the two operands.
One String operand and one of another type
If one operand is a reference to an object of type String and the other operand is of some type other
than String , the plus operator causes a new String object to come into existence.
This new String object is a String representation of the non-String operand (such as a value of
type int ) ,
Then it concatenates the two String objects, producing another new String object, which is the
concatenation of the two.
How is the new String operand representing the non-string operand created?
String object that represents the non-String operand
The manner in which it creates the new varies
with the actual type of the operand.
A primitive operand
The simplest case is when the non-String operand is one of the primitive types. In these cases, the
capability already exists in the core programming language to produce a String object that represents the
value of the primitive type.
A boolean operand
For example, if the operand is of type boolean , the new String object that represents the operand
will either contain the word true or the word false.
A numeric operand
If the operand is one of the numeric types, the new String object will be composed of some of the
following:
• numeric characters
• a decimal point character
• minus characters
• plus character
• other characters such as E or e
These characters will be arranged in such a way as to represent the numeric value of the operand to a human
observer.
3.5.6.5 Answer 6
C. 4 -3
3.5.6.5.1 Explanation 6
A rounding algorithm
The method named doIt in this program illustrates an algorithm that can be used with a numeric cast
operator (int) to cause double values to be rounded to the nearest integer.
Dierent than truncation toward zero
Note that this is dierent from simply truncating to the next integer closer to zero (as was illustrated
in Question 5 (p. 97) ) .
Back to Question 6 (p. 98)
3.5.6.6 Answer 5
D. 3 -3
3.5.6.6.1 Explanation 5
Truncates toward zero
When a double value is cast to an int , the fractional part of the double value is discarded.
This produces a result that is the next integer value closer to zero.
This is true regardless of whether the double is positive or negative. This is sometimes referred to as
its "truncation toward zero" behavior.
Not the same as rounding
If each of the values assigned to the variables named w and x in this program were rounded to the
nearest integer, the result would be 4 and -4, not 3 and -3 as produced by the program.
Back to Question 5 (p. 97)
3.5.6.7 Answer 4
A. Compiler Error
3.5.6.7.1 Explanation 4
Cannot cast a boolean type
A boolean type cannot be cast to any other type. This program produces the following compiler error:
note:
3.5.6.8 Answer 3
D. B
3.5.6.8.1 Explanation 3
The logical and operator
The logical and operator shown below
&&
performs an and operation between its two operands, both of which must be of type boolean . If both
operands are true, the operator returns true. Otherwise, it returns false.
The boolean negation operator
The boolean negation operator shown below
is a unary operator, meaning that it always has only one operand. That operand must be of type boolean
, and the operand always appears immediately to the right of the operator.
The behavior of this operator is to change its right operand from true to false, or from false to true.
Evaluation from left to right
Now, consider the following code fragment from this program.
note:
int x = 5, y = 6;
if(!(x < y) && !(y < x/0)){
System.out.println("A");
}else{
System.out.println("B");
}//end else
The individual operands of the logical and operator are evaluated from left to right.
Consider the left operand of the logical and operator that reads:
note:
!(x<y)
(x < y)
In this case, x is less than y , so the expression inside the parentheses evaluates to true.
The following expression is false
note:
!(x < y)
The true result becomes the right operand for the boolean negation operator at this point.
You might think of the state of the evaluation process at this point as being something like
not true .
When the ! operator is applied to the true result, the combination of the two become a false result.
Short-circuit evaluation applies
This, in turn, causes the left operand of the logical and operator to be false .
At that point, the nal outcome of the logical expression has been determined. It doesn't matter whether
the right operand is true or false. The nal result will be false regardless.
No attempt is made to evaluate the right operand
Therefore, no attempt is made to evaluate the right operand of the logical and operator in this case.
No attempt is made to divide the integer variable x by zero, no exception is thrown, and the program
doesn't terminate abnormally. It runs to completion and displays a B on the screen.
Back to Question 3 (p. 95)
3.5.6.9 Answer 2
C. A
3.5.6.9.1 Explanation 2
Short-circuit evaluation
Question 1 (p. 94) was intended to set the stage for this question.
This Question, in combination with Question 1 (p. 94) , is intended to help you understand and remember
the concept of short-circuit evaluation.
What is short-circuit evaluation?
Logical expressions are evaluated from left to right. That is, the left operand of a logical operator is
evaluated before the right operand of the same operator is evaluated.
When evaluating a logical expression, the nal outcome can often be determined without the requirement
to evaluate all of the operands.
Once the nal outcome is determined, no attempt is made to evaluate the remainder of the expression.
This is short-circuit evaluation.
Code from Question 1
Consider the following code fragment from Question 1 (p. 94) :
note:
int x = 5, y = 6;
if((x > y) || (y < x/0)){
...
If either of its operands is true, the operator returns true. Otherwise, it returns false.
Left operand is false
In this particular expression, the value of x is not greater than the value of y . Therefore, the left
operand of the logical or operator is not true.
Right operand must be evaluated
This means that the right operand must be evaluated in order to determine the nal outcome.
Right operand attempts to divide by zero
However, when an attempt is made to evaluate the right operand, an attempt is made to divide x by
zero. This throws an exception, which is not caught and handled by the program, so the program terminates
as described in Question 1 (p. 94) .
Similar code from Question 2
Now consider the following code fragment from Question 2 (p. 94) .
note:
int x = 5, y = 6;
if((x < y) || (y < x/0)){
System.out.println("A");
...
Note that the right operand of the logical or operator still contains an expression that attempts to divide
the integer x by zero.
No runtime error in this case
This program does not terminate with a runtime error. Why not?
And the answer is ...
x is less than y . Therefore, the left operand of the logical or
In this case, operator is true.
Remember the rule for inclusive or
It doesn't matter whether the right operand is true or false. The nal outcome is determined as soon as
it is determined that the left operand is true.
The bottom line
Because the nal outcome has been determined as soon as it is determined that the left operand is true,
no attempt is made to evaluate the right operand.
Therefore, no attempt is made to divide x by zero, and no runtime error occurs.
Short-circuit evaluation
This behavior is often referred to as short-circuit evaluation .
Only as much of a logical expression is evaluated as is required to determine the nal outcome.
Once the nal outcome is determined, no attempt is made to evaluate the remainder of the logical
expression.
This is not only true for the logical or operator, it is also true for the logical and operator, which
consists of two ampersand characters with no space between them.
Back to Question 2 (p. 94)
3.5.6.10 Answer 1
B. Runtime Error
3.5.6.10.1 Explanation 1
Divide by zero
Whenever a Java program attempts to evaluate an expression requiring that a value of one of the integer
types be divided by zero, it will throw an ArithmeticException . If this exception is not caught and
handled by the program, it will cause the program to terminate.
Attempts to divide x by 0
This program attempts to evaluate the following expression:
note:
(y < x/0)
This expression attempts to divide the variable named x by zero. This causes the program to terminate
with the following error message when running under JDK 1.3:
note:
java.lang.ArithmeticException: / by zero
at Worker.doLogical(Ap039.java:13)
at Ap039.main(Ap039.java:6)
· 1 (p. 112) , 2 (p. 113) , 3 (p. 114) , 4 (p. 115) , 5 (p. 117) , 6 (p. 118) , 7 (p. 118) , 8 (p. 119) ,
9 (p. 120) , 10 (p. 121) , 11 (p. 122) , 12 (p. 123) , 13 (p. 124) , 14 (p. 125) , 15 (p. 126)
3.6.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 127) to easily nd and view the listings while you are reading about them.
3.6.3 Questions
3.6.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 113) ?
note:
A. Compiler Error
B. Runtime Error
C. \"Backslash\"->\\\nUnderstand
D. "Backslash"->\
Understand
class Worker{
public void doEscape(){
System.out.println(
"\"Backslash\"->\\\nUnderstand");
}//end doEscape()
}// end class
3.65
3.6.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 114) ?
• A. Compiler Error
• B. Runtime Error
• C. St@273d3c St@256a7c St@720eeb
• D. Tom Dick Harry
• E. None of the above
class Worker{
public void doArrays(){
St[] myArray = {new St("Tom"),
new St("Dick"),
new St ("Harry")};
for(int cnt = 0;
cnt < myArray.length;cnt++){
System.out.print(
myArray[cnt] + " ");
class St{
private String name;
3.66
3.6.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 115) ?
note:
A. Compiler Error
B. Runtime Error
C. 0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
class Worker{
public void doArrays(){
int myArray[3][5];
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
myArray[i][j] = i*j;
}//end inner for loop
}//end outer for loop
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
System.out.print(
myArray[i][j] + " ");
}//end inner for loop
System.out.println("");
}//end outer for loop
}//end doArrays()
}// end class
3.67
3.6.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 116) ?
note:
A. Compiler Error
B. Runtime Error
C. 1 1 1 1 1
1 2 3 4 5
1 3 5 7 9
class Worker{
public void doArrays(){
int myArray[][];
myArray = new int[3][5];
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
myArray[i][j] = i*j + 1;
}//end inner for loop
}//end outer for loop
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
System.out.print(
myArray[i][j] + " ");
}//end inner for loop
System.out.println("");
}//end outer for loop
}//end doArrays()
}// end class
3.68
3.6.3.5 Question 5
What output is produced by program shown in Listing 5 (p. 117) ?
note:
A. Compiler Error
B. Runtime Error
C. -1 -1 -1 -1 -1
-1 -2 -3 -4 -5
-1 -3 -5 -7 -9
class Worker{
public void doArrays(){
int myArray[][];
myArray = new int[3][5];
}//end doArrays()
}// end class
3.69
3.6.3.6 Question 6
What output is produced by program shown in Listing 6 (p. 118) ?
• A. Compiler Error
• B. Runtime Error
• C. 3
• D. None of the above
class Worker{
public void doArrays(){
int[] A = new int[2];
A[0] = 1;
A[1] = 2;
System.out.println(A[0] + A[1]);
}//end doArrays()
}// end class
3.70
3.6.3.7 Question 7
What output is produced by program shown in Listing 7 (p. 119) ?
• A. Compiler Error
• B. Runtime Error
• C. OK
• D. None of the above
import java.awt.Label;
public class Ap055{
public static void main(
String args[]){
new Worker().doArrays();
}//end main()
}//end class definition
class Worker{
public void doArrays(){
Label[] A = new Label[2];
A[0] = new Label("O");
A[1] = new Label("K");
System.out.println(A[0] + A[1]);
}//end doArrays()
}// end class
3.71
3.6.3.8 Question 8
What output is produced by program shown in Listing 8 (p. 120) ?
• A. Compiler Error
• B. Runtime Error
• C. OK
• D. None of the above
import java.awt.Label;
public class Ap056{
public static void main(
String args[]){
new Worker().doArrays();
}//end main()
}//end class definition
class Worker{
public void doArrays(){
Label[] A = new Label[2];
A[0] = new Label("O");
A[1] = new Label("K");
System.out.println(A[0].getText() + A[1].getText());
}//end doArrays()
}// end class
3.72
3.6.3.9 Question 9
What output is produced by program shown in Listing 9 (p. 121) ?
• A. Compiler Error
• B. Runtime Error
• C. 1
• D. None of the above
class Worker{
public void doArrays(){
Integer[] A = new Integer[2];
A[0] = new Integer(1);
System.out.println(
A[1].intValue());
}//end doArrays()
}// end class
3.73
3.6.3.10 Question 10
What output is produced by program shown in Listing 10 (p. 122) ?
note:
A. Compiler Error
B. Runtime Error
C. 0
0 1
0 2 4
class Worker{
public void doArrays(){
int A[][] = new int[3][];
A[0] = new int[1];
A[1] = new int[2];
A[2] = new int[3];
for(int i=0;i<A.length;i++){
for(int j=0;j < A[i].length;j++){
System.out.print(
A[i][j] + " ");
}//end inner for loop
System.out.println("");
}//end outer for loop
}//end doArrays()
}// end class
3.74
3.6.3.11 Question 11
What output is produced by the program shown in Listing 11 (p. 123) ?
• A. Compiler Error
• B. Runtime Error
• C. Zero One Two
• D. None of the above
class Worker{
public void doArrays(){
Object[] A = new Object[3];
//Note that there is a simpler and
// better way to do the following
// but it won't illustrate my point
// as well as doing it this way.
A[0] = new String("Zero");
A[1] = new String("One");
A[2] = new String("Two");
3.75
3.6.3.12 Question 12
What output is produced by program shown in Listing 12 (p. 124) ?
• A. Compiler Error
• B. Runtime Error
• C. Zero 1 2.0
• D. None of the above.
class Worker{
public void doArrays(){
Object[] A = new Object[3];
//Note that there is a simpler and
// better way to do the following
// but it won't illustrate my point
// as well as doing it this way.
A[0] = new String("Zero");
A[1] = new Integer(1);
A[2] = new Double(2.0);
3.76
3.6.3.13 Question 13
What output is produced by program shown in Listing 13 (p. 125) ?
• A. Compiler Error
• B. Runtime Error
• C. Zero 1 2.0
• D. None of the above.
class Worker{
public void doArrays(){
Object[] A = new Object[3];
//Note that there is a simpler and
// better way to do the following
// but it won't illustrate my point
// as well as doing it this way.
A[0] = new String("Zero");
A[1] = new Integer(1);
A[2] = new MyClass(2.0);
class MyClass{
private double data;
3.77
3.6.3.14 Question 14
What output is produced by program shown in Listing 14 (p. 126) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
Object[] A = new Object[2];
A[0] = new MyClass(1.0);
A[1] = new MyClass(2.0);
System.out.println(
A[0].getData() + " " +
A[1].getData());
}//end doArrays()
}// end class
class MyClass{
private double data;
3.78
3.6.3.15 Question 15
What output is produced by program shown in Listing 15 (p. 127) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
Object[] A = new Object[2];
A[0] = new MyClass(1.0);
A[1] = new MyClass(2.0);
System.out.println(
((MyClass)A[0]).getData() + " "
+ ((MyClass)A[1]).getData());
}//end doArrays()
}// end class
class MyClass{
private double data;
3.79
3.6.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.6.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.6.6 Answers
3.6.6.1 Answer 15
C. 1.0 2.0
3.6.6.1.1 Explanation 15
This is an upgrade of the program from Question 14 (p. 125) . This program applies the proper downcast
operator to the references extracted from the array of type Object before attempting to call the method
named getData on those references. (For more information, see the discussion of Question 14 (p. 125)
.)
As a result of applying a proper downcast, the program compiles and runs successfully.
Back to Question 15 (p. 126)
3.6.6.2 Answer 14
A. Compiler Error
3.6.6.2.1 Explanation 14
Storing references in a generic array of type Object
This program stores references to two objects instantiated from a new class named MyClass in the
elements of an array object of declared type Object . That is OK.
Calling a method on the references
Then the program extracts the references to the two objects and attempts to call the method named
getData on each of the references. That is not OK.
Downcast is required
Because the method named getData is not dened in the class named Object , in order to call this
method on references extracted from an array of type Object , it is necessary to downcast the references
to the class in which the method is dened. In this case, the method is dened in the new class named
MyClass (but it could be dened in an intermediate class in the class hierarchy if the new class extended
some class further down the hierarchy) .
Here is a partial listing of the compiler error produced by this program:
note:
3.6.6.3 Answer 13
D. None of the above.
3.6.6.3.1 Explanation 13
The array object of type Object in this program is capable of storing a reference to a new object instantiated
from the new class named MyClass . However, because the new class does not override the toString
method, when a string representation of the new object is displayed, the string representation is created
using the version of the toString method that is inherited from the Object class. That causes this
program to produce an output similar to the following:
Zero 1 MyClass@273d3c
Back to Question 13 (p. 124)
3.6.6.4 Answer 12
C. Zero 1 2.0
3.6.6.4.1 Explanation 12
A type-generic array object
As explained in Question 11 (p. 122) , an array object of the type Object is a generic array that can
be used to store references to objects instantiated from any class.
Storing mixed reference types
This program instantiates objects from the classes String , Integer , and Double , and stores those
object's references in the elements of an array of type Object . Then the program accesses the references
and uses them to display string representations of each of the objects.
Polymorphic behavior applies
Once again, polymorphic behavior involving overridden versions of the toString method were involved
and it was not necessary to downcast the references to their true type to display string representations of
the objects.
Back to Question 12 (p. 123)
3.6.6.5 Answer 11
C. Zero One Two
3.6.6.5.1 Explanation 11
Storing references to subclass types
When you create an array object for a type dened by a class denition, the elements of the array can
be used to store references to objects of that class or any subclass of that class.
A type-generic array object
All classes in Java are subclasses of the class named Object . This program creates an array object
with the declared type being type Object . An array of type Object can be used to store references to
objects instantiated from any class.
After creating the array object, this program instantiates three objects of the class String and stores
those object's references in the elements of the array. (As I pointed out in the comments, there is a simpler
and better way to instantiate String objects, but it wouldn't illustrate my point as well as doing the
way that I did.)
Sometimes you need to downcast
Object can
Although an array of type be used to store references to objects of any type (including
mixed types and references to other array objects) , you will sometimes need to downcast those references
back to their true type once you extract them from the array and attempt to use them for some purpose.
Polymorphic behavior applies here
toString method is dened in the Object class and overridden
For this case, however, because the
in the String class, polymorphic behavior applies and it is not necessary to downcast the references to
type String in order to be able to convert them to strings and display them.
Back to Question 11 (p. 122)
3.6.6.6 Answer 10
note:
C. 0
0 1
0 2 4
3.6.6.6.1 Explanation 10
Defer size specication for secondary arrays
It is not necessary to specify the sizes of the secondary arrays when you create a multi-dimensional array
in Java. Rather, since the elements in the primary array simply contain references to other array objects
(or null by default) , you can defer the creation of those secondary array objects until later.
Independent array objects
When you do nally create the secondary arrays, they are essentially independent array objects (except
for the requirement for type commonality among them) .
Ragged arrays
ragged array .
Each individual secondary array can be of any size, and this leads to the concept of a
(On a two-dimensional basis, a ragged array might be thought of as a two-dimensional array where each
row can have a dierent number of columns.)
This program creates, populates, and displays the contents of such a two-dimensional ragged array.
Although this program creates a two-dimensional array that is triangular in shape, even that is not a
requirement. The number of elements in each of the secondary arrays need have no relationship to the
number of elements in any of the other secondary arrays.
Back to Question 10 (p. 121)
3.6.6.7 Answer 9
B. Runtime Error
3.6.6.7.1 Explanation 9
NullPointerException
The following code fragment shows that this program attempts to perform an illegal operation on the
value accessed from the array object at index 1.
note:
note:
java.lang.NullPointerException
at Worker.doArrays(Ap057.java:14)
at Ap057.main(Ap057.java:6)
This is a common programming error, and most Java programmers have seen an error message involving a
NullPointerException several (perhaps many) times during their programming careers.
Back to Question 9 (p. 120)
3.6.6.8 Answer 8
C. OK
3.6.6.8.1 Explanation 8
Success at last
This program nally gets it all together and works properly. In particular, after accessing the reference
values stored in each of the elements, the program does something legal with those values.
Call methods on the object's references
In this case, the code calls one of the public methods belonging to the objects referred to by the reference
values stored in the array elements.
note:
System.out.println(A[0].getText() + A[1].getText());
The getText method that is called, returns the contents of the Label object as type String . This
makes it possible to perform String concatenation on the values returned by the method, so the program
compiles and executes properly.
Back to Question 8 (p. 119)
3.6.6.9 Answer 7
A. Compiler Error
3.6.6.9.1 Explanation 7
Java arrays may seem dierent to you
For all types other than the primitive types, you may nd the use of arrays in Java to be considerably
dierent from what you are accustomed to in other programming languages. There are a few things that
you should remember.
Array elements may contain default values
If the declared type of an array is one of the primitive types, the elements of the array contain values
of the declared type. If you have not initialized those elements or have not assigned specic values to the
elements, they will contain default values.
The default values
You need to know that:
• The default for numeric primitive types is the zero value for that type
• The default for the boolean type is false
• The default for the char type is a 16-bit unsigned integer, all of whose bits have a zero value
(sometimes called a null character)
• The default value for reference types is null , not to be confused with the null character above.
(An array element that contains null doesn't refer to an object.)
Arrays of references
If the declared type for the array is not one of the primitive types, the elements in the array are actually
reference variables. Objects are never stored directly in a Java array. Only references to objects are stored
in a Java array.
If the array type is the name of a class ...
If the declared type is the name of a class, references to objects of that class or any subclass of that class
can be stored in the elements of the array.
If the array type is the name of an interface ...
If the declared type is the name of an interface, references to objects of any class that implements the
interface, or references to objects of any subclass of a class that implements the interface can be stored in
the elements of the array.
note:
note:
note:
System.out.println(A[0] + A[1]);
The compiler produces the following error message:
note:
3.6.6.10 Answer 6
C. 3
3.6.6.10.1 Explanation 6
Once you create an array object for a primitive type in Java, you can treat the elements of the array pretty
much as you would treat the elements of an array in other programming languages. In particular, a statement
such the following can be used to assign a value to an indexed element in an array referred to by a reference
variable named A .
note:
A[1] = 2;
Similarly, when you reference an indexed element in an expression such as the following, the value stored in
the element is used to evaluate the expression.
note:
System.out.println(A[0] + A[1]);
For all Java arrays, you must remember to create the new array object and to store the array object's
reference in a reference variable of the correct type. Then you can use the reference variable to gain access
to the elements in the array.
Back to Question 6 (p. 118)
3.6.6.11 Answer 5
B. Runtime Error
3.6.6.11.1 Explanation 5
Good fences make good neighbors
One of the great things about an array object in Java is that it knows how to protect its boundaries.
Unlike some other currently popular programming languages, if your program code attempts to access a
Java array element outside its boundaries, an exception will be thrown. If your program doesn't catch and
handle the exception, the program will be terminated.
Abnormal termination
While experiencing abnormal program termination isn't all that great, it is better than the alternative
of using arrays whose boundaries aren't protected. Programming languages that don't protect the array
boundaries simply overwrite other data in memory whenever the array boundaries are exceeded.
Attempt to access out of bounds element
for loop in the following fragment
The code in the attempts to access the array element at the index
value 5. That index value is out of bounds of the array.
note:
Because that index value is outside the boundaries of the array, an ArrayIndexOutOfBoundsException
is thrown. The exception isn't caught and handled by program code, so the program terminates abnormally
at runtime.
This program also illustrates that it is usually better to use the length property of an array to control
iterative loops than to use hard-coded limit values, which may be coded erroneously.
Back to Question 5 (p. 117)
3.6.6.12 Answer 4
note:
C. 1 1 1 1 1
1 2 3 4 5
1 3 5 7 9
3.6.6.12.1 Explanation 4
A two-dimensional array
This program illustrates how to create, populate, and process a two-dimensional array with three rows
and ve columns.
(As mentioned earlier, a Java programmer who understands the ne points of the language probably
wouldn't call this a two-dimensional array. Rather, this is a one-dimensional array containing three elements.
Each of those elements is a reference to a one-dimensional array containing ve elements. That is the more
general way to think of Java arrays.)
The following code fragment creates the array, using one of the acceptable formats discussed in Question
3 (p. 114) .
note:
int myArray[][];
myArray = new int[3][5];
note:
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
myArray[i][j] = i*j + 1;
}//end inner for loop
}//end outer for loop
This is where the analogy of a two-dimensional array falls apart. It is much easier at this point to think in
terms of a three-element primary array, each of whose elements contains a reference to a secondary array
containing ve elements. (Note that in Java, the secondary arrays don't all have to be of the same size.
Hence, it is possible to create odd-shaped multi-dimensional arrays in Java.)
Using the length property
Pay special attention to the two chunks of code that use the length properties of the arrays to determine
the number of iterations for each of the for loops.
The rst chunk determines the number of elements in the primary array. In this case, the length property
contains the value 3.
The second chunk determines the number of elements in the secondary array that is referred to by the
contents of the element at index 0 in the primary array. (Think carefully about what I just said.)
In this case, the length property of the secondary array contains the value 5.
Putting data into the secondary array elements
The code interior to the inner loop simply calculates some numeric values and stores those values in the
elements of the three secondary array objects.
Let's look at a picture
Here is a picture that attempts to illustrate what is really going on here. I don't know if it will make
sense to you or not, but hopefully, it won't make the situation any more confusing than it might already be.
note:
[->] [1][1][1][1][1]
[->] [1][2][3][4][5]
[->] [1][3][5][7][9]
note:
for(int i=0;i<myArray.length;i++){
for(int j=0;
j<myArray[0].length;j++){
System.out.print(
myArray[i][j] + " ");
}//end inner for loop
System.out.println("");
}//end outer for loop
In this case, the code in the inner loop accesses the contents of the individual elements in the three ve-
element arrays and displays those contents. If you understand the earlier code in this program, you shouldn't
have any diculty understanding the code in this fragment.
Back to Question 4 (p. 115)
3.6.6.13 Answer 3
A. Compiler Error
3.6.6.13.1 Explanation 3
An incorrect statement
The following statement is not the proper way to create an array object in Java.
note:
int myArray[3][5];
This statement caused the program to fail to compile, producing several error messages.
What is the correct syntax?
There are several dierent formats that can be used to create an array object in Java. One of the
acceptable ways was illustrated by the code used in Question 2 (p. 113) . Three more acceptable formats
are shown below.
note:
int myArrayC[][];
myArrayC = new int[3][5];
a reference variable capable of holding a reference to a one-dimensional array object, whose elements are
capable of holding references to other array objects.)
Making the two steps obvious
A third acceptable format, also shown above, separates the process into two steps.
One statement in the third format declares a reference variable capable of holding a reference to a two-
dimensional array object containing data of type int . When that statement nishes executing, the reference
variable exists, but it doesn't refer to an actual array object. The next statement creates an array object
and assigns that object's reference to the reference variable.
Back to Question 3 (p. 114)
3.6.6.14 Answer 2
D. Tom Dick Harry
3.6.6.14.1 Explanation 2
An array is an object in Java
An array is a special kind of object in Java. Stated dierently, all array structures are encapsulated in
objects in Java. Further. all array structures are one-dimensional. I often refer to this special kind of object
as an array object .
An array object always has a property named length . The value of the length property is always
equal to the number of elements in the array. Thus, a program can always determine the size of an array be
examining its length property.
Instantiating an array object
An array object can be instantiated in at least two dierent ways:
1. By using the new operator in conjunction with the type of data to be stored in the array.
2. By specifying an initial value for every element in the array, in which case the new operator is not
used.
This program uses the second of the two ways listed above.
Declaring a reference variable for an array object
The following code fragment was extracted from the method named doArrays().
note:
The code to the left of the assignment operator declares a reference variable named myArray . This
reference variable is capable of holding a reference to an array object that contains an unspecied number
of references to objects instantiated from the class named St (or any subclass of the class named St) .
Note the square brackets
You should note the square brackets in the declaration of the reference variable in the above code (the
declaration of a reference variable to hold a reference to an ordinary object doesn't include square brackets)
.
Create the array object
The code to the right of the assignment operator in the above fragment causes the new array object to
come into being. Note that the new operator is not used to create the array object in this case. (This
is one of the few cases in Java, along with a literal String object, where it is possible to create a new
object without using either the new operator or the newInstance method of the class whose name is
Class .)
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
139
note:
for(int cnt = 0;
cnt < myArray.length;
cnt++){
System.out.print(
myArray[cnt] + " ");
note:
class St{
private String name;
note:
This version causes the value in the String object, referred to by the instance variable named name ,
to be returned when it is necessary to produce a String representation of the object.
Back to Question 2 (p. 113)
3.6.6.15 Answer 1
The answer is item D, which reads as follows:
note:
"Backslash"->\
Understand
3.6.6.15.1 Explanation 1
Don't confuse the compiler
If you include certain characters inside a literal String , you will confuse the compiler. For example, if
you simply include a quotation mark (") inside a literal String , the compiler will interpret that as the end
of the string. From that point on, everything will be out of synchronization. Therefore, in order to include
a quotation mark inside a literal string, you must precede it with a backslash character like this:
\"
Multiple lines
If you want your string to comprise two or more physical lines, you can include a newline code inside a
String by including the following in the string:
\n
Escape character sequences
These character sequences are often referred to as escape character sequences . Since the backslash is
used as the rst character in such a sequence, if you want to include a backslash in a literal string, you must
do it like this:
\\
There are some other escape sequences used in Java as well. You would do well to learn how to use them
before going to an interview for a job as a Java programmer.
Back to Question 1 (p. 112)
-end-
· 1 (p. 141) , 2 (p. 142) , 3 (p. 142) , 4 (p. 143) , 5 (p. 144) , 6 (p. 145) , 7 (p. 146) , 8 (p. 149) ,
9 (p. 151) , 10 (p. 153) , 11 (p. 153) , 12 (p. 154) , 13 (p. 155) , 14 (p. 156) , 15 (p. 158)
3.7.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 158) to easily nd and view the listings while you are reading about them.
3.7.3 Questions
3.7.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 141) ?
• A. Compiler Error
• B. Runtime Error
• C. I'm OK
• D. None of the above
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
System.out.println("I'm OK");
}//end doArrays()
}// end class
3.80
3.7.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 142) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
System.out.println(
B[0] + " " + B[1]);
}//end doArrays()
}// end class
3.81
3.7.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 143) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
double C = (double)B;
System.out.println(
C[0] + " " + C[1]);
}//end doArrays()
}// end class
3.82
3.7.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 144) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
double[] C = (double[])B;
System.out.println(
C[0] + " " + C[1]);
}//end doArrays()
}// end class
3.83
3.7.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 145) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. None of the above.
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
String[] C = (String[])B;
System.out.println(
C[0] + " " + C[1]);
}//end doArrays()
}// end class
3.84
3.7.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 146) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
Subclass[] A = new Subclass[2];
A[0] = new Subclass(1);
A[1] = new Subclass(2);
System.out.println(
A[0] + " " + A[1]);
}//end doArrays()
}// end class
class Superclass{
private int data;
public Superclass(int data){
this.data = data;
}//end constructor
3.85
3.7.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 148) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
Subclass[] A = new Subclass[2];
A[0] = new Subclass(1);
A[1] = new Subclass(2);
Superclass[] B = A;
System.out.println(
B[0] + " " + B[1]);
}//end doArrays()
}// end class
class Superclass{
private int data;
public Superclass(int data){
this.data = data;
}//end constructor
3.86
3.7.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 150) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
Superclass[] A = new Superclass[2];
A[0] = new Superclass(1);
A[1] = new Superclass(2);
Subclass[] B = (Subclass[])A;
System.out.println(
B[0] + " " + B[1]);
}//end doArrays()
}// end class
class Superclass{
private int data;
public Superclass(int data){
this.data = data;
}//end constructor
3.87
3.7.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 152) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
Subclass[] A = new Subclass[2];
A[0] = new Subclass(1);
A[1] = new Subclass(2);
Superclass[] B = A;
Subclass[] C = (Subclass[])B;
System.out.println(
C[0] + " " + C[1]);
}//end doArrays()
}// end class
class Superclass{
private int data;
public Superclass(int data){
this.data = data;
}//end constructor
3.88
3.7.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 153) ?
• A. Compiler Error
• B. Runtime Error
• C. 1.0 2.0
• D. D. None of the above
class Worker{
public void doArrays(){
double[] A = new double[2];
A[0] = 1.0;
A[1] = 2.0;
Object B = A;
System.out.println(
((double[])B)[0] + " " +
((double[])B)[1]);
}//end doArrays()
}// end class
3.89
3.7.3.11 Question 11
What output is produced by the program shown in Listing 11 (p. 154) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
int[] A = new int[2];
A[0] = 1;
A[1] = 2;
double[] B = (double[])A;
System.out.println(
B[0] + " " + B[1]);
}//end doArrays()
}// end class
3.90
3.7.3.12 Question 12
What output is produced by the program shown in Listing 12 (p. 155) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
int[] B = returnArray();
for(int i = 0; i < B.length;i++){
System.out.print(B[i] + " ");
}//end for loop
System.out.println();
}//end doArrays()
3.91
3.7.3.13 Question 13
What output is produced by the program shown in Listing 13 (p. 156) ?
note:
A. Compiler Error
B. Runtime Error
C. 0 0 0
0 1 2
class Worker{
public void doArrays(){
int[] A[];
A = new int[2][3];
}//end doArrays()
}// end class
3.92
3.7.3.14 Question 14
What output is produced by the program shown in Listing 14 (p. 157) ?
• A. Compiler Error
• B. Runtime Error
• C. 1 2
• D. None of the above
class Worker{
public void doArrays(){
Subclass[] A = new Subclass[2];
A[0] = new Subclass(1);
A[1] = new Subclass(2);
Object X = A;
Superclass B = A;
Subclass[] C = (Subclass[])B;
Subclass[] Y = (Subclass[])X;
System.out.println(
C[0] + " " + Y[1]);
}//end doArrays()
}// end class
class Superclass{
private int data;
public Superclass(int data){
this.data = data;
}//end constructor
3.93
3.7.3.15 Question 15
What output is produced by the program shown in Listing 15 (p. 158) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 0.0 false 0
• D. None of the above
class Worker{
public void doArrays(){
int[] A = new int[1];
double[] B = new double[1];
boolean[] C = new boolean[1];
int[] D = new int[0];
}//end doArrays()
}// end class
3.94
3.7.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.7.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.7.6 Answers
3.7.6.1 Answer 15
C. 0 0.0 false 0
3.7.6.1.1 Explanation 15
You can initialize array elements
You can create a new array object and initialize its elements using statements similar to the following:
note:
3.7.6.2 Answer 14
A. Compiler Error
3.7.6.2.1 Explanation 14
Assigning array reference to type Object
As you learned in an earlier module, you can assign an array object's reference to an ordinary reference
variable of the type Object . It is not necessary to indicate that the reference variable is a reference to an
array by appending square brackets to the type name or the variable name.
Only works with type Object
However, you cannot assign an array object's reference to an ordinary reference variable of any other
type. For any type other than Object , the reference variable must be declared to hold a reference to an
array object by appending empty square brackets onto the type name or the variable name.
The rst statement in the following fragment compiles successfully.
note:
Object X = A;
Superclass B = A;
However, the second statement in the above fragment produces a compiler error under JDK 1.3, which is
partially reproduced below.
note:
Both Superclass and Object are superclasses of the array type referred to by the reference variable
named A . However, because of the above rule, in order to cause this program to compile successfully, you
would need to modify it as shown below by adding the requisite empty square brackets to the Superclass
type name.
note:
Object X = A;
Superclass[] B = A;
3.7.6.3 Answer 13
note:
C. 0 0 0
0 1 2
3.7.6.3.1 Explanation 13
Syntactical ugliness
As I indicated in an earlier module, when declaring a reference variable that will refer to an array object,
you can place the empty square brackets next to the name of the type or next to the name of the reference
variable. In other words, either of the following formats will work.
note:
int[][] A;
int B[][];
What I may not have told you at that time is that you can place some of the empty square brackets in one
location and the remainder in the other location.
Really ugly syntax
This is indicated by the following fragment, which declares a reference variable for a two-dimensional
array of type int . Then it creates the two-dimensional array object and assigns the array object's reference
to the reference variable.
note:
int[] A[];
A = new int[2][3];
While it doesn't matter which location you use for the square brackets in the declaration, it does matter
how many pairs of square brackets you place in the two locations combined. The number of dimensions
on the array (if you want to think of a Java array as having dimensions) will equal the total number of
pairs of empty square brackets in the declaration of the reference variable. Thus, in this case, the array is a
two-dimensional array because there is one pair of square brackets next to the type and another pair next
to the variable name.
This program goes on to use nested for loops to populate the array and then to display the contents of
the elements.
I personally don't use this syntax, and I hope that you don't either. However, even if you don't use it,
you need to be able to recognize it when used by others.
Back to Question 13 (p. 155)
3.7.6.4 Answer 12
C. 1 2
3.7.6.4.1 Explanation 12
The length property
This program illustrates the use of the array property named length , whose value always matches the
number of elements in the array.
As a Java programmer, you will frequently call methods that will return a reference to an array object of a
specied type, but of an unknown length. (See, for example, the method named getEventSetDescriptors
that is declared in the interface named BeanInfo .) This program simulates that situation.
Returning a reference to an array
The method named returnArray returns a reference to an array of type int having two elements.
Although I xed the size of the array in this example, I could just as easily have used a random number to
set a dierent size for the array each time the method is called. Therefore, the doArrays method making
the call to the method named returnArray has no way of knowing the size of the array referred to by the
reference that it receives as a return value.
All array objects have a length property
This could be a problem, but Java provides the solution to the problem in the length property belonging
to all array objects.
The for loop in the method named doArrays uses the length property of the array to determine
how many elements it needs to display. This is a very common scenario in Java.
Back to Question 12 (p. 154)
3.7.6.5 Answer 11
A. Compiler Error
3.7.6.5.1 Explanation 11
You cannot cast primitive array references
You cannot cast an array reference from one primitive type to another primitive type, even if the individual
elements in the array are of a type that can normally be converted to the new type.
This program attempts to cast a reference to an array of type int[] and assign it to a reference variable of
type double []. Normally, a value of type int will be automatically converted to type double whenever
there is a need for such a conversion. However, this attempted cast produces the following compiler error
under JDK 1.3.
note:
3.7.6.6 Answer 10
C. 1.0 2.0
3.7.6.6.1 Explanation 10
Assigning array reference to variable of type Object
A reference to an array can be assigned to a non-array reference of the class named Object , as in the
following statement extracted from the program, where A is a reference to an array object of type double
.
note:
Object B = A;
Note that there are no square brackets anywhere in the above statement. Thus, the reference to the array
object is not being assigned to an array reference of the type Object[] . Rather, it is being assigned to an
ordinary reference variable of the type Object .
Downcasting to an array type
Once the array reference has been assigned to the ordinary reference variable of the type Object , that
reference variable can be downcast and used to access the individual elements in the array as illustrated in
the following fragment. Note the empty square brackets in the syntax of the cast operator (double[]) .
note:
System.out.println(
((double[])B)[0] + " " +
((double[])B)[1]);
3.7.6.7 Answer 9
C. 1 2
3.7.6.7.1 Explanation 9
General array casting rule
The general rule for casting array references (for arrays whose declared type is the name of a class or an
interface) is:
A reference to an array object can be cast to another array type if the elements of the referenced array
are of a type that can be cast to the type of the elements of the specied array type.
Old rules apply here also
Thus, the general rules covering conversion and casting up and down the inheritance hierarchy and among
classes that implement the same interfaces also apply to the casting of references to array objects.
A reference to an object can be cast down the inheritance hierarchy to the actual class of the object.
Therefore, an array reference can also be cast down the inheritance hierarchy to the declared class for the
array object.
This program declares a reference to, creates, and populates an array of the class type Subclass . This
reference is assigned to an array reference of a type that is a superclass of the actual class type of the array.
Then the superclass reference is downcast to the actual class type of the array and assigned to a dierent
reference variable. This third reference variable is used to successfully access and display the contents of the
elements in the array.
Back to Question 9 (p. 151)
3.7.6.8 Answer 8
B. Runtime Error
3.7.6.8.1 Explanation 8
Another ClassCastException
While it is allowable to assign an array reference to an array reference variable declared for a class that
is further up the inheritance hierarchy (as illustrated earlier) , it is not allowable to cast an array reference
down the inheritance hierarchy to a subclass of the original declared class for the array.
This program declares a reference for, creates, and populates a two-element array for a class named
Superclass . Then it downcasts that reference to a subclass of the class named Superclass . The
compiler is unable to determine that this is a problem. However, the runtime system throws the following
exception, which terminates the program at runtime.
note:
java.lang.ClassCastException: [LSuperclass;
at Worker.doArrays(Ap071.java:19)
at Ap071.main(Ap071.java:9)
3.7.6.9 Answer 7
C. 1 2
3.7.6.9.1 Explanation 7
Assignment to superclass array reference variable
This program illustrates that, if you have a reference to an array object containing references to other
objects, you can assign the array object's reference to an array reference variable whose type is a superclass
of the declared class of the array object. (As we will see later, this doesn't work for array objects containing
primitive values.)
3.7.6.10 Answer 6
C. 1 2
3.7.6.10.1 Explanation 6
Straightforward array application
This is a straightforward application of Java array technology for the storage and retrieval of references
to objects.
The program declares a reference to, creates, and populates a two-element array of a class named
Subclass Subclass extends the class named Superclass , which in turn, extends
. The class named
the class named Object by default.
The super keyword
The class named Subclass doesn't do anything particularly useful other than to illustrate extending a
class.
However, it also provides a preview of the use of the super keyword for the purpose of causing a
constructor in a subclass to call a parameterized constructor in its superclass.
Setting the stage for follow-on questions
The main purpose for showing you this program is to set the stage for several programs that will be using
this class structure in follow-on questions.
Back to Question 6 (p. 145)
3.7.6.11 Answer 5
B. Runtime Error
3.7.6.11.1 Explanation 5
ClassCastException
There are some situations involving casting where the compiler cannot identify an erroneous condition
that is later identied by the runtime system. This is one of those cases.
This program begins with an array of type double []. The reference to that array is converted to type
Object . Then it is cast to type String []. All of these operations are allowed by the compiler.
However, at runtime, the runtime system expects to nd references to objects of type String in the
elements of the array. What it nds instead is values of type double stored in the elements of the array.
As a result, a ClassCastException is thrown. Since it isn't caught and handled by the program, the
program terminates with the following error message showing on the screen.
note:
java.lang.ClassCastException: [D
at Worker.doArrays(Ap068.java:17)
at Ap068.main(Ap068.java:6)
3.7.6.12 Answer 4
C. 1.0 2.0
3.7.6.12.1 Explanation 4
Finally, we got it right
Finally, we managed to get it all together. The program compiles and executes correctly. This program
illustrates the assignment of an array object's reference to a reference variable of type Object , and the
casting of that reference of type Object back to the correct array type in order to gain access to the
elements in the array.
But don't go away, there is a lot more that you need to know about arrays in Java. We will look at some
of those things in the questions that follow.
Back to Question 4 (p. 143)
3.7.6.13 Answer 3
A. Compiler Error
3.7.6.13.1 Explanation 3
Must use the correct cast syntax
While it is possible to store an array object's reference in a reference variable of type Object , and later
cast it back to an array type to gain access to the elements in the array, you must use the correct syntax in
performing the cast. This is not the correct syntax for performing that cast. It is missing the empty square
brackets required to indicate a reference to an array object.
A portion of the compiler error produced by JDK 1.3 is shown below:
note:
3.7.6.14 Answer 2
A. Compiler Error
3.7.6.14.1 Explanation 2
Must cast back to an array type
This program illustrates another very important point. Although you can assign an array object's ref-
erence to a reference variable of type Object , you cannot gain access to the elements in the array while
treating it as type Object . Instead, you must cast it back to an array type before you can gain access to
the elements in the array object.
A portion of the compiler error produced by JDK 1.3 is shown below:
note:
3.7.6.15 Answer 1
C. I'm OK
3.7.6.15.1 Explanation 1
Assigning array reference to type Object
This program illustrates a very important point. You can assign an array object's reference to an ordinary
Object . Note that I didn't say Object[]
reference variable of type . The empty square brackets are not
required when the type isObject .
Standard containers or collections
Later on, when we study the various containers in the Java class libraries (see the Java Collections
Framework) , we will see that they store references to all objects, including array objects, as type Object
. Thus, if it were not possible to store a reference to an array object in a reference variable of type Object
, it would not be possible to use the standard containers to store references to array objects.
Because it is possible to assign an array object's reference to a variable of type Object , it is also
possible to store array object references in containers of type Object .
Back to Question 1 (p. 141)
-end-
· 1 (p. 168) , 2 (p. 168) , 3 (p. 169) , 4 (p. 170) , 5 (p. 171) , 6 (p. 172) , 7 (p. 173) , 8 (p. 174)
3.8.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 175) to easily nd and view the listings while you are reading about them.
3.8.3 Questions
3.8.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 168) ?
• A. Compiler Error
• B. Runtime Error
• C. 9 17.64
• D. None of the above
class Worker{
public void doOverLoad(){
int x = 3;
double y = 4.2;
System.out.println(square(x) + " "
+ square(y));
}//end doOverLoad()
3.95
3.8.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 169) ?
• A. Compiler Error
• B. Runtime Error
• C. oat 9.0 double 17.64
• D. None of the above
class Worker{
public void doOverLoad(){
int x = 3;
double y = 4.2;
3.96
3.8.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 170) ?
• A. Compiler Error
• B. Runtime Error
• C. 10 17.64
• D. None of the above
class Worker{
public void doOverLoad(){
double w = 3.2;
double x = 4.2;
int y = square(w);
double z = square(x);
3.97
3.8.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 171) ?
• A. Compiler Error
• B. Runtime Error
• C. 9 17.64
• D. None of the above
class Worker{
public void doOverLoad(){
int w = 3;
double x = 4.2;
System.out.println(
new Subclass().square(w) + " "
+ new Subclass().square(x));
}//end doOverLoad()
}// end class
class Superclass{
public double square(double y){
return y*y;
}//end square()
}//end class Superclass
3.98
3.8.3.5 Question 5
Which of the following is produced by the program shown in Listing 5 (p. 172) ?
note:
A. Compiler Error
B. Runtime Error
C. float 2.14748365E9
float 9.223372E18
double 4.2
class Worker{
public void doOverLoad(){
int x = 2147483647;
square(x);
long y = 9223372036854775807L;
square(y);
double z = 4.2;
square(z);
System.out.println();
}//end doOverLoad()
3.99
3.8.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 173) ?
• A. Compiler Error
• B. Runtime Error
• C. Test DumIntfc
class Worker{
public void doOverLoad(){
Test a = new Test();
DumIntfc b = new Test();
overLoadMthd(a);
overLoadMthd(b);
System.out.println();
}//end doOverLoad()
interface DumIntfc{
}//end DumIntfc
3.100
3.8.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 174) ?
• A. Compiler Error
• B. Runtime Error
• C. Test Object
• D. None of the above
class Worker{
public void doOverLoad(){
Test a = new Test();
Object b = new Test();
overLoadMthd(a);
overLoadMthd(b);
System.out.println();
}//end doOverLoad()
class Test{
}//end class Test
3.101
3.8.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 175) ?
• A. Compiler Error
• B. Runtime Error
• C. SubC SuperC
• D. None of the above
class Worker{
public void doOverLoad(){
SubC a = new SubC();
SuperC b = new SubC();
System.out.println();
}//end doOverLoad()
class SuperC{
public void overLoadMthd(SuperC x){
System.out.print("SuperC ");
}//end overLoadMthd
}//end SuperC
3.102
3.8.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.8.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.8.6 Answers
3.8.6.1 Answer 8
C. SubC SuperC
3.8.6.1.1 Explanation 8
While admittedly a little convoluted, this is another relatively straightforward application of method over-
loading using types from the class hierarchy.
Type SubC , SuperC , or Object?
This method denes a class named SuperC , which extends Object , and a class named SubC ,
which extends SuperC . Therefore, an object instantiated from the class named SubC can be treated
SubC , SuperC , or Object .
as any of the following types:
Two overloaded methods in dierent classes
Two overloaded methods named overLoadMthd are dened in two classes in the inheritance hierarchy.
The class named SuperC denes a version that requires an incoming parameter of type SuperC . The
class named SubC denes a version that requires an incoming parameter of type SubC . When called,
each of these overloaded methods prints the type of its formal argument.
3.8.6.2 Answer 7
C. Test Object
3.8.6.2.1 Explanation 7
Another straightforward application
This is another straightforward application of method overloading, which produces no surprises.
This program denes a new class named Test , which extends the Object class by default. This
means that an object instantiated from the class named Test can be treated either as type Test , or as
type Object .
The program denes two overloaded methods named overLoadMthd . One requires an incoming
parameter of type Test . The other requires an incoming parameter of type Object . When called, each
of these methods prints the type of its incoming parameter.
The program instantiates two dierent objects of the class Test , storing a reference to one of them
in a reference variable of type Test , and storing a reference to the other in a reference variable of type
Object .
No surprises here
Then it calls the overloaded overLoadMthd method twice in succession, passing the reference of type
Test during the rst call, and passing the reference of type Object during the second call.
As mentioned above, the output produces no surprises. The output indicates that the method selected for
execution during each call is the method with the formal argument type that matches the type of parameter
passed to the method.
Back to Question 7 (p. 173)
3.8.6.3 Answer 6
C. Test DumIntfc
3.8.6.3.1 Explanation 6
Overloaded methods with reference parameters
This is a fairly straightforward application of method overloading. However, rather than requiring method
parameters of primitive types as in the previous questions in this module, the overloaded methods in this
program require incoming parameters of class and interface types respectively.
Type Test or type DumIntfc?
The program denes an interface named DumIntfc and denes a class named Test that implements
that interface. The result is that an object instantiated from the Test class can be treated either as type
Test or as type DumIntfc (it could also be treated as type Object as well) .
Two overloaded methods
The program denes two overloaded methods named overLoadMthd . One requires an incoming
parameter of type Test , and the other requires an incoming parameter of type DumIntfc . When
called, each of the overloaded methods prints a message indicating the type of its argument.
Two objects of the class Test
The program instantiates two objects of the class Test . It assigns one of the object's references to a
reference variable named a , which is declared to be of type Test .
b , which is declared to
The program assigns the other object's reference to a reference variable named
be of type DumIntfc . (Remember, both objects were instantiated from the class Test .)
No surprises here
Then it calls the overloaded method named overLoadMthd twice in succession, passing rst the
reference variable of type Test and then the reference variable of type DumIntfc .
The program output doesn't produce any surprises. When the reference variable of type Test is passed
as a parameter, the overloaded method requiring that type of parameter is selected for execution. When the
reference variable of type DumIntfc is passed as a parameter, the overloaded method requiring that type
of parameter is selected for execution.
Back to Question 6 (p. 172)
3.8.6.4 Answer 5
note:
C. float 2.14748365E9
float 9.223372E18
double 4.2
3.8.6.4.1 Explanation 5
Another subtle method selection issue
This program illustrates a subtle issue in the automatic selection of an overloaded method based on
assignment compatibility.
This program denes two overloaded methods named square . One requires an incoming parameter of
type oat , and the other requires an incoming parameter of type double .
When called, each of these methods prints the type of its formal argument along with the value of the
incoming parameter as represented by its formal argument type. In other words, the value of the incoming
parameter is printed after it has been automatically converted to the formal argument type.
Printout identies the selected method
This printout makes it possible to determine which version is called for dierent types of parameters. It
also makes it possible to determine the eect of the automatic conversion on the incoming parameter. What
we are going to see is that the conversion process can introduce serious accuracy problems.
Call the method three times
The square method is called three times in succession, passing values of type int , long , and
double during successive calls.
(Type long is a 64-bit integer type capable of storing integer values that are much larger than can
be stored in type int . The use of this type here is important for illustration of data corruption that
occurs through automatic type conversion.)
The third invocation of the square method, passing a double as a parameter, is not particularly
interesting. There is a version of square with a matching argument type, and everything behaves as would
be expected for this invocation. The interesting behavior occurs when the int and long values are passed
as parameters.
Passing an int parameter
The rst thing to note is the behavior of the program produced by the following code fragment.
note:
int x = 2147483647;
square(x);
The above fragment assigns a large integer value (2147483647)to the int variable and passes that variable
to the square method. This fragment produces the following output on the screen:
note:
float 2.14748365E9
As you can see, the system selected the overloaded method that requires an incoming parameter of type
oat for execution in this case (rather than the version that requires type double ).
Conversion from int to oat loses accuracy
Correspondingly, it converted the incoming int value to type oat , losing one decimal digit of accuracy
in the process. (The original int value contained ten digits of accuracy. This was approximated by a
nine-digit oat value with an exponent value of 9.)
This seems like an unfortunate choice of overloaded method. Selecting the other version that requires a
double parameter as input would not have resulted in any loss of accuracy.
A more dramatic case
Now, consider an even more dramatic case, as illustrated in the following fragment where a very large
long integer value(9223372036854775807) is passed to the square method.
note:
long y = 9223372036854775807L;
square(y);
note:
float 9.223372E18
selected, the conversion process would have lost about three digits of accuracy, but that would have been
much better than losing twelve digits of accuracy.)
The moral to the story is ...
Don't assume that just because the system knows how to automatically convert your integer data to
oating data, it will protect the integrity of your data. Oftentimes it won't.
To be really safe ...
To be really safe, whenever you need to convert either int or long types to oating format, you should
write your code in such a way as to ensure that it will be converted to type double instead of type oat
.
For example, the following modication would solve the problem for the int data and would greatly
reduce the magnitude of the problem for the long data. Note the use of the (double) cast to force the
double version of the square method to be selected for execution.
note:
int x = 2147483647;
square((double)x);
long y = 9223372036854775807L;
square((double)y);
The above modication would cause the program to produce the following output:
note:
double 2.147483647E9
double 9.223372036854776E18
double 4.2
This output shows no loss of accuracy for the int value, and the loss of three digits of accuracy for the
long value.
(Because a long and a double both store their data in 64 bits, it is not possible to convert
a very large long value to a double value without some loss in accuracy, but even that is much
better than converting a 64-bit long value to a 32-bit oat value.)
Back to Question 5 (p. 171)
3.8.6.5 Answer 4
C. 9 17.64
3.8.6.5.1 Explanation 4
When the square method is called on an object of the Subclass type passing an int as a parameter,
there is an exact match to the required parameter type of the square method dened in that class. Thus,
the method is properly selected and executed.
When the square method is called on an object of the Subclass type passing a double as a
parameter, the version of the square method dened in the Subclass type is not selected. The double
value is not assignment compatible with the required type of the parameter (an int is narrower than
a double ).
Having made that determination, the system continues searching for an overloaded method with a required
parameter that is either type double or assignment compatible with double . It nds the version inherited
from Superclass double parameter and calls it.
that requires a
The bottom line is, overloaded methods can occur up and down the inheritance hierarchy.
Back to Question 4 (p. 170)
3.8.6.6 Answer 3
A. Compiler Error
3.8.6.6.1 Explanation 3
Return type is not a dierentiating feature
This is not a subtle issue. This program illustrates the important fact that the return type does not
dierentiate between overloaded methods having the same name and formal argument list.
For a method to be overloaded, two or more versions of the method must have the same name and
dierent formal arguments lists.
The return type can be the same, or it can be dierent (it can even be void) . It doesn't matter.
These two methods are not a valid overload
This program attempts to dene two methods named square , each of which requires a single incoming
parameter of type double . One of the methods casts its return value to type int and returns type int
. The other method returns type double .
The JDK 1.3 compiler produced the following error:
note:
3.8.6.7 Answer 2
C. oat 9.0 double 17.64
3.8.6.7.1 Explanation 2
This program is a little more subtle
Once again, the program denes two overloaded methods named square . However, in this case, one
of the methods requires a single incoming parameter of type oat and the other requires a single incoming
parameter of type double . (Suce it to say that the oat type is similar to the double type,
but with less precision. It is a oating type, not an integer type. The double type is a 64-bit oating
type and the oat type is a 32-bit oating type.)
Passing a type int as a parameter
This program does not dene a method named square that requires an incoming parameter of type
int square
. However, the program calls the method passing a value of type int as a parameter.
What happens to the int parameter?
The rst question to ask is, will this cause one of the two overloaded methods to be called, or will it
cause a compiler error? The answer is that it will cause one of the overloaded methods to be called because
a value of type int is assignment compatible with both type oat and type double .
Which overloaded method will be called?
Since the type int is assignment compatible with type oat and also with type double , the next
question is, which of the two overloaded methods will be called when a value of type int is passed as a
parameter?
Learn through experimentation
I placed a print statement in each of the overloaded methods to display the type of that method's
argument on the screen when the method is called. By examining the output, we can see that the method
with the oat parameter was called rst (corresponding to the parameter of type int ). Then the
method with the double parameter was called (corresponding to the parameter of type double ).
Converted int to oat
Thus, the system selected the overloaded method requiring an incoming parameter of type oat when
the method was called passing an int as a parameter. The value of type int was automatically converted
to type oat .
In this case, it wasn't too important which method was called to process the parameter of type int ,
because the two methods do essentially the same thing compute and return the square of the incoming
value.
However, if the behavior of the two methods were dierent from one another, it could make a lot of
dierence, which one gets called on an assignment compatible basis. (Even in this case, it makes some
dierence. As we will see later, when a very large int value is converted to a oat , there is some
loss in accuracy. However, when the same very large int value is converted to a double , there is
no loss in accuracy.)
Avoiding the problem
One way to avoid this kind of subtle issue is to avoid passing assignment-compatible values to overloaded
methods.
Passing assignment-compatible values to overloaded methods allows the system to resolve the issue
through automatic type conversion. Automatic type conversion doesn't always provide the best choice.
Using a cast to force your choice of method
Usually, you can cast the parameter values to a specic type before calling the method and force the
system to select your overloaded method of choice.
double parameter to handle
For example, in this problem, you could force the method with the the
parameter of type int by using the following cast when the method named square is called:
square((double)x)
However, as we will see later, casting may not be the solution in every case.
Back to Question 2 (p. 168)
3.8.6.8 Answer 1
C. 9 17.64
3.8.6.8.1 Explanation 1
What is method overloading?
A rigorous denition of method overloading is very involved and won't be presented here. However, from
a practical viewpoint, a method is overloaded when two or more methods having the same name and dierent
formal argument lists are dened in the class from which an object is instantiated, or are inherited into an
object by way of superclasses of that class.
How does the compiler select among overloaded methods?
The exact manner in which the system determines which method to call in each particular case is also
very involved. Basically, the system determines which of the overloaded methods to execute by matching
the types of parameters passed to the method to the types of arguments dened in the formal argument list.
Assignment compatible matching
However, there are a number of subtle issues that arise, particularly when there isn't an exact match. In
selecting the version of the method to call, Java supports the concept of an "assignment compatible" match
(or possibly more than one assignment compatible match) .
Briey, assignment compatibility means that it would be allowable to assign a value of the type that is
passed as a parameter to a variable whose type matches the specied argument in the formal argument list.
Selecting the best match
According to Java Language Reference by Mark Grand,
"If more than one method is compatible with the given arguments, the method that most closely matches
the given parameters is selected. If the compiler cannot select one of the methods as a better match than
the others, the method selection process fails and the compiler issues an error message."
Understanding subtleties
If you plan to be a Java programmer, you must have some understanding of the subtle issues involving
overloaded methods, and the relationship between overloaded methods and overridden methods. Therefore,
the programs in this module will provide some of that information and discuss some of the subtle issues that
arise.
Even if you don't care about the subtle issues regarding method overloading, many of those issues really
involve automatic type conversion. You should study these questions to learn about the problems associated
with automatic type conversion.
This program is straightforward
However, there isn't anything subtle about the program for Question 1 (p. 168) . This program denes
two overloaded methods named square . One requires a single incoming parameter of type int . The
other requires a single incoming parameter of type double . Each method calculates and returns the
square of the incoming parameter.
The program calls a method named square twice in succession, and displays the values returned by
those two invocations. In the rst case, an int value is passed as a parameter. This causes the method
with the formal argument list of type int to be called.
double value is passed as a parameter.
In the second case, a This causes the method with the formal
argument list of typedouble to be called.
Overloaded methods may have dierent return types
Note in particular that the overloaded methods have dierent return types. One method returns its value
as type int and the other returns its value as type double . This is reected in the output format for
the two return vales as shown below:
9 17.64
Back to Question 1 (p. 168)
-end-
· 1 (p. 184) , 2 (p. 184) , 3 (p. 185) , 4 (p. 186) , 5 (p. 187) , 6 (p. 188) , 7 (p. 189) , 8 (p. 190) ,
9 (p. 191) , 10 (p. 192)
3.9.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 193) to easily nd and view the listings while you are reading about them.
3.9.3 Questions
3.9.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 184) ?
• A. Compiler Error
• B. Runtime Error
• C. An Object
• D. None of the above
class Worker{
public void makeObj(){
NewClass obj = NewClass();
System.out.println(obj);
}//end makeObj()
class NewClass{
public String toString(){
return "An Object";
}//end toString()
}//end NewClass
3.103
3.9.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 185) ?
• A. Compiler Error
• B. Runtime Error
• C. An Object
• D. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass();
System.out.println(obj);
}//end makeObj()
Class NewClass{
public String toString(){
return "An Object";
}//end toString()
}//end NewClass
3.104
3.9.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 186) ?
• A. Compiler Error
• B. Runtime Error
• C. An Object
• D. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass();
System.out.println(obj);
}//end makeObj()
class NewClass{
public String toString(){
return "An Object";
}//end toString()
}//end NewClass
3.105
3.9.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 187) ?
• A. Compiler Error
• B. Runtime Error
• C. Object containing 2
• D. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass();
System.out.println(obj);
}//end makeObj()
}// end class
class NewClass{
private int x = 2;
3.106
3.9.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 188) ?
• A. Compiler Error
• B. Runtime Error
• C. Object containing 2
• D. None of the above
class Worker{
public void makeObj(){
Subclass obj = new Subclass();
System.out.println(obj);
}//end makeObj()
}// end class
class Superclass{
private int x;
3.107
3.9.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 189) ?
• A. Compiler Error
• B. Runtime Error
• C. Object containing 5
• D. Object containing 2
• E. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass(5);
System.out.println(obj);
}//end makeObj()
}// end class
class NewClass{
private int x = 2;
public NewClass(){
}//end constructor
3.108
3.9.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 190) ?
• A. Compiler Error
• B. Runtime Error
• C. Object containing 0, 0.0, false
• D. Object containing 0.0, 0, true
class Worker{
public void makeObj(){
NewClass obj = new NewClass();
System.out.println(obj);
}//end makeObj()
}// end class
class NewClass{
private int x;
private double y;
private boolean z;
3.109
3.9.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 191) ?
• A. Compiler Error
• B. Runtime Error
• C. 2
• D. 5
• E. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass(5);
System.out.println(obj.getX());
}//end makeObj()
}// end class
class NewClass{
private int x = 2;
public NewClass(){
}//end constructor
3.110
3.9.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 192) ?
• A. Compiler Error
• B. Runtime Error
• C. 10
• D. None of the above
class Worker{
public void makeObj(){
}//end makeObj()
}// end class
class NewClass{
private int y;
3.111
3.9.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 193) ?
• A. Compiler Error
• B. Runtime Error
• C. 2
• D. 5
• E. 10
• F. None of the above
class Worker{
public void makeObj(){
NewClass obj = new NewClass(5);
obj.x = 10;
System.out.println(obj.x);
}//end makeObj()
}// end class
class NewClass{
private int x = 2;
public NewClass(){
}//end constructor
3.112
3.9.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.9.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.9.6 Answers
3.9.6.1 Answer 10
A. Compiler Error
3.9.6.1.1 Explanation 10
Variables declared private really are private
The code in the following fragment attempts to ignore the setter and getter methods and directly access
the private instance variable named x in the object referred to by the reference variable named obj .
note:
obj.x = 10;
System.out.println(obj.x);
This produces a compiler error. The compiler error produced by JDK 1.3 is reproduced below.
note:
3.9.6.2 Answer 9
C. 10
3.9.6.2.1 Explanation 9
A setter and a getter
This is a very simple program that uses a setter (modier or mutator) method named setX to set the
value 10 in a property named x that is stored in an instance variable named y in an object instantiated
from the class named NewClass ..
The program also uses a getter (accessor) method named getX to get and display the value of the
property named x . (Note that according to JavaBeans design patterns, the name of the property is
unrelated to the name of variable in which the property value is stored.)
Back to Question 9 (p. 191)
3.9.6.3 Answer 8
D. 5
3.9.6.3.1 Explanation 8
Hide your data and expose your methods
For reasons that I won't go into here, good object-oriented design principles state that in almost all cases
where an instance variable is not declared to be nal , it should be declared private . (A nal variable
behaves like a constant.)
What is private access?
When an instance variable is declared private , it is accessible only by methods of the class in which it
is dened. Therefore, the only way that the "outside world" can gain access to a private instance variable
is by going through an (usually public ) instance method of the object.
Accessor, modier, mutator, setter, and getter methods
Historically, methods that have been dened for the purpose of exposing private instance variables to
the outside world have been referred to as accessor and modier methods. (Modier methods are also
sometimes called mutator methods.)
(Note that since the advent of Sun's JavaBeans Component design patterns, these methods have also come
to be known as getter methods and setter methods in deference to the design-pattern naming conventions
for the methods.)
A private instance variable with an initializer
The class named NewClass declares a private instance variable named x and initializes its value
to 2, as shown in the following code fragment:
note:
private int x = 2;
Two constructors
The class contains both a noarg constructor and a parameterized constructor as shown in the following
fragment:
note:
public NewClass(){
}//end constructor
note:
A getter method
Because the instance variable named x private , it
is cannot be accessed directly for display by
the code in the makeObj method of the Worker class. However, the NewClass class provides
the following public getter or accessor method that can be used to get the value stored in the instance
variable.
(The name of this method complies with JavaBeans design patterns. If you examine the name carefully,
you will see why Java programmers often refer to methods like this as getter methods.)
note:
note:
3.9.6.4 Answer 7
C. Object containing 0, 0.0, false
3.9.6.4.1 Explanation 7
Default initialization values
The purpose of this question is to conrm that you understand the default initialization of instance
variables in an object when you don't write code to cause the initialization of the instance variable to dier
from the default.
By default, all instance variables in a new object are initialized with default values if you don't provide
a constructor (or other mechanism) that causes them to be initialized dierently from the default.
• All instance variables of the numeric types are initialized to the value of zero for the type. This program
int and double types.
illustrates default initialization to zero for
• Instance variables of type boolean are initialized to false.
• Instance variables of type char are initialized to a 16-bit Unicode character for which all sixteen bits
have been set to zero. I didn't include initialization of the char type in the output of this program
because the default char value is not printable.
• Instance variables of reference types are initialized to null.
3.9.6.5 Answer 6
C. Object containing 5
3.9.6.5.1 Explanation 6
A parameterized constructor
This program illustrates the straightforward use of a parameterized constructor.
The class named NewClass denes a parameterized constructor that requires an incoming parameter
of type int .
(For good design practice, the class also denes a noarg constructor, even though it isn't actually used
in this program. This makes it available if needed later when someone extends the class.)
Both constructors are shown in the following code fragment.
note:
public NewClass(){
}//end constructor
The parameterized constructor stores its incoming parameter named x in an instance variable of the class,
also named x .
(The use of the keyword this is required in this case to eliminate the ambiguity of having a local
parameter with the same name as an instance variable. This is very common Java programming style that
you should recognize and understand.)
Call the parameterized constructor
The following code fragment calls the parameterized constructor, passing the literal int value of 5 as a
parameter.
note:
Hopefully you will have no diculty understanding the remaining code in the program that causes the value
stored in the instance variable named x to be displayed on the computer screen.
Back to Question 6 (p. 188)
3.9.6.6 Answer 5
A. Compiler Error
3.9.6.6.1 Explanation 5
If you dene any constructors, ...
The discussion for Question 4 (p. 186) explained that if you dene any constructor in a new class, you
must dene all constructors that will ever be needed for that class. When you dene one or more constructors,
the default noarg constructor is no longer provided by the system on your behalf.
Question 4 (p. 186) illustrated a simple manifestation of a problem arising from the failure to dene a
noarg constructor that would be needed later. The reason that it was needed later was that the programmer
attempted to explicitly use the non-existent noarg constructor to create an instance of the class.
A more subtle problem
The problem in this program is more subtle. Unless you (or the programmer of the superclasses)
specically write code to cause the system to behave otherwise, each time you instantiate an object of a
class, the system automatically calls the noarg constructor on superclasses of that class up to and including
the class named Object . If one or more of those superclasses don't have a noarg constructor, unless the
author of the subclass constructor has taken this into account, the program will fail to compile.
Calling a non-existing noarg constructor
This program attempts to instantiate an object of a class named Subclass , which extends a class
named Superclass . By default, when attempting to instantiate the object, the system will attempt to
call anoarg constructor dened in Superclass .
Superclass has no noarg constructor
The Superclass class denes a parameterized constructor that requires a single incoming parameter of
type int . However, it does not also dene a noarg constructor. Because the parameterized constructor is
dened, the default noarg constructor does not exist. As a result, JDK 1.3 produces the following compiler
error:
note:
3.9.6.7 Answer 4
A. Compiler Error
3.9.6.7.1 Explanation 4
Constructors
Java uses the following kinds of constructors:
• Those that take arguments, often referred to as parameterized constructors , which typically perform
initialization on the new object using parameter values.
• Those that don't take arguments, often referred to as default or noarg constructors, which perform
default initialization on the new object.
• Those that don't take arguments but perform initialization on the new object in ways that dier from
the default initialization.
note:
· numeric = 0,
· boolean = false,
· char = all zero bits
· reference = null
In this case, you will typically dene your parameterized constructors to initialize some or all of the
instance variables of the new object using values passed to the constructor as parameters.
What else can a constructor do?
You can also cause your new constructor to do other things if you so choose. For example, if you know
how to do so, you could cause your constructor (with or without parameters) to play an audio clip each
time a new object is instantiated. You could use a parameter to determine which audio clip to play in each
particular instance.
The punch line
So far, everything that I have said is background information for this program. Here is the punch line
insofar as this program is concerned.
If you dene any constructor in your new class, you must dene all constructors that your new class will
ever need.
If you dene any constructor, the default constructor is no longer provided on your behalf. If your new
class needs a noarg constructor (and it probably does, but that may not become apparent until later
when you or someone else extends your class) you must dene the noarg version in addition to the other
overloaded versions that you dene.
A violation of the rule
This program violated the rule given above. It dened the parameterized constructor for the class named
NewClass shown below
note:
However, the program did not also dene a noarg constructor for the NewClass class.
Calling the noarg constructor
The code in the makeObj method of the Worker class attempted to instantiate a new object using
the following code:
note:
Since the class denition didn't contain a denition for a noarg constructor, the following compiler error
was produced by JDK 1.3.
note:
3.9.6.8 Answer 3
C. An Object
3.9.6.8.1 Explanation 3
We nally got it right!
Did you identify the errors in the previous two programs before looking at the answers?
This program declares the class named NewClass correctly and uses the new operator correctly in
conjunction with the default noarg constructor for the NewClass class to create a new instance of the
class (an object) .
Making the class public
One of the things that I could do dierently would be to make the declaration for the NewClass class
public (as shown in the following code fragment) .
note:
I am a little lazy
The reason that I didn't declare this class public (and haven't done so throughout this series of
modules) is because the source code for all public classes and interfaces must be in separate les. While
that is probably a good requirement for large programming projects, it is overkill for simple little programs
like I am presenting in this group of self-assessment modules.
Dealing with multiple les
Therefore, in order to avoid the hassle of having to deal with multiple source code les for every program,
I have been using package-private access for class denitions other than the controlling class (the controlling
class is declared public) . Although I won't get into the details at this point, when a class is not declared
public, it is common to say that it has package-private access instead of public access.
Back to Question 3 (p. 185)
3.9.6.9 Answer 2
A. Compiler Error
3.9.6.9.1 Explanation 2
Java is a case-sensitive language
Java keywords must be written exactly as specied. The keyword class cannot be written as Class ,
which is the problem with this program.
The inappropriate use of the upper-case C in the word Class caused the following compiler error.
note:
Class NewClass{
note:
class NewClass{
public String toString(){
return "An Object";
}//end toString()
}//end NewClass
3.9.6.10 Answer 1
A. Compiler Error
3.9.6.10.1 Explanation 1
Instantiating an object
There are several ways to instantiate an object in Java:
note:
note:
note:
· 1 (p. 203) , 2 (p. 205) , 3 (p. 207) , 4 (p. 207) , 5 (p. 208) , 6 (p. 209) , 7 (p. 210) , 8 (p. 211) ,
9 (p. 212) , 10 (p. 213)
3.10.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 214) to easily nd and view the listings while you are reading about them.
3.10.3 Questions
3.10.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 204) ?
• A. Compiler Error
• B. Runtime Error
• C. 1, 2
• D. 5, 10
• E. None of the above
14 This content is available online at <http://cnx.org/content/m45270/1.4/>.
class Worker{
public void makeObj(){
Subclass obj = new Subclass();
System.out.println(obj.getX() +
", " + obj.getY());
}//end makeObj()
}// end class
class Superclass{
private int x = 1;
public Superclass(){
x = 5;
}//end constructor
public Subclass(){
super();
y = 10;
}//end constructor
3.113
3.10.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 206) ?
• A. Compiler Error
• B. Runtime Error
• C. 1, 2
• D. 5, 2
• E. 5, 10
• F. 20, 10
• G. None of the above
class Worker{
public void makeObj(){
Subclass obj = new Subclass();
System.out.println(obj.getX() +
", " + obj.getY());
}//end makeObj()
}// end class
class Superclass{
private int x = 1;
public Superclass(){
x = 5;
}//end constructor
public Subclass(){
super(20);
y = 10;
}//end constructor
3.114
3.10.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 207) ?
• A. Compiler Error
• B. Runtime Error
• C. 5
• D. None of the above
class Worker{
public void finalStuff(){
final int x = 5;
x = 10;
System.out.println(x);
}//end finalStuff()
}// end class
3.115
3.10.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 208) ?
• A. Compiler Error
• B. Runtime Error
• C. 5
• D. None of the above
class Worker{
public void finalStuff(){
public final int x = 5;
System.out.println(x);
}//end finalStuff()
}// end class
3.116
3.10.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 209) ?
• A. Compiler Error
• B. Runtime Error
• C. 5
• D. None of the above
class Worker{
void finalStuff(){
final int x = 5;
System.out.println(x);
}//end finalStuff()
}// end class
3.117
3.10.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 210) ?
• A. Compiler Error
• B. Runtime Error
• C. 3.141592653589793
• D. 3.1415927
• E. None of the above
class Worker{
public static final float fPi =
(float)Math.PI;
}// end class
3.118
3.10.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 211) ?
• A. Compiler Error
• B. Runtime Error
• C. A static method
• D. None of the above
class Worker{
public static void staticMethod(){
System.out.println(
"A static method");
}//end staticMethod()
3.119
3.10.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 212) ?
• A. Compiler Error
• B. Runtime Error
• C. 5
• D. None of the above
class Worker{
private int x = 5;
public static void staticMethod(){
System.out.println(x);
}//end staticMethod()
3.120
3.10.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 213) ?
• A. Compiler Error
• B. Runtime Error
• C. 5
• D. None of the above
class Worker{
private int x = 5;
public static void staticMethod(){
System.out.println(
new Worker().getX());
}//end staticMethod()
3.121
3.10.3.10 Question 10
Which output shown below is produced by the program shown in Listing 10 (p. 214) ?
note:
A. Compiler Error
B. Runtime Error
C. 38.48451000647496
12.566370614359172
D. None of the above
class Worker{
public static double area(double r){
return r*r*Math.PI;
}//end area()
3.122
3.10.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.10.5 Miscellaneous
This section contains a variety of miscellaneous information.
• File: Ap0090.htm
• Originally published: 2002
• Published at cnx.org: 12/05/12
• Revised: 01/02/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.10.6 Answers
3.10.6.1 Answer 10
note:
C. 38.48451000647496
12.566370614359172
3.10.6.1.1 Explanation 10
Use static methods sparingly
Good object-oriented design dictates that static methods be used sparingly, and only in those situations
where they are appropriate. As you might guess, not all authors will agree on the issue of appropriateness
in all cases.
Is this an appropriate use of a static method?
However, I believe that most authors will agree that this program illustrates an appropriate use of a
static method.
No persistence requirement
This static method computes and returns a result on a non-persistent basis. That is to say, there is no
attempt by the static method to save any historical information from one call of the method to the next.
(Of course, the method that calls the static method can save whatever it chooses to save.)
Avoiding wasted computer resources
In situations such as this, it would often be a waste of computer resources to require a program to
instantiate an object and call an instance method on that object just to be able to delegate a non-persistent
computation to that method. (This is just about as close to a global method as you can get in Java.)
Computing the area of a circle
In this program, the Worker class provides a static method named area that receives a double
parameter representing the radius of a circle. It computes and returns the area of the circle as a double
value. The static method named area is shown in the following code fragment.
note:
class Worker{
public static double area(double r){
return r*r*Math.PI;
}//end area()
As a driver, the main method of the controlling class calls the area method twice in succession, passing
dierent values for the radius of a circle. In each case, the main method receives and displays the value
that is returned by the area method representing the area of a circle.
Static methods in the class libraries
If you examine the Java API documentation carefully, you will nd numerous examples of static methods
(Again, non-persistent in this context means
that produce and return something on a non-persistent basis.
that no attempt is made by the static method to store any historical information. It does a job, forgets
it, and goes on to the next job when it is called again.)
Factory methods
For example, the alphabetical index of the JDK 1.3 API lists several dozen static methods named
getInstance , which are dened in dierent classes. These methods, which usually produce and return a
reference to an object, are often called factory methods .
Here is the text from the API documentation describing one of them:
note: getInstance(int)
3.10.6.2 Answer 9
C. 5
3.10.6.2.1 Explanation 9
Going through a reference to ...
This program illustrates a rather convoluted methodology by which a static method can gain access
to an instance member of an object.
note:
class Worker{
private int x = 5;
public static void staticMethod(){
System.out.println(
new Worker().getX());
}//end staticMethod()
In this example, the static method calls a getter method on a reference to an object to gain access to an
instance variable belonging to that object. This is what I meant in the discussion in the previous question
when I said "going through a reference to an object of the class."
Back to Question 9 (p. 212)
3.10.6.3 Answer 8
A. Compiler Error
3.10.6.3.1 Explanation 8
A static method cannot access ...
A static method cannot access non-static or instance members of its class without going through a
reference to an object of the class.
In this program, the static method attempts to directly access the instance variable named x . As a
result, JDK 1.3 produces the following compiler error:
note:
System.out.println(x);
Back to Question 8 (p. 211)
3.10.6.4 Answer 7
C. A static method
3.10.6.4.1 Explanation 7
Using a static method
This is a very straightforward example of the use of a static method.
When a method is declared static , it is not necessary to instantiate an object of the class containing
the method in order to access the method (although it is possible to do so unless the class is declared
abstract) . All that is necessary to access a public static method is to refer to the name of the class in
which it is dened and the name of the method joined by a period.
(A method that is declared static is commonly referred to as a class method. If the method is not
declared public , it may not be accessible from your code.)
Accessing the static method
This is illustrated by the following fragment from the program, with much of the code deleted for brevity.
note:
//...
Worker.staticMethod();
//...
class Worker{
public static void staticMethod(){
//...
}//end staticMethod()
The class named Worker denes a public static method named staticMethod . A statement in
the main method of the controlling class calls the method by referring to the name of the class and the
name of the method joined by a period.
When should you use static methods?
Static methods are very useful as utility methods (getting the absolute value of a number, for example)
.
In my opinion, you should almost never use a static method in any circumstance that requires the
storage and use of data from one call of the method to the next. In other words, a static method may
be appropriate for use when it performs a specic task that is completed each time it is called without the
requirement for data to persist between calls.
The Math class contains many good examples of the use of static methods, such as abs , acos ,
asin , etc.
Back to Question 7 (p. 210)
3.10.6.5 Answer 6
D. 3.1415927
3.10.6.5.1 Explanation 6
Using a public static nal member variable
The class named Worker declares and initializes a member variable named fPi .
nal
Because it is declared nal , it is not possible to write code that will change its value after it has been
initialized.
static
Because it is declared static , it can be accessed without a requirement to instantiate an object of the
Worker class. All that is necessary to access the variable is to refer to the name of the class and the name
of the variable joined by a period.
Because it is static , it can also be accessed by static methods.
public
Because it is declared public , it can be accessed by any code in any method in any object that can
locate the class.
Type oat is less precise than type double
Because the initialized value is cast from the type double that is returned by Math.PI to type
oat , an 8-digit approximation is stored in the variable named fPi .
The double value returned by Math.PI is 3.141592653589793
The cast to type oat reduces the precision down to 3.1415927
Back to Question 6 (p. 209)
3.10.6.6 Answer 5
C. 5
3.10.6.6.1 Explanation 5
Using a nal local variable
Well, I nally got rid of all the bugs. This program uses a nal local variable properly. The program
compiles and executes without any problems.
Back to Question 5 (p. 208)
3.10.6.7 Answer 4
A. Compiler Error
3.10.6.7.1 Explanation 4
The purpose of this question is to see if you are still awake.
What caused the compiler error?
The statement that caused the compiler error in this program is shown below. Now that you know that
there was a compiler error, and you know which statement caused it, do you know what caused it?
note:
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its
diameter.
note:
note:
3.10.6.8 Answer 3
A. Compiler Error
3.10.6.8.1 Explanation 3
The nal keyword
The nal keyword can be applied in a variety of ways in Java. This includes:
• nal parameters
• nal methods
• nal classes
• nal variables (constants)
note:
final int x = 5;
x = 10;
A compiler error
JDK 1.3 produces the following error message:
note:
x = 10;
(Some authors refer to this as a blank nal.) However, once you have assigned a value to a nal local
variable, you cannot change that value later.
The bottom line
Whether you initialize the nal local variable when you declare it, or assign a value to it later, the
result is the same. It behaves as a constant. The dierence is that if you don't initialize it when you declare
it, you cannot access it until after you assign a value to it.
Back to Question 3 (p. 207)
3.10.6.9 Answer 2
F. 20, 10
3.10.6.9.1 Explanation 2
Calling a parameterized constructor
This is a relatively straightforward implementation of the use of the super keyword in a subclass
constructor to call a parameterized constructor in the superclass.
The interesting code in the program is highlighted in the following fragment. Note that quite a lot of
code was deleted from the fragment for brevity.
note:
class Superclass{
//...
//...
}//end Superclass
public Subclass(){
super(20);
//...
}//end constructor
//...
}//end Subclass
3.10.6.10 Answer 1
D. 5, 10
3.10.6.10.1 Explanation 1
The execution of constructors
The purpose of this question and the associated answer is to illustrate explicitly what happens automat-
ically by default regarding the execution of constructors.
The Subclass constructor
This program denes a class named Subclass , which extends a class named Superclass . A portion
of the Subclass noarg constructor is shown in the
denition, including its following code fragment.
(The class also denes a getter method, which was omitted here for brevity.)
note:
public Subclass(){
super();
y = 10;
}//end constructor
//...
}//end Subclass
note:
class Superclass{
private int x = 1;
public Superclass(){
x = 5;
}//end constructor
//...
}//end Superclass
Additional code
Beyond an exposure and explanation of the use of the super keyword to call the superclass constructor,
this program plays a few games with initial values of instance variables just to see if you are alert to that
sort of thing. However, none of that should be new to you, so I won't discuss it further here.
Back to Question 1 (p. 203)
-end-
· 1 (p. 224) , 2 (p. 224) , 3 (p. 225) , 4 (p. 226) , 5 (p. 227) , 6 (p. 228) , 7 (p. 229) , 8 (p. 229) ,
9 (p. 230) , 10 (p. 231)
3.11.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 232) to easily nd and view the listings while you are reading about them.
3.11.3 Questions
3.11.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 224) ?
• A. Compiler Error
• B. Runtime Error
• C. 33
• D. None of the above
class Worker{
private int data = 33;
class Helper{
public void helpMe(Worker param){
System.out.println(
param.getData());
}//end helpMe()
}//end class Helper
3.123
3.11.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 225) ?
• A. Compiler Error
• B. Runtime Error
• C. 33
• D. None of the above.
class Worker{
private int data = 33;
class Helper{
public void helpMe(Worker param){
System.out.println(
param.getData());
}//end helpMe()
}//end class Helper
3.124
3.11.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 226) ?
• A. Compiler Error
• B. Runtime Error
• C. 11
• D. 22
• E. 33
• F. 44
• G. None of the above.
class Worker{
private int data;
3.125
3.11.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 227) ?
Note that 6.283185307179586 is a correct numeric value.
• A. Compiler Error
• B. Runtime Error
• C. 6.283185307179586
• D. None of the above.
class Worker{
public static final double twoPI;
public Worker(){
twoPI = 2 * Math.PI;
}//end constructor
}// end class Worker
3.126
3.11.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 228) ?
Note that 6.283185307179586 is a correct numeric value.
• A. Compiler Error
• B. Runtime Error
• C. 6.283185307179586
• D. None of the above.
class Worker{
public static final double twoPI
= 2 * Math.PI;
}// end class Worker
3.127
3.11.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 228) ?
Note that 6.283185307179586 is a correct numeric value.
• A. Compiler Error
• B. Runtime Error
• C. 6.283185307179586
• D. None of the above.
class Worker{
public static final double twoPI
= 2 * Math.PI;
}// end class Worker
3.128
3.11.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 229) ?
Note that 6.283185307179586 is a correct numeric value.
• A. Compiler Error
• B. Runtime Error
• C. C. 6.283185307179586
• D. None of the above.
class Worker{
public static final double twoPI
= 2 * myPI;
public static final double myPI
= Math.PI;
}// end class Worker
3.129
3.11.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 230) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 0.0 false
• D. null null null
• E. None of the above.
class Worker{
private int myInt;
private double myDouble;
private boolean myBoolean;
3.130
3.11.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 231) ?
• A. Compiler Error
• B. Runtime Error
• C. 0 false 5 true
• D. None of the above.
class Worker{
private int myInt;
private boolean myBoolean;
3.131
3.11.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 232) ?
• A. Compiler Error
• B. Runtime Error
• C. 20 222.0 false 5 222.0 true
• D. None of the above.
class Worker{
private int myInt = 100;
private double myDouble = 222.0;
private boolean myBoolean;
public Worker(){
myInt = 20;
}//end noarg constructor
3.132
3.11.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.11.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.11.6 Answers
3.11.6.1 Answer 10
C. 20 222.0 false 5 222.0 true
3.11.6.1.1 Explanation 10
Four ways to initialize instance variables
There are at least four ways to establish initial values for instance variables (you may be able to think
of others) :
note:
class Worker{
private int myInt = 100;
private double myDouble = 222.0;
private boolean myBoolean;
//...
In the above fragment, the instance variables named myInt and myDouble receive their initial values
from initialization expressions. In these two cases, the initialization expressions are very simple. They are
simply literal expressions. However, they could be much more complex if needed.
The variable named myBoolean in the above fragment is allowed to take on its default value of false.
Replacing the default noarg constructor
The next fragment shows one of the two overloaded constructors in the class named Worker . This
constructor is a replacement for the default noarg constructor.
note:
class Worker{
private int myInt = 100;
private double myDouble = 222.0;
private boolean myBoolean;
public Worker(){
myInt = 20;
}//end noarg constructor
//...
note:
class Worker{
private int myInt = 100;
private double myDouble = 222.0;
private boolean myBoolean;
//...
//...
A parameterized constructor
The above fragment shows the second of two overloaded constructors for the class named Worker .
This constructor uses two incoming parameter values to establish the values of two of the instance variables,
overwriting whatever values may earlier have been established for those variables.
The above fragment uses this constructor to instantiate an object of the Worker class, assigning
incoming parameter values of 5 and true to the instance variables named myInt and myBoolean
respectively. This overwrites the value previously placed in the variable named myInt by the initialization
expression. It also overwrites the default value previously placed in the instance variable named myBoolean
.
(Note that this constructor doesn't disturb the value for the instance variable named myDouble
that was previously established through the use of an initialization expression.)
Initial values using parameterized constructor
After instantiating the new object, this fragment causes the values of all three instance variables to be
displayed. The result is:
5 222.0 true
As you can see, the values contained in the instance variables named myInt and myBoolean are
the values of 5 and true placed there by the constructor, based on incoming parameter values. The value in
the instance variable named myDouble is the value placed there by the initialization expression when the
variable was declared.
Default initialization
If you don't take any steps to initialize instance variables, they will be automatically initialized. Numeric
instance variables will be initialized with zero value for the type of variable involved. Instance variables of
type boolean will be initialized to false. Instance variables of type char will be initialized to a Unicode
value with all 16 bits set to zero. Reference variables will be initialized to null.
Initialization expression
If you provide an initialization expression for an instance variable, the value of the expression will overwrite
the default value, and the value of the initialization expression will become the initial value for the instance
variable.
3.11.6.2 Answer 9
A. Compiler Error
3.11.6.2.1 Explanation 9
The default constructor
When you dene a class, you are not required to dene a constructor for the class. If you do not dene a
constructor for the class, a default constructor that takes no arguments will be provided on your behalf. You
can instantiate new objects of the class by applying the new operator to the default constructor as shown in
the following code fragment from Question 8 (p. 229) .
note:
new Worker().display();
note:
class Worker{
private int myInt;
private boolean myBoolean;
note:
A compiler error
Since there is no constructor dened in the Worker class with an empty formal argument list (and
the default version is not provided) , the program produces the following compiler error.
note:
3.11.6.3 Answer 8
C. 0 0.0 false
3.11.6.3.1 Explanation 8
All instance variables are initialized to default values
All instance variables are automatically initialized to default values if the author of the class doesn't take
explicit steps to cause them to initialized to other values.
3.11.6.4 Answer 7
A. Compiler Error
3.11.6.4.1 Explanation 7
Pushing the compiler beyond its limits
Compared to many programming environments, the Java compiler is very forgiving. However, there is a
limit to how far even the Java compiler is willing to go to keep us out of trouble.
Initializing the value of a static variable
static variable using an initialization expression as follows:
We can initialize the value of a
note:
Important point
It is necessary for the compiler to be able to evaluate the initialization expression when it is encountered.
Illegal forward reference
This program attempts to use an initialization expression that makes use of the value of another static
variable (myPI) that has not yet been established at that point in the compilation process. As a result,
the program produces the following compiler error under JDK 1.3.
note:
note:
class Worker{
public static final double myPI
= Math.PI;
public static final double twoPI
= 2 * myPI;
3.11.6.5 Answer 6
C. 6.283185307179586
3.11.6.5.1 Explanation 6
Access via an object
Question 5 (p. 227) illustrated the fact that a public static nal member variable of a class can
be accessed via a reference to an object instantiated from the class.
Not the only way to access a static variable
static member variables can be accessed. More importantly,
However, that is not the only way in which
public static member variables of a class can be accessed simply by referring to the name of the class and
the name of the member variable joined by a period.
(Depending on other factors, it may not be necessary for the static variable to also be declared
public , but that is the most general approach.)
A public static nal member variable
In this program, the Worker class declares and initializes a public static nal member variable
named twoPI as shown in the following fragment.
note:
class Worker{
public static final double twoPI
= 2 * Math.PI;
}// end class Worker
3.11.6.6 Answer 5
C. 6.283185307179586
3.11.6.6.1 Explanation 5
A public static nal variable
This program declares a public static nal member variable named twoPI in the class named
Worker , and properly initializes it when it is declared as shown in the following code fragment.
note:
note:
3.11.6.7 Answer 4
A. Compiler Error
3.11.6.7.1 Explanation 4
A nal variable
When a member variable of a class (not a local variable) is declared nal , its value must be established
when the variable is declared. This program attempts to assign a value to a nal member variable after
it has been declared, producing the following compiler error under JDK 1.3.
note:
3.11.6.8 Answer 3
D. 22
3.11.6.8.1 Explanation 3
Two uses of the this keyword
This program illustrates two dierent uses of thethis keyword.
Disambiguating a reference to a variable
Consider rst the use of this that is shown in the following code fragment.
note:
class Worker{
private int data;
In this shadowing circumstance, when the code in the constructor refers simply to the name data , it
is referring to the local parameter having that name. In order for the code in the constructor to refer to the
instance variable having the name data, it must refer to it as this.data .
In other words ...
In other words, this.data is a reference to an instance variable named data belonging to the object
being constructed by the constructor (this object) .
Not always necessary
You could always use this syntax to refer to an instance variable of the object being constructed if you
wanted to. However, the use of this syntax is necessary only when a local parameter or variable has the
same name as the instance variable and casts a shadow on the instance variable. When this is not the case,
you can refer to the instance variable simply by referring to its name without the keyword this .
Finally, the main point ...
Now consider the main point of this program. The following fragment shows the main method of the
controlling class for the application.
note:
note:
note:
note:
obj2.doThis();
3.11.6.9 Answer 2
C. 33
3.11.6.9.1 Explanation 2
The this keyword
The key to an understanding of this program lies in an understanding of the single statement that appears
in the method named doThis , as shown in the following fragment.
note:
The keyword named this has several uses in Java, some of which are explicit, and some of which take place
behind the scenes.
What do you need to know about the this keyword?
One of the uses of the keyword this is passing the implicit parameter in its entirety to another method.
That is exactly what this program does. But what is the implicit parameter named this anyway?
Every object holds a reference to itself
This implicit reference can be accessed using the keyword this in a non-static (instance) method
belonging to the object.(The implicit reference named this cannot be accessed from within a static
method for reasons that won't be discussed here.)
note:
new Worker().doThis();
An anonymous object
The above statement creates an anonymous object of the class named Worker . (An anonymous
object is an object whose reference is not assigned to a named reference variable.)
The code to the left of the period returns a reference to the new object. Then the code calls the instance
method named doThis on the reference to the object.
Which object is this object?
When the code in the instance method named doThis refers to the keyword this , it is a reference
to the specic object on which the doThis method was called. The statement in the following fragment
passes a reference to that specic instance of the Worker class to a method named helpMe in a new
object of the Helper class.
note:
note:
class Helper{
public void helpMe(Worker param){
System.out.println(
param.getData());
}//end helpMe()
}//end class Helper
Any number of objects can be instantiated from a given class. A given instance method can be called
on any of those objects. When the code in such an instance method refers to this , it is referring to the
specic object on which it was called, and is not referring to any of the many other objects that may have
been instantiated from the same class.
Back to Question 2 (p. 224)
3.11.6.10 Answer 1
A. Compiler Error
3.11.6.10.1 Explanation 1
A wakeup call
The purpose of this question is simply to give you a wakeup call. The declaration for the method named
getData indicates that the method returns a reference to an object of the class String . However, the
code in the method attempts to return an int . The program produces the following compiler error under
JDK 1.3.
note:
found : int
required: java.lang.String
return data;
· 1 (p. 246) , 2 (p. 246) , 3 (p. 247) , 4 (p. 248) , 5 (p. 249) , 6 (p. 250) , 7 (p. 251) , 8 (p. 252) ,
9 (p. 253) , 10 (p. 254)
3.12.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 255) to easily nd and view the listings while you are reading about them.
3.12.3 Questions
3.12.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 246) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
}//end class Base
3.133
3.12.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 247) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
((A)myVar).test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
}//end class Base
3.134
3.12.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 248) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
abstract public void test();
}//end class Base
3.135
3.12.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 249) ?
• A. Compiler Error
• B. Runtime Error
• C. A
• D. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
3.136
3.12.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 250) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new Base();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
3.137
3.12.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 251) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new Base();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
3.138
3.12.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 252) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new Base();
((A)myVar).test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
3.139
3.12.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 253) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
((A)myVar).test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
3.140
3.12.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 254) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
3.141
3.12.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 255) ?
• A. Compiler Error
• B. Runtime Error
• C. Base
• D. A B
• E. None of the above.
class Worker{
void doIt(){
Base myVar = new A();
myVar.test();
myVar = new B();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
3.142
3.12.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.12.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.12.6 Answers
3.12.6.1 Answer 10
D. A B
3.12.6.1.1 Explanation 10
Another illustration of simple polymorphic behavior
In this program, two classes named A and B extend the class named Base , each overriding the
method named test to produce dierent behavior. (Typically, overridden methods in dierent classes will
produce dierent behavior, even though they have the same names.)
Behavior appropriate for object on which method is called
In other words, the behavior of the method named test , when called on a reference to an object of
type A , is dierent from the behavior of the method named test when called on a reference to an object
of type B .
note:
note:
note:
3.12.6.2 Answer 9
D. A
3.12.6.2.1 Explanation 9
Compiles and executes successfully
This program compiles and executes successfully causing the version of the method named test , which
is overridden in the class named A to be executed. That overridden method is shown in the following
fragment.
note:
note:
note:
myVar.test();
Again, you need to know when downcasting is required, when it isn't required, and to make use of that
knowledge to downcast appropriately.
Back to Question 9 (p. 253)
3.12.6.3 Answer 8
D. A
3.12.6.3.1 Explanation 8
Compiles and executes successfully
This program compiles and executes successfully causing the version of the method named test , which
is overridden in the class named A to be executed. That overridden method is shown in the following
fragment.
note:
note:
This would be a simple case of polymorphic behavior were it not for the downcast shown in the above
fragment.
The downcast is redundant
Actually, the downcast was placed there to see if you could determine that it is redundant. It isn't
required, and it has no impact on the behavior of this program. This program would behave exactly the
same if the second statement in the above fragment were replaced with the following statement, which does
not contain a downcast.
note:
myVar.test();
You need to know when downcasting is required, when it isn't required, and to make use of that knowledge
to downcast appropriately.
Back to Question 8 (p. 252)
3.12.6.4 Answer 7
B. Runtime Error
3.12.6.4.1 Explanation 7
Storing a reference as a superclass type
You can store an object's reference in any reference variable whose declared type is a superclass of the
actual class from which the object was instantiated.
May need to downcast later
Later on, when you attempt to make use of that reference, you may need to downcast it. Whether or
not you will need to downcast will depend on what you attempt to do.
In order to call a method ...
For example, if you attempt to call a method on the reference, but that method is not dened in or
inherited into the class of the reference variable, then you will need to downcast the reference in order to
call the method on that reference.
Class Base denes method named test
This program denes a class named Base that denes a method named test .
Class A extends Base and overrides test
The program also denes a class named A that extends Base and overrides the method named test
as shown in the following fragment.
note:
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
note:
note:
myVar.test();
This statement would cause the version of the method named test dened in the class named Base to
be called, causing the wordBase to appear on the standard output device.
This downcast is not allowed
However, this program attempts to cause the version of the method named test dened in the class
named A to be called, by downcasting the reference to type A before calling the method named test .
This is shown in the following fragment.
note:
((A)myVar).test();
note:
3.12.6.5 Answer 6
C. Base
3.12.6.5.1 Explanation 6
Totally straightforward code
This rather straightforward program instantiates an object of the class named Base and assigns that
object's reference to a reference variable of the type Base as shown in the following fragment .
note:
note:
class Base{
public void test(){
System.out.print("Base ");};
}//end class Base
note:
3.12.6.6 Answer 5
A. Compiler Error
3.12.6.6.1 Explanation 5
Cannot instantiate an abstract class
This program denes an abstract class named Base . Then it violates one of the rules regarding
abstract classes, by attempting to instantiate an object of the abstract class as shown in the following
code fragment.
note:
The program produces the following compiler error under JDK 1.3:
note:
3.12.6.7 Answer 4
C. A
3.12.6.7.1 Explanation 4
An abstract class with an abstract method
This program illustrates the use of an abstract class containing an abstract method to achieve
polymorphic behavior .
The following code fragment shows an abstract class named Base that contains an abstract
method named test .
note:
note:
note:
This causes the overridden version of the method named test , shown in the following fragment, to be
called, which causes the letter A to be displayed on the standard output device.
note:
3.12.6.8 Answer 3
A. Compiler Error
3.12.6.8.1 Explanation 3
Classes can be nal or abstract, but not both
A class in Java may be declared nal . A class may also be declared abstract . A class cannot be
declared both nal and abstract .
Behavior of nal and abstract classes
A class that is declared nal cannot be extended. A class that is declared abstract cannot be
instantiated. Therefore, it must be extended to be useful.
An abstract class is normally intended to be extended.
Methods can be nal or abstract, but not both
A method in Java may be declared nal . A method may also be declared abstract . However, a
method cannot be declared both nal and abstract .
Behavior of nal and abstract methods
A method that is declared nal cannot be overridden. A method that is declared abstract must be
overridden to be useful.
note:
class Base{
abstract public void test();
}//end class Base
Therefore, the program produces the following compiler error under JDK 1.3:
note:
3.12.6.9 Answer 2
C. A
3.12.6.9.1 Explanation 2
If you missed this ...
If you missed this question, you didn't pay attention to the explanation for Question 1 (p. 246) .
Dene a method in a subclass
A that extends a superclass named Base . A method named
This program denes a subclass named
test is dened in the subclass named A but is not dened in any superclass of the class named A .
Store a reference as a superclass type
The program declares a reference variable of the superclass type, and stores a reference to an object of
the subclass in that reference variable as shown in the following code fragment.
note:
note:
((A)myVar).test();
Unlike the program in Question 1 (p. 246) , the reference is downcast to the true type of the object before
calling the method named test . As a result, this program does not produce a compiler error.
Why is the cast required?
As explained in Question 1 (p. 246) , it is allowable to store a reference to a subclass object in a variable
of a superclass type. Also, as explained in Question 1 (p. 246) , it is not allowable to directly call, on that
superclass reference, a method of the subclass object that is not dened in or inherited into the superclass.
However, such a call is allowable if the programmer purposely downcasts the reference to the true type
of the object before calling the method.
Back to Question 2 (p. 246)
3.12.6.10 Answer 1
A. Compiler Error
3.12.6.10.1 Explanation 1
Dene a method in a subclass
This program denes a subclass named A that extends a superclass named Base . A method named
test , is dened in the subclass named A , which is not dened in any superclass of the class named A
.
Store a reference as superclass type
The program declares a reference variable of the superclass type, and stores a reference to an object of
the subclass in that reference variable as shown in the following code fragment.
note:
Note that no cast is required to store a reference to a subclass object in a reference variable of a superclass
type. The required type conversion happens automatically in this case.
Call a method on the reference
Then the program attempts to call the method named test on the reference stored as the superclass
type, as shown in the following fragment. This produces a compiler error.
note:
myVar.test();
note:
note:
((A)myVar).test();
· 1 (p. 266) , 2 (p. 267) , 3 (p. 269) , 4 (p. 270) , 5 (p. 272) , 6 (p. 274) , 7 (p. 276) , 8 (p. 278) ,
9 (p. 280) , 10 (p. 282)
3.13.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 284) to easily nd and view the listings while you are reading about them.
3.13.3 Questions
3.13.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 267) ?
• A. Compiler Error
• B. Runtime Error
• C. Base A-intfcMethod
• D. None of the above.
17 This content is available online at <http://cnx.org/content/m45303/1.3/>.
class Worker{
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
X myVar2 = new A();
myVar2.intfcMethod();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
3.143
3.13.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 268) ?
• A. Compiler Error
• B. Runtime Error
• C. A-inherMethod A-intfcMethod
• D. None of the above.
class Worker{
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
Base myVar2 = new A();
myVar2.intfcMethod();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
3.144
3.13.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 270) ?
• A. Compiler Error
• B. Runtime Error
• C. Base A-intfcMethod
• D. None of the above.
class Worker{
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
A myVar2 = new A();
myVar2.intfcMethod();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
3.145
3.13.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 271) ?
• A. Compiler Error
• B. Runtime Error
• C. Base A-intfcMethod
• D. None of the above.
class Worker{
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
X myVar2 = new A();
myVar2.intfcMethod();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
3.146
3.13.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 273) ?
• A. Compiler Error
• B. Runtime Error
• C. A-intfcMethodX B-intfcMethodX
• D. None of the above.
class Worker{
void doIt(){
X myVar1 = new A();
myVar1.intfcMethodX();
X myVar2 = new B();
myVar2.intfcMethodX();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethodX();
}//end X Available for free at Connexions <http://cnx.org/content/col11441/1.121>
3.147
274 CHAPTER 3. OOP SELF-ASSESSMENT
3.13.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 275) ?
• A. Compiler Error
• B. Runtime Error
• C. A-intfcMethodX B-intfcMethodX
• D. None of the above.
class Worker{
void doIt(){
Object[] myArray = new Object[2];
myArray[0] = new A();
myArray[1] = new B();
for(int i=0;i<myArray.length;i++){
myArray[i].intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethodX();
}//end X
276 CHAPTER 3. OOP SELF-ASSESSMENT
3.13.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 277) ?
• A. Compiler Error
• B. Runtime Error
• C. A-intfcMethodX B-intfcMethodX
• D. None of the above.
class Worker{
void doIt(){
Object[] myArray = new Object[2];
myArray[0] = new A();
myArray[1] = new B();
for(int i=0;i<myArray.length;i++){
((X)myArray[i]).intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethodX();
}//end X
278 CHAPTER 3. OOP SELF-ASSESSMENT
3.13.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 279) ?
• A. Compiler Error
• B. Runtime Error
• C. A-intfcMethodX B-intfcMethodX
• D. None of the above.
class Worker{
void doIt(){
X[] myArray = new X[2];
myArray[0] = new A();
myArray[1] = new B();
for(int i=0;i<myArray.length;i++){
myArray[i].intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethodX();
}//end X
280 CHAPTER 3. OOP SELF-ASSESSMENT
3.13.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 281) ?
• A. Compiler Error
• B. Runtime Error
• C. Base A B
• D. None of the above.
class Worker{
void doIt(){
Base myVar = new Base();
myVar.test();
myVar = new A();
myVar.test();
myVar = new B();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");
}//end test()
}//end class Base
interface X{
public void test();
}//end X
interface Y{
public void test();
}//end Y
3.151
3.13.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 283) ?
• A. Compiler Error
• B. Runtime Error
• C. Base A B B
• D. None of the above.
class Worker{
void doIt(){
Base myVar1 = new Base();
myVar1.test();
myVar1 = new A();
myVar1.test();
myVar1 = new B();
myVar1.test();
X myVar2 = (X)myVar1;
myVar2.test();
System.out.println("");
}//end doIt()
}// end class Worker
class Base{
public void test(){
System.out.print("Base ");
}//end test()
}//end class Base
interface X{
public void test();
}//end X
interface Y{
public void test();
}//end Y
3.152
3.13.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.13.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.13.6 Answers
3.13.6.1 Answer 10
C. Base A B B
3.13.6.1.1 Explanation 10
Expansion of the program from Question 9 (p. 280)
The class and interface denitions for the classes and interfaces named Base , A , B , X , and
Y are the same as in Question 9 (p. 280) .
Call the test method dierently
However, the call of the method named test in the object instantiated from the class named B is
somewhat dierent. The dierence is identied by the code in the following fragment.
note:
void doIt(){
Base myVar1 = new Base();
myVar1.test();
myVar1 = new A();
myVar1.test();
myVar1 = new B();
myVar1.test();
X myVar2 = (X)myVar1;
myVar2.test();
System.out.println("");
}//end doIt()
Calling test method on Base-type reference
In Question 9 (p. 280) , and in the above code fragment as well, the method named test was called on
each of the objects using a reference stored in a reference variable of type Base .
Calling the overridden version of test method
This might be thought of as calling the overridden version of the method, through polymorphism, without
regard for anything having to do with the interfaces.
Calling test method on interface-type reference
Then the code shown above calls the same method named test on one of the same objects using a
X .
reference variable of the interface type
Only one test method in each object
Keep in mind that each object denes only one method named test . This single method serves the
dual purpose of overriding the method having the same signature from the superclass, and implementing a
method with the same signature declared in each of the interfaces.
Implementing the interface method
Perhaps when the same method is called using a reference variable of the interface type, it might be
thought of as implementing the interface method rather than overriding the method dened in the superclass.
You can be the judge of that.
The same method is called regardless of reference type
In any event, in this program, the same method is called whether it is called using a reference variable
of the superclass type, or using a reference variable of the interface type.
Illustrates the behavior of signature collisions
The purpose of this and Question 9 (p. 280) is not necessarily to illustrate a useful inheritance and
implementation construct. Rather, these two questions are intended to illustrate the behavior of Java for
the case of duplicated superclass and interface method signatures.
Back to Question 10 (p. 282)
3.13.6.2 Answer 9
C. Base A B
3.13.6.2.1 Explanation 9
A question regarding signature collisions
The question often arises in my classroom as to what will happen if a class inherits a method with a given
signature and also implements one or more interfaces that declare a method with an identical signature.
The answer
The answer is that nothing bad happens, as long as the class provides a concrete denition for a method
having that signature.
Only one method denition is allowed
Of course, only one denition can be provided for any given method signature, so that denition must
satisfy the needs of overriding the inherited method as well as the needs of implementing the interfaces.
An example of signature collisions
The following fragment denes a class named Base that denes a method named test . The code
also denes two interfaces named X and Y , each of which declares a method named test with an
identical signature.
note:
class Base{
public void test(){
System.out.print("Base ");
}//end test()
}//end class Base
interface X{
public void test();
}//end X
interface Y{
public void test();
}//end Y
note:
System.out.print("B ");
}//end test()
}//end class B
note:
void doIt(){
Base myVar = new Base();
myVar.test();
myVar = new A();
myVar.test();
myVar = new B();
myVar.test();
System.out.println("");
}//end doIt()
}// end class Worker
As you probably expected, this causes the following text to appear on the screen:
note:
Base A B
3.13.6.3 Answer 8
C. A-intfcMethodX B-intfcMethodX
3.13.6.3.1 Explanation 8
Similar to previous two programs
This program is very similar to the programs in Question 6 (p. 274) and Question 7 (p. 276) . The
program is Question 6 (p. 274) exposed a specic type mismatch problem. The program in Question 7 (p.
276) provided one solution to the problem.
A dierent solution
The following fragment illustrates a dierent solution to the problem.
note:
void doIt(){
X[] myArray = new X[2];
myArray[0] = new A();
for(int i=0;i<myArray.length;i++){
myArray[i].intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
An array object of the interface type
In this case, rather than to declare the array object to be of type Object , the array is declared to be
of the interface type X .
This is a less generic container than the one declared to be of type Object . Only references to objects
instantiated from classes that implement the X interface, or objects instantiated from subclasses of those
classes can be stored in the container. However, this is often adequate.
What methods can be called?
Since the references are stored as the interface type, any method declared in or inherited into the interface
can be called on the references stored in the container. Of course, the objects referred to by those references
must provide concrete denitions of those methods or the program won't compile.
(Although it isn't implicitly obvious, it is also possible to call any of the eleven methods dened in the
Object class on an object's reference being stored as an interface type. Those eleven methods can be
called on any object, including array objects, regardless of how the references are stored.)
Not the standard approach
If you are dening your own container, this is a satisfactory approach to implementation of the observer
design pattern. However, you cannot use this approach when using containers from the standard collections
framework, because those containers are designed to always store references as the generic type Object .
In those cases, the casting solution of Question 7 (p. 276) (or the use of generics) is required.
Back to Question 8 (p. 278)
3.13.6.4 Answer 7
C. A-intfcMethodX B-intfcMethodX
3.13.6.4.1 Explanation 7
The correct use of an interface
This program illustrates the correct use of an interface. It uses a cast of the interface type in the following
fragment to resolve the problem that was discussed at length in Question 6 (p. 274) earlier.
note:
void doIt(){
Object[] myArray = new Object[2];
myArray[0] = new A();
myArray[1] = new B();
for(int i=0;i<myArray.length;i++){
((X)myArray[i]).intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
Back to Question 7 (p. 276)
3.13.6.5 Answer 6
A. Compiler Error
3.13.6.5.1 Explanation 6
What is a container?
The word container is often used in Java, with at least two dierent meaning. One meaning is to refer
to the type of an object that is instantiated from a subclass of the class named Container . In that case,
the object can be considered to be of type Container , and typically appears in a graphical user interface
(GUI) . That is not the usage of the word in the explanation of this program.
A more generic meaning
In this explanation, the word container has a more generic meaning. It is common to store a collection
of object references in some sort of Java container, such as an array object or a Vector object. In fact,
there is a complete collections framework provided to facilitate that sort of thing ( Vector is one of the
concrete classes in the Java Collections Framework) .
Storing references as type Object
It is also common to declare the type of references stored in the container to be of the class Object .
Because Object is a completely generic type, this means that a reference to any object instantiated from
any class (or any array object) can be stored in the container. The standard containers such as Vector
and Hashtable take this approach.
(Note that this topic became a little more complicated with the release of generics in jdk version 1.5.)
A class named Base and an interface named X
In a manner similar to several previous programs, this program denes a class named Base and an
interface named X as shown in the following fragment.
note:
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethodX();
}//end X
note:
"A-intfcMethodX ");
}//end intfcMethodX()
}//end class A
note:
void doIt(){
Object[] myArray = new Object[2];
myArray[0] = new A();
myArray[1] = new B();
note:
for(int i=0;i<myArray.length;i++){
myArray[i].intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
note:
myArray[i].intfcMethodX();
• clone ()
• equals(Object obj)
• nalize()
• getClass()
• hashCode()
• notify()
• notifyAll()
• toString()
• wait()
• wait(long timeout)
• wait(long timeout,int nanos)
Overridden methods
Some, (but not all) , of the methods in the above list are dened with default behavior in the Object
class, and are meant to be overridden in new classes that you dene. This includes the methods named
equals and toString .
Some of the methods in the above list, such as getClass , are simply utility methods, which are not
meant to be overridden.
Polymorphic behavior applies
If you call one of these methods on an object's reference (being stored as type Object) , polymorphic
behavior will apply. The version of the method overridden in, or inherited into, the class from which the
object was instantiated will be identied and executed.
Otherwise, a cast is required
In order to call any method other than one of the eleven methods in the above list (p. 291) , (on an
object's reference being stored as type Object without using generics) , you must cast the reference to
some other type.
Casting to an interface type
The exact manner in which you write the cast will dier from one situation to the next. In this case, the
problem can be resolved by rewriting the program using the interface cast shown in the following fragment.
note:
void doIt(){
Object[] myArray = new Object[2];
myArray[0] = new A();
myArray[1] = new B();
for(int i=0;i<myArray.length;i++){
((X)myArray[i]).intfcMethodX();
}//end for loop
System.out.println("");
}//end doIt()
3.13.6.6 Answer 5
C. A-intfcMethodX B-intfcMethodX
3.13.6.6.1 Explanation 5
More substantive use of an interface
This program illustrates a more substantive use of the interface than was the case in the previous pro-
grams.
The class named Base
The program denes a class named Base as shown in the following fragment.
note:
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
note:
interface X{
public void intfcMethodX();
}//end X
note:
note:
note:
void doIt(){
X myVar1 = new A();
myVar1.intfcMethodX();
X myVar2 = new B();
myVar2.intfcMethodX();
System.out.println("");
}//end doIt()
note:
A-intfcMethodX B-intfcMethodX
3.13.6.7 Answer 4
C. Base A-intfcMethod
3.13.6.7.1 Explanation 4
Illustrates the use of an interface as a type
The program denes a class named Base , and a class named A , which extends Base , and
implements an interface named X , as shown below.
note:
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
Implementing interfaces
A class may implement none, one, or more interfaces.
The cardinal rule on interfaces
If a class implements one or more interfaces, that class must either be declared abstract, or it must provide
concrete denitions of all methods declared in and inherited into all of the interfaces that it implements. If
the class is declared abstract, its subclasses must provide concrete denitions of the interface methods.
A concrete denition of an interface method
X in this program declares a method named intfcMethod
The interface named . The class named
A provides a concrete denition of that method.
(The minimum requirement for a concrete denition is a method that matches the method signature
and has an empty body.)
Storing object's reference as an interface type
The interesting part of the program is shown in the following code fragment.
note:
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
X myVar2 = new A();
myVar2.intfcMethod();
System.out.println("");
}//end doIt()
The above fragment instantiates a new object of the class named A , and saves a reference to that object
X .
in a reference variable of the declared type
How many ways can you save an object's reference?
Recall that a reference to an object can be held by a reference variable whose type matches any of the
following:
3.13.6.8 Answer 3
C. Base A-intfcMethod
3.13.6.8.1 Explanation 3
What is runtime polymorphic behavior?
One way to describe runtime polymorphic behavior is:
The runtime system selects among two or more methods having the same signature, not on the basis of
the type of the reference variable in which an object's reference is stored, but rather on the basis of the class
from which the object was originally instantiated.
Illustrates simple class and interface inheritance
The program denes a class named Base , and a class named A , which extends Base , and
implements the interface named X , as shown in the following fragment.
note:
class Base{
public void inherMethod(){
System.out.print("Base ");
}//end inherMethod()
}//end class Base
interface X{
public void intfcMethod();
}//end X
note:
void doIt(){
Base myVar1 = new Base();
myVar1.inherMethod();
note:
System.out.println("");
}//end doIt()
The program makes no use of the interface as a type, and exhibits no polymorphic behavior (no decision
among methods having the same signature is required) .
The class named A inherits an abstract method named intfcMethod from the interface and must
dene it. (Otherwise, it would be necessary to declare the class named A abstract.)
The interface is not a particularly important player in this program.
Back to Question 3 (p. 269)
3.13.6.9 Answer 2
A. Compiler Error
3.13.6.9.1 Explanation 2
Simple hierarchical polymorphic behavior
This program is designed to test your knowledge of simple hierarchical polymorphic behavior.
Implement the interface named X
A that extends a class named Base
This program denes a class named , and implements an interface
named X , as shown in the following code fragment.
note:
interface X{
public void intfcMethod();
}//end X
note:
note:
myVar2.intfcMethod();
3.13.6.10 Answer 1
A. Compiler Error
3.13.6.10.1 Explanation 1
I put this question in here just to see if you are still awake.
Can store reference as interface type
A reference to an object instantiated from a class can be assigned to any reference variable whose
declared type is the name of an interface implemented by the class from which the object was instantiated,
or implemented by any superclass of that class.
Dene two classes and an interface
A that
This program denes a class named extends a class named Base . The class named Base
extends Object by default.
The program also denes an interface named X .
Instantiate an object
The following statement instantiates an object of the class named A , and attempts to assign that
object's reference to a reference variable whose type is the interface type named X .
note:
note:
· 1 (p. 300) , 2 (p. 301) , 3 (p. 302) , 4 (p. 303) , 5 (p. 304) , 6 (p. 305) , 7 (p. 306) , 8 (p. 307) ,
9 (p. 308) , 10 (p. 309)
3.14.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 309) to easily nd and view the listings while you are reading about them.
3.14.3 Questions
3.14.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 301) ?
• A. Compiler Error
• B. Runtime Error
• C. Joe Joe false
• D. Joe Joe true
• E. None of the above.
18 This content is available online at <http://cnx.org/content/m45310/1.3/>.
class Worker{
void doIt(){
char[] anArray = {'J','o','e'};
String Str1 = new String(anArray);
String Str2 = new String(anArray);
System.out.println(
Str1 + " " + Str2 + " " +
(Str1 == Str2));
}//end doIt()
}// end class Worker
3.153
3.14.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 302) ?
• A. Compiler Error
• B. Runtime Error
• C. Joe Joe false
• D. Joe Joe true
• E. None of the above.
class Worker{
void doIt(){
char[] anArray = {'J','o','e'};
String Str1 = new String(anArray);
String Str2 = new String(anArray);
System.out.println(
Str1 + " " + Str2 + " " +
Str1.equals(Str2));
}//end doIt()
}// end class Worker
3.154
3.14.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 303) ?
• A. Compiler Error
• B. Runtime Error
• C. ABC DEF GHI
• D. None of the above.
class Worker{
void doIt(){
java.util.ArrayList ref =
new java.util.ArrayList(1);
ref.add("ABC ");
ref.add("DEF ");
ref.add("GHI");
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
}//end doIt()
}// end class Worker
3.155
3.14.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 304) ?
• A. Compiler Error
• B. Runtime Error
• C. ABC DEF GHI
• D. None of the above.
class Worker{
void doIt(){
ArrayList ref =
new ArrayList(1);
ref.add("ABC ");
ref.add("DEF ");
ref.add("GHI");
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
}//end doIt()
}// end class Worker
3.156
3.14.3.5 Question 5
What output is produced by the program shown in Listing 5 (p. 305) ?
• A. Compiler Error
• B. Runtime Error
• C. ABC DEF GHI
• D. None of the above.
import java.util.ArrayList;
class Worker{
void doIt(){
ArrayList ref = null;
ref = new ArrayList(1);
ref.add("ABC ");
ref.add("DEF ");
ref.add("GHI");
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
}//end doIt()
}// end class Worker
3.157
3.14.3.6 Question 6
What output is produced by the program shown in Listing 6 (p. 306) ?
• A. Compiler Error
• B. Runtime Error
• C. ABC DEF GHI
• D. None of the above.
import java.util.ArrayList;
class Worker{
void doIt(){
ArrayList ref = null;
ref.add("ABC ");
ref.add("DEF ");
ref.add("GHI");
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
}//end doIt()
}// end class Worker
3.158
3.14.3.7 Question 7
What output is produced by the program shown in Listing 7 (p. 307) ?
• A. Compiler Error
• B. Runtime Error
• C. ABC DEF GHI
• D. None of the above.
class Worker{
void doIt(){
ArrayList ref = null;
ref = new ArrayList(1);
ref.add("ABC ");
ref.add("DEF ");
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
}//end doIt()
}// end class Worker
3.159
3.14.3.8 Question 8
What output is produced by the program shown in Listing 8 (p. 308) ?
• A. Compiler Error
• B. Runtime Error
• C. Innity
• D. None of the above.
class Worker{
void doIt(){
System.out.println(1.0/0);
}//end doIt()
}// end class Worker
3.160
3.14.3.9 Question 9
What output is produced by the program shown in Listing 9 (p. 308) ?
• A. Compiler Error
• B. Runtime Error
• C. Innity
• D. None of the above.
class Worker{
void doIt(){
System.out.println(1/0);
}//end doIt()
}// end class Worker
3.161
3.14.3.10 Question 10
What output is produced by the program shown in Listing 10 (p. 309) ?
• A. Compiler Error
• B. Runtime Error
• C. AB CD EF
• D. None of the above.
class Worker{
void doIt(){
String[] ref = {"AB ","CD ","EF "};
for(int i = 0; i <= 3; i++){
System.out.print(ref[i]);
}//end forloop
System.out.println("");
}//end doIt()
}// end class Worker
3.162
3.14.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.14.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.14.6 Answers
3.14.6.1 Answer 10
Both of the following occur.
C. AB CD EF
B. Runtime Error
3.14.6.1.1 Explanation 10
Another index out of bounds
This is another example of a program that throws an index out of bounds exception. In this case, since
the container is an array object, the name of the exception is ArrayIndexOutOfBoundsException .
Populate a three-element array object
The code in the following fragment creates and populates a three-element array object containing reference
to three String objects.
note:
void doIt(){
String[] ref = {"AB ","CD ","EF "};
note:
Since index value 3 is outside the bounds of the array, the program throws the following exception and
aborts:
note:
AB CD EF
java.lang.ArrayIndexOutOfBoundsException
at Worker.doIt(Ap150.java:22)
at Ap150.main(Ap150.java:14)
Note however that the program displays the contents of the three String objects referred to by the contents
of the rst three elements in the array before the problem occurs.
That's the way it often is with runtime errors. Often, a program will partially complete its task before
getting into trouble and aborting with a runtime error.
Back to Question 10 (p. 309)
3.14.6.2 Answer 9
B. Runtime Error
3.14.6.2.1 Explanation 9
A setup
If you feel like you've been had, chances are you have been had. The purpose for Question 8 (p. 307)
was to set you up for this question.
Division by zero for integer types
This program deals with the process of dividing by zero for int types. The code in the following
fragment divides the int value 1 by the int value 0.
note:
void doIt(){
System.out.println(1/0);
}//end doIt()
java.lang.ArithmeticException: / by zero
at Worker.doIt(Ap149.java:20)
at Ap149.main(Ap149.java:14)
3.14.6.3 Answer 8
C. Innity
3.14.6.3.1 Explanation 8
A double divide by zero operation
This program deals with the process of dividing by zero for oating values of type double .
The following code fragment attempts to divide the double value 1.0 by the double value 0.
note:
void doIt(){
System.out.println(1.0/0);
}//end doIt()
3.14.6.4 Answer 7
B. Runtime Error
3.14.6.4.1 Explanation 7
This program illustrates anIndexOutOfBounds exception.
Instantiate and populate an ArrayList object
By now, you will be familiar with the kind of container object that you get when you instantiate the
ArrayList class.
The code in the following fragment instantiates such a container, having an initial capacity of one element.
Then it adds two elements to the container. Each element is a reference to an object of the class String
.
note:
void doIt(){
ArrayList ref = null;
ref = new ArrayList(1);
ref.add("ABC ");
ref.add("DEF ");
note:
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
An IndexOutOfBounds exception
As a result, the program throws an IndexOutOfBounds exception. The error produced under JDK
1.3 looks something like the following:
note:
Attempting to access an element with a negative index value would produce the same result.
An ArrayIndexOutOfBounds exception
A similar result occurs if you attempt to access an element in an ordinary array object outside the bounds
of the index values determined by the size of the array. However, in that case, the name of the exception is
ArrayIndexOutOfBounds .
Back to Question 7 (p. 306)
3.14.6.5 Answer 6
B. Runtime Error
3.14.6.5.1 Explanation 6
The infamous NullPointerException
Interestingly, one of the rst things that you read when you start reading Java books, is that there are
no pointers in Java . It is likely that shortly thereafter when you begin writing, compiling, and executing
simple Java programs, one of your programs will abort with an error message looking something like that
shown below :
note:
What is a NullPointerException?
Stated simply, a NullPointerException occurs when you attempt to perform some operation on an
object using a reference that doesn't refer to an object.
That is the case in this program
The following code fragment declares a local reference variable and initializes its value to null .
note:
void doIt(){
ArrayList ref = null;
(A reference variable in Java must either refer to a valid object, or specically refer to no object (null).
Unlike a pointer in C and C++, a Java reference variable cannot refer to something arbitrary.)
In this case, null means that the reference variable doesn't refer to a valid object.
No ArrayList object
Note that the code in the above fragment does not instantiate an object of the class ArrayList and
assign that object's reference to the reference variable.
(The reference variable doesn't contain a reference to an object instantiated from the class named
ArrayList , or an object instantiated from any class for that matter.)
Call a method on the reference
However, the code in the next fragment attempts to add a String object's reference to a nonexistent
ArrayList object by calling the add method on the reference containing null.
note:
ref.add("ABC ");
3.14.6.6 Answer 5
C. ABC DEF GHI
3.14.6.6.1 Explanation 5
The purpose of this program is to
note:
import java.util.ArrayList;
A shortcut
The designers of Java recognized that having to type a fully-qualied name for every reference to a class
in a Java program can become burdensome. Therefore, they provided us with a shortcut that can be used,
so long as we don't need to refer to two or more class les having the same name.
Import directives
The shortcut is called an import directive.
As can be seen above, the import directive consists of the word import followed by the fully-qualied
name of a class le that will be used in the program.
A program may have more than one import directive, with each import directive specifying the location
of a dierent class le.
The import directive(s) must appear before any class or interface denitions in the source code.
The alternative wild-card syntax
An alternative form of the import directive replaces the name of the class with an asterisk.
The asterisk behaves as a wild-card character. It tells the compiler to use any class le that it nds in
that package that matches a class reference in the source code.
The wild-card form should be used with care, because it can sometimes cause the compiler to use a class
le that is dierent from the one that you intended to use (if it nds the wrong one rst) .
Class le name collisions
If your source code refers to two dierent class les having the same name, you must forego the use of
the import directive and provide fully-qualied names for those class les.
Back to Question 5 (p. 304)
3.14.6.7 Answer 4
A. Compiler Error
3.14.6.7.1 Explanation 4
The purpose of this program is to continue to illustrate the use of java packages.
No fully-qualied class names
This program is the same as the program in Question 3 (p. 302) with a major exception. Neither of the
references to the ArrayList class use fully-qualied names in this program. Rather, the references are as
shown in the following fragment.
note:
ArrayList ref =
new ArrayList(1);
Compiler errors
As a result, the JDK 1.3 compiler produces two error messages similar to the following:
note:
3.14.6.8 Answer 3
C. ABC DEF GHI
3.14.6.8.1 Explanation 3
Illustrate the use of java packages
Since it was necessary to make use of a class to illustrate packages, this program also previews the use of
the ArrayList class. We will be very interested in this class later when we study Java data containers.
What is an ArrayList object?
Some of this terminology may not make much sense to you at this point, but I'll go ahead and tell you
anyway, just as a preview.
According to Sun, the ArrayList class provides a
"Resizable-array implementation of the List interface. Implements all optional list operations, and
permits all elements, including null. In addition to implementing the List interface, this class provides
methods to manipulate the size of the array that is used internally to store the list. (This class is roughly
equivalent to Vector , except that it is unsynchronized.)"
Stated more simply ...
Stated more simply, an object of the ArrayList class can be used as a replacement for an array object.
An ArrayList object knows how to increase its capacity on demand, whereas the capacity of a simple
array object cannon change once it is instantiated.
An ArrayList object
The following statement instantiates a new object of the ArrayList class, with an initial capacity for
one element. The initial capacity is determined by the int value passed to the constructor when the object
is instantiated.
note:
java.util.ArrayList ref =
new java.util.ArrayList(1);
the same Java program can refer to those two class les as X.Joe and Y.Joe . This scheme makes it
possible for the Java compiler and the Java virtual machine to distinguish between the two les having the
name Joe.class .
The java and util directories
Again, simplifying things slightly, the code in the above fragment refers to a le named ArrayList.class
, which is stored in a directory named util , which is a subdirectory of a directory named java .
The directory named java is the root of a directory tree containing a very large number of standard Java
class les.
(As an aside, there is another directory named javax, which forms the root of another directory tree
containing class les considered to be extensions to the standard class library.)
Many directories (packages)
Stated simply, a Java package is nothing more or less than a directory containing class les.
The standard and extended Java class libraries are scattered among a fairly large number of directories or
packages (a quick count of the packages in the JDK 1.3 documentation indicates that there are approximately
65 standard and extended packages) .
A fully-qualied class name
With one exception, whenever you refer to a class in a Java program, you must provide a fully-qualied
name for the class, including the path through the directory tree culminating in the name of the class. Thus,
the following is the fully-qualied name for the class whose name is ArrayList .
java.util.ArrayList
(Later we will see another way to accomplish this that requires less typing eort.)
The exception
The one exception to the rule is the use of classes in the java.lang package, (such as Boolean ,
Class , and Double ) . Your source code can refer to classes in the java.lang package without the
requirement to provide a fully-qualied class name.
An ArrayList object
Now back to the use of the object previously instantiated from the class named ArrayList . This is
the kind of object that is often referred to as a container.
(A container in this sense is an object that is used to store references to other objects.)
Many methods available
ArrayList
An object of the class provides a variety of methods that can be used to store object
references and to fetch the references that it contains.
The add method
One of those methods is the method named add .
The following code fragment instantiates three objects of the String class, and stores them in the
ArrayList object instantiated earlier.
(Note that since the initial capacity of the ArrayList object was adequate to store only a single
reference, the following code causes the object to automatically increase its capacity to at least three.)
note:
ref.add("ABC ");
ref.add("DEF ");
ref.add("GHI");
note:
System.out.println(
(String)ref.get(0) +
(String)ref.get(1) +
(String)ref.get(2));
The output
This results in the following being displayed:
ABC DEF GHI
Summary
The above discussion gave you a preview into the use of containers in general, and the ArrayList
container in particular.
However, the primary purpose of this program was to help you to understand the use of packages in Java.
The ArrayList class was simply used as an example of a class le that is stored in a standard Java
package.
Back to Question 3 (p. 302)
3.14.6.9 Answer 2
D. Joe Joe true
3.14.6.9.1 Explanation 2
Two String objects with identical contents
As in Question 1 (p. 300) , the program instantiates two String objects containing identical character
strings, as shown in the following code fragment.
note:
note:
System.out.println(
Str1 + " " + Str2 + " " +
Str1.equals(Str2));
The reason that the equals method returned true in this case was that the author of the String class
provided an overridden version of the equals method.
The default equals method
If the author of the class does not override the equals method, and the default version of the equals
method inherited from Object is called on an object of the class, then according to Sun:
"for any reference values x and y, this method returns true if and only if x and y refer to the same object
(x==y has the value true)"
In other words, the default version of the equals method inherited from the class Object provides
the same behavior as the == operator when applied to object references.
Back to Question 2 (p. 301)
3.14.6.10 Answer 1
C. Joe Joe false
3.14.6.10.1 Explanation 1
The identity operator
This program illustrates the behavior of the == operator (sometimes referred to as the identity operator)
when used to compare references to objects.
Two String objects with identical contents
As shown in the following fragment, this program instantiates two objects of the String class containing
identical character strings.
note:
class Worker{
void doIt(){
char[] anArray = {'J','o','e'};
String Str1 = new String(anArray);
String Str2 = new String(anArray);
The fact that the two String objects contain identical character strings is conrmed by:
• Both objects are instantiated using the same array object of type char as input.
• When the toString representations of the two objects are displayed later, the display of each object
produces Joe on the computer screen.
note:
System.out.println(
Str1 + " " + Str2 + " " +
(Str1 == Str2));
We know that the two objects are of the same type ( String ) and that they contain the same character
strings. Why does the == operator return false?
Doesn't compare the objects
The answer lies in the fact that the above statement doesn't really compare the two objects at all. Rather,
it compares the values stored in the reference variables referring to the two objects. That is not the same as
comparing the objects.
References are not equal
Even though the objects are of the same type and contain the same character string, they are two
dierent objects, located in dierent parts of memory. Therefore, the contents of the two reference variables
containing references to the two objects are not equal.
The correct answer is false
The == operator returns false as it should. The only way that the == operator could return true
is if both reference variables refer to the same object, (which is not the case) .
The bottom line is ...
The == operator cannot be used to compare two objects for equality. However, it can be used to
determine if two reference variables refer to the same object.
Back to Question 1 (p. 300)
-end-
· 1 (p. 320) , 2 (p. 321) , 3 (p. 322) , 4 (p. 323) , 5 (p. 325) , 6 (p. 325) , 7 (p. 326) , 8 (p. 327) ,
9 (p. 327) , 10 (p. 328)
3.15.2 Preface
This module is part of a self-assessment test designed to help you determine how much you know about
object-oriented programming using Java.
The test consists of a series of questions with answers and explanations of the answers.
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back.
I recommend that you open another copy of this document in a separate browser window and use the
links to under Listings (p. 329) to easily nd and view the listings while you are reading about them.
3.15.3 Questions
3.15.3.1 Question 1 .
What output is produced by the program shown in Listing 1 (p. 321) ?
• A. Compiler Error
• B. Runtime Error
• C. OK OK
• D. OK
• E. None of the above.
class Worker{
void doIt(){
Object refA = new MyClassA();
Object refB =
(Object)(new MyClassB());
System.out.print(refA);
System.out.print(refB);
System.out.println("");
}//end doIt()
}// end class Worker
class MyClassA{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassA
class MyClassB{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassB
3.163
3.15.3.2 Question 2
What output is produced by the program shown in Listing 2 (p. 322) ?
• A. Compiler Error
• B. Runtime Error
• C. OK OK
• D. OK
• E. None of the above.
class Worker{
void doIt(){
Object ref1 = new MyClassA();
Object ref2 = new MyClassB();
System.out.print(ref1);
class MyClassA{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassA
class MyClassB{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassB
3.164
3.15.3.3 Question 3
What output is produced by the program shown in Listing 3 (p. 323) ?
• A. Compiler Error
• B. Runtime Error
• C. OK
• D. None of the above.
import java.util.Random;
import java.util.Date;
class Worker{
void doIt(){
Random ref = new Random(
new Date().getTime());
if(ref.nextBoolean()){
throw new IllegalStateException();
}else{
System.out.println("OK");
}//end else
}//end doIt()
}// end class Worker
3.165
3.15.3.4 Question 4
What output is produced by the program shown in Listing 4 (p. 324) ?
• A. Compiler Error
• B. Runtime Error
• C. 5 10 15
• D. None of the above.
import java.util.NoSuchElementException;
public class Ap154{
public static void main(
String args[]){
new Worker().doIt();
}//end main()
}//end class Ap154
class Worker{
void doIt(){
MyContainer ref =
new MyContainer();
ref.put(0,5);
ref.put(1,10);
ref.put(2,15);
System.out.print(ref.get(0)+" ");
System.out.print(ref.get(1)+" ");
System.out.print(ref.get(2)+" ");
System.out.print(ref.get(3)+" ");
}//end doIt()
}// end class Worker
class MyContainer{
private int[] array = new int[3];
3.166
3.15.3.5 Question 5
The source code in Listing 5 (p. 325) is contained in a single le named Ap155.java
What output is produced by the program?
• A. Compiler Error
• B. Runtime Error
• C. OK
• D. None of the above.
3.167
3.15.3.6 Question 6
A Java application consists of the two source les shown in Listing 6 (p. 326) and Listing 7 (p. 326) having
names of AP156.java and AP156a.java
What output is produced by this program?
• A. Compiler Error
• B. Runtime Error
• C. OK
• D. None of the above.
3.168
3.169
3.15.3.7 Question 7
Explain the purpose of the terms @param and @return in Listing 8 (p. 327) . Also explain any of the other
terms that make sense to you.
/**
* Returns the character at the
* specified index. An index ranges from
* <code>0</code> to
* <code>length() - 1</code>.
*
* @param index index of desired
* character.
* @return the desired character.
*/
public char charAt(int index) {
//Note, this method is not intended
// to be operational. Rather, it
// ...
return 'a';//return dummy char
}//end charAt method
}//end class
3.170
3.15.3.8 Question 8
What output is produced by the program shown in Listing 9 ?
• A. Compiler Error
• B. Runtime Error
• C. Tom
• D. None of the above.
3.15.3.9 Question 9
What output is produced by the program shown in Listing 10 (p. 328) ?
• A. Compiler Error
• B. Runtime Error
• C. Tom
• D. None of the above.
class Worker{
void doIt(){
char[] ref = null;
System.out.print(ref);
System.out.print(" ");
ref[0] = 'T';
ref[1] = 'o';
ref[2] = 'm';
System.out.println(ref);
}//end doIt()
}// end class Worker
3.171
3.15.3.10 Question 10
What output is produced by the program shown in Listing 11 (p. 329) ?
• A. Compiler Error
• B. Runtime Error
• C. Joe Tom
• D. None of the above.
class Worker{
void doIt(){
char[] ref = {'J','o','e'};
System.out.print(ref);
System.out.print(" ");
ref[0] = 'T';
ref[1] = 'o';
ref[2] = 'm';
System.out.println(ref);
}//end doIt()
}// end class Worker
3.172
3.15.4 Listings
I recommend that you open another copy of this document in a separate browser window and use the
following links to easily nd and view the listings while you are reading about them.
3.15.5 Miscellaneous
This section contains a variety of miscellaneous information.
• Module name: Ap0140: Self-assessment, Type conversion, casting, common exceptions, public
class les, javadoc comments and directives, and null references
• File: Ap0140.htm
• Originally published: 2004
• Published at cnx.org: 12/18/12
• Revised: 01/02/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
3.15.6 Answers
3.15.6.1 Answer 10
C. Joe Tom
3.15.6.1.1 Explanation 10
This is an upgrade to the program from Question 9 (p. 327) .
Success at last
The code in the following fragment resolves the compilation problem from Question 8 and the runtime
problem from Question 9 (p. 327) .
note:
void doIt(){
char[] ref = {'J','o','e'};
System.out.print(ref);
System.out.print(" ");
ref[0] = 'T';
ref[1] = 'o';
ref[2] = 'm';
System.out.println(ref);
}//end doIt()
Simply initializing the local reference variable named ref satises the compiler, making it possible to
compile the program.
Initializing the local reference variable named ref with a reference to a valid array object eliminates
the NullPointerException that was experienced in Question 9 (p. 327) .
3.15.6.2 Answer 9
B. Runtime Error
3.15.6.2.1 Explanation 9
Purposely initializing a local variable
This is an update to the program from Question 8 (p. 327) . The code in the following fragment solves
the compilation problem identied in Question 8 (p. 327) .
note:
void doIt(){
char[] ref = null;
In particular, initializing the value of the reference variable named ref satises the compiler and makes it
possible to compile the program.
A NullPointerException
However, there is still a problem, and that problem causes a runtime error.
The following statement attempts to use the reference variable named ref to print something on the
screen. This results, among other things, in an attempt to call the toString method on the reference.
However, the reference doesn't refer to an object. Rather, it contains the value null .
note:
System.out.print(ref);
The result is a runtime error with the following infamous NullPointerException message appearing on
the screen:
note:
java.lang.NullPointerException
at java.io.Writer.write(Writer.java:107)
at java.io.PrintStream.write(PrintStream.java:245)
at java.io.PrintStream.print(PrintStream.java:396)
at Worker.doIt(Ap159.java:22)
at Ap159.main(Ap159.java:15)
3.15.6.3 Answer 8
A. Compiler Error
3.15.6.3.1 Explanation 8
Garbage in, garbage out
Earlier programming languages, notably C and C++ allowed you to inadvertently write programs that
process the garbage left in memory by previous programs running there. This happens when the C or C++
programmer fails to properly initialize variables, allowing them to contain left-over garbage from memory.
Member variables are automatically initialized to default values
That is not possible in Java. All member variables in a Java object are automatically initialized to a
default value if you don't write the code to initialize them to some other value.
Local variables are not automatically initialized
Local variables are not automatically initialized. However, your program will not compile if you write
code that attempts to fetch and use a value in a local variable that hasn't been initialized or had a value
assigned to it.
Print an uninitialized local variable
The statement in the following code fragment attempts to fetch and print a value using the uninitialized
local variable named ref .
note:
void doIt(){
char[] ref;
System.out.print(ref);
As a result, the program refuses to compile, displaying the following error message under JDK 1.3.
note:
3.15.6.4 Answer 7
See explanation below.
3.15.6.4.1 Explanation 7
The javadoc.exe program
When you download the JDK from Oracle, you receive a program named javadoc.exe in addition to
several other programs.
The purpose of the javadoc program is to help you document the Java programs that you write. You
create the documentation by running the javadoc program and specifying your source le or les as a
command-line parameter. For example, you can generate documentation for this program by entering the
following at the command line.
note:
javadoc Ap157.java
This le can be opened in a browser to provide a viewer for all of the information contained in the many
related HTML les.
(As a labor saving device, you can also specify a group of input les to the javadoc program, using
wildcard characters as appropriate, to cause the program to produce documentation les for each of the
input les in a single run.)
Special documentation comments and directives
If you include comments in your source code that begin with
/**
and end with
*/
they will be picked up by the javadoc program and become part of the documentation.
In addition to comments, you can also enter a variety of special directives to the javadoc program as
shown in the following program.
note:
/**
* Returns the character at the
* specified index. An index ranges from
* <code>0</code> to
* <code>length() - 1</code>.
*
* @param index index of desired
* character.
* @return the desired character.
*/
public char charAt(int index) {
//Note, this method is not intended
// to be operational. Rather, it
// is intended solely to illustrate
// the generation of javadoc
// documentation for the parameter
// and the return value.
return 'a';//return dummy char
}//end charAt method
}//end class
3.15.6.5 Answer 6
C. OK
3.15.6.5.1 Explanation 6
Public classes in separate les
This program meets the requirement identied in Question 5 (p. 325) . In particular, this program denes
two public classes. The source code for each public class is stored in a separate le. Thus, the program
compiles and executes successfully, producing the text OK on the screen.
Back to Question 6 (p. 325)
3.15.6.6 Answer 5
A. Compiler Error
3.15.6.6.1 Explanation 5
Public classes in separate les
Java requires that the source code for every public class be contained in a separate le. In this case, the
source code for two public classes was contained in a single le. The following compiler error was produced
by JDK 1.3:
note:
3.15.6.7 Answer 4
This program produces both of the following:
• C. 5 10 15
• B. Runtime Error
3.15.6.7.1 Explanation 4
The NoSuchElementException
This program denes, creates, and uses a very simple container object for the purpose of illustrating the
NoSuchElementException .
The code in the following fragment shows the beginning of a class named MyContainer from which
the container object is instantiated.
note:
class MyContainer{
private int[] array = new int[3];
note:
The get method also tests to conrm that the specied index is within the positive bounds of the array.
If not, it throws an exception of the type NoSuchElementException . Otherwise, it returns the value
stored in the specied index of the array.
(As noted earlier, a negative index will cause an ArrayIndexOutOfBoundsException instead of a No-
SuchElementException to be thrown.)
The NoSuchElementException
Thus, this container class illustrates the general intended purpose of the NoSuchElementException
.
Instantiate and populate a container
The remainder of the program simply exercises the container. The code in the following fragment instan-
tiates a new container, and uses the put method to populate each of its three available elements with the
values 5, 10, and 15.
note:
void doIt(){
MyContainer ref =
new MyContainer();
ref.put(0,5);
ref.put(1,10);
ref.put(2,15);
note:
System.out.print(ref.get(0)+" ");
System.out.print(ref.get(1)+" ");
System.out.print(ref.get(2)+" ");
note:
System.out.print(ref.get(3)+" ");
This causes the get method of the container object to throw a NoSuchElementException . The
program was not designed to handle this exception, so this causes the program to abort with the following
text showing on the screen:
note:
5 10 15 java.util.NoSuchElementException
at MyContainer.get(Ap154.java:49)
at Worker.doIt(Ap154.java:30)
at Ap154.main(Ap154.java:15)
(Note that the values of 5, 10, and 15 were displayed on the screen before the program aborted and displayed
the error message.)
Back to Question 4 (p. 323)
3.15.6.8 Answer 3
This program can produce either of the following depending on the value produced by a random boolean
value generator:
• B. Runtime Error
• C. OK
3.15.6.8.1 Explanation 3
Throwing an exception
This program illustrates the use of the throw keyword to throw an exception.
(Note that the throw keyword is dierent from the throws keyword.)
Throw an exception if random boolean value is true
A random boolean value is obtained. If the value is true, the program throws an IllegalStateEx-
ception and aborts with the following message on the screen:
note:
java.lang.IllegalStateException
at Worker.doIt(Ap153.java:29)
at Ap153.main(Ap153.java:20)
If the random boolean value is false, the program runs to completion, displaying the text OK on the
screen.
Instantiate a Random object
The following code fragment instantiates a new object of the Random class and stores the object's
reference in a reference variable named ref .
note:
void doIt(){
Random ref = new Random(
new Date().getTime());
I'm not going to go into a lot of detail about the Random class. Suce it to say that an object of this
class provides methods that will return a pseudo random sequence of values upon successive calls. You might
think of this object as a random value generator.
Seeding the random generator
The constructor for the class accepts a long integer as the seed for the sequence.
(Two Random objects instantiated using the same seed will produce the same sequence of values.)
In this case, I obtained the time in milliseconds, relative to January 1, 1970, as a long integer, and
provided that value as the seed. Thus, if you run the program two times in succession, with a time delay of
at least one millisecond in between, the random sequences will be dierent.
Get a random boolean value
The code in the next fragment calls the nextBoolean method on the Random object to obtain a
random boolean value. (Think of this as tossing a coin with true on one side and false on the other side.)
note:
if(ref.nextBoolean()){
throw new IllegalStateException();
Throw an exception
If the boolean value obtained in the above fragment is true, the code instantiates a new object of the
IllegalStateException class , and uses the throw keyword to throw an exception of this type.
Program aborts
The program was not designed to gracefully handle such an exception. Therefore the program aborts,
displaying the error message shown earlier.
Don't throw an exception
The code in the next fragment shows that if the boolean value tested above is false, the program will
display the text OK and run successfully to completion.
note:
}else{
System.out.println("OK");
}//end else
}//end doIt()
You may need to run the program several times to see both possibilities.
Back to Question 3 (p. 322)
3.15.6.9 Answer 2
The answer is both of the following:
• D. OK
• B. Runtime Error
3.15.6.9.1 Explanation 2
One cast is allowable ...
It is allowable, but not necessary, to cast the type of an object's reference toward the root of the inheritance
hierarchy.
It is also allowable to cast the type of an object's reference along the inheritance hierarchy toward the
actual class from which the object was instantiated.
Another cast is not allowable ...
However, (excluding interface type casts) , it is not allowable to cast the type of an object's reference in
ways that are not related in a subclass-superclass inheritance sense. For example, you cannot cast the type
of an object's reference to the type of a sibling of that object.
Two sibling classes
The code in the following fragment denes two simple classes named MyClassA and MyClassB .
By default, each of these classes extends the class named Object . Therefore, neither is a superclass of
the other. Rather, they are siblings.
note:
class MyClassA{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassA
class MyClassB{
public String toString(){
return "OK ";
}//end test()
}//end class MyClassB
note:
void doIt(){
Object ref1 = new MyClassA();
Object ref2 = new MyClassB();
System.out.print(ref1);
The code in the above fragment causes the text OK to appear on the screen.
Try to cast to a sibling class type
At this point, the reference variable named ref1 holds a reference to an object of type MyClassA .
The reference is being held as type Object .
The statement in the next fragment attempts to cast that reference to type MyClassB , which is a
sibling of the class named MyClassA .
note:
A ClassCastException
The above statement causes a ClassCastException to be thrown, which in turn causes the program
to abort. The screen output is shown below:
note:
OK java.lang.ClassCastException:MyClassA
at Worker.doIt(Ap152.java:24)
at Ap152.main(Ap152.java:14)
(Note that the text OK appeared on the screen before the program aborted and displayed diagnostic
information on the screen.)
Back to Question 2 (p. 321)
3.15.6.10 Answer 1
C. OK OK
3.15.6.10.1 Explanation 1
Type conversion
This program illustrates type conversion up the inheritance hierarchy, both with and without a cast.
Store object's reference as type Object
The following fragment instantiates a new object of the class named MyClassA , and stores that
object's reference in a reference variable of type Object . This demonstrates that you can store an object's
reference in a reference variable whose type is a superclass of the class from which the object was instantiated,
with no cast required.
note:
class Worker{
void doIt(){
Object refA = new MyClassA();
note:
Object refB =
(Object)(new MyClassB());
note:
System.out.print(refA);
System.out.print(refB);
No cast required
This works without the use of a cast because the print method calls the toString method on any
object's reference that it receives as an incoming parameter. The toString method is dened in the
Object class, and overridden in the String class. Polymorphic behavior dictates that in such a situation,
the version of the method belonging to the object will be called regardless of the type of the reference variable
holding the reference to the object.
When would a cast be required?
Had the program attempted to call a method on the reference that is not dened in the Object , class,
it would have been necessary to cast the reference down the inheritance hierarchy in order to successfully
call the method.
Back to Question 1 (p. 320)
-end-
Programming Fundamentals
4.1.2 Welcome
Welcome to Programming Fundamentals.
This group of modules under the heading Programming Fundamentals is not part of a formal course
of study at Austin Community College
2 where I teach. Instead, it is a compilation of material that I have
published over the years for the benet of those students who desire to enroll in ITSE 2321 Object Oriented
Programming
3 but who don't have the required prerequisite knowledge for that course.
If you fall in that category, or if you just want to get a good introduction to computer programming, you
may nd this material useful.
Even if you have completed a programming fundamentals course in another language, or you have con-
siderable programming experience in another language, you may nd this material useful as an introduction
to the Java programming language and its syntax.
Most of the topics are divided into two modules a primary module and a review module. The review
modules contain review questions and answers keyed to the material in the primary modules.
As you work your way through the modules in this group, you should prepare yourself for the more
challenging ITSE 2321 OOP tracks identied below:
341
342 CHAPTER 4. PROGRAMMING FUNDAMENTALS
4.1.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6 http://www.oracle.com/technetwork/java/javase/downloads/index.html
7 http://www.drjava.org/
8 http://www.drjava.org/docs/quickstart/index.html
9 This content is available online at <http://cnx.org/content/m45142/1.2/>.
4.2.2 Preface
This module, which presents some of the similarities and dierences between Java and C++, is provided
solely for the benet of those students who are already familiar with C++ and are making the transition
from C++ into Java.
If you have some familiarity with C++, you may nd the material in this module helpful. If not, simply
skip this module and move on to the next module in the collection.
In general, students in Prof. Baldwin's Java/OOP courses are not expected to have any specic knowledge
of C++.
This module is intended to be general in nature. Therefore, although a few update notes were added
prior to publication at cnx.org, no signicant eort has been made to keep it up to date relative to any
particular version of the Java JDK or any particular version of C++. Changes have occurred in both Java
and C++ since the rst publication of this document in 1997. Those changes may not be reected in this
module.
10 http://net.uom.gr/Books/Manuals/langenviron-a4.pdf
11 http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
While Java does not support multiple class inheritance, single inheritance in Java is similar to C++, but
the manner in which you implement inheritance diers signicantly, especially with respect to the use of
constructors in the inheritance chain.
In addition to the access modiers applied to individual members of a class, C++ allows you to provide
an additional access modier when inheriting from a class. This latter concept is not supported by Java.
goto statement (but goto is a reserved word) . However, it does support
Java does not support the
labeled break continue statements, a feature not supported by C++. In certain restricted situations,
and
labeled break
and continue statements can be used where a goto statement might otherwise be used.
Java does not support operator overloading .
Java does not support automatic type conversions (except where guaranteed safe) .
Unlike C++, Java has a String (cannot be modied)
type, and objects of this type are immutable
. (Note, although I'm not certain, I believe that the equivalent of a Java String type was introduced into
C++ sometime after the original publication of this document.)
Quoted strings are automatically converted into String objects in Java. Java also has a StringBuer
type. Objects of this type can be modied, and a variety of string manipulation methods are provided.
Unlike C++, Java provides true arrays as rst-class objects. There is a length member, which tells you
how big the array is. An exception is thrown if you attempt to access an array out of bounds. All arrays
are instantiated in dynamic memory and assignment of one array to another is allowed. However, when
you make such an assignment, you simply have two references to the same array. Changing the value of an
element in the array using one of the references changes the value insofar as both references are concerned.
Unlike C++, having two "pointers" or references to the same object in dynamic memory is not necessarily
a problem (but it can result in somewhat confusing results) . In Java, dynamic memory is reclaimed
automatically, but is not reclaimed until all references to that memory become NULL or cease to exist.
Therefore, unlike in C++, the allocated dynamic memory cannot become invalid for as long as it is being
referenced by any reference variable.
Java does not support pointers (at least it does not allow you to modify the address contained in
a pointer or to perform pointer arithmetic) . Much of the need for pointers was eliminated by providing
types for arrays and strings. For example, the oft-used C++ declaration char* ptr needed to point to the
rst character in a C++ null-terminated "string" is not required in Java, because a string is a true object
in Java.
A class denition in Java looks similar to a class denition in C++, but there is no closing semicolon.
Also forward reference declarations that are sometimes required in C++ are not required in Java.
The scope resolution operator (::) required in C++ is not used in Java. The dot is used to construct all
fully-qualied references. Also, since there are no pointers, the pointer operator (->) used in C++ is not
required in Java.
In C++, static data members and functions are called using the name of the class and the name of the
static member connected by the scope resolution operator. In Java, the dot is used for this purpose.
Like C++, Java has primitive types such as int , oat , etc. Unlike C++, the size of each primitive
type is the same regardless of the platform. There is no unsigned integer type in Java. Type checking and
type requirements are much tighter in Java than in C++.
Unlike C++, Java provides a true boolean type. (Note, the C++ equivalent of the Java boolean type
may have been introduced into C++ subsequent to the original publication of this document.)
Conditional expressions in Java must evaluate to boolean rather than to integer, as is the case in C++.
Statements such as
if(x+y)...
are not allowed in Java because the conditional expression doesn't evaluate to a boolean .
The char type in C++ is an 8-bit type that maps to the ASCII (or extended ASCII) character
set. The char type in Java is a 16-bit type and uses the Unicode character set (the Unicode values
from 0 through 127 match the ASCII character set) . For information on the Unicode character set see
http://www.unicode.org/
12 .
12 http://www.unicode.org/
Unlike C++, the operator in Java is a "signed" right bit shift, inserting the sign bit into the vacated
bit position. Java adds an operator that inserts zeros into the vacated bit positions.
C++ allows the instantiation of variables or objects of all types either at compile time in static memory or
at run time using dynamic memory. However, Java requires all variables of primitive types to be instantiated
at compile time, and requires all objects to be instantiated in dynamic memory at runtime. Wrapper classes
are provided for all primitive types to allow them to be instantiated as objects in dynamic memory at runtime
if needed.
C++ requires that classes and functions be declared before they are used. This is not necessary in Java.
The "namespace" issues prevalent in C++ are handled in Java by including everything in a class, and
collecting classes into packages.
C++ requires that you re-declare static data members outside the class. This is not required in Java.
In C++, unless you specically initialize variables of primitive types, they will contain garbage. Although
local variables of primitive types can be initialized in the declaration, primitive data members of a class cannot
be initialized in the class denition in C++.
In Java, you can initialize primitive data members in the class denition. You can also initialize them in
the constructor. If you fail to initialize them, they will be initialized to zero (or equivalent) automatically.
Like C++, Java supports constructors that may be overloaded. As in C++, if you fail to provide
a constructor, a default constructor will be provided for you. If you provide a constructor, the default
constructor is not provided automatically.
All objects in Java are passed by reference, eliminating the need for the copy constructor used in C++.
(In reality, all parameters are passed by value in Java. However, passing a copy of a reference variable
makes it possible for code in the receiving method to access the object referred to by the variable, and
possibly to modify the contents of that object. However, code in the receiving method cannot cause the
original reference variable to refer to a dierent object.)
There are no destructors in Java. Unused memory is returned to the operating system by way of a
garbage collector , which runs in a dierent thread from the main program. This leads to a whole host of
subtle and extremely important dierences between Java and C++.
Like C++, Java allows you to overload functions (methods) . However, default arguments are not
supported by Java.
Unlike C++, Java does not support templates. Thus, there are no generic functions or classes. (Note,
generics similar to C++ templates were introduced into Java in version 5 subsequent to the original publi-
cation of this document.)
Unlike C++, several "data structure" classes are contained in the "standard" version of Java. (Note,
the Standard Template Library was introduced into the C++ world subsequent to the original publication
of this document.)
More specically, several "data structure" classes are contained in the standard class library that is
distributed with the Java Development Kit (JDK). For example, the standard version of Java provides the
containers Vector and Hashtable that can be used to contain any object through recognition that any
object is an object of type Object . However, to use these containers, you must perform the appropriate
upcasting and downcasting, which may lead to eciency problems. (Note, the upcasting and downcasting
requirements were eliminated in conjunction with the introduction of "generics" into Java mentioned earlier.)
Multithreading is a standard feature of the Java language.
Although Java uses the same keywords as C++ for access control: private , public , and protected
, the interpretation of these keywords is signicantly dierent between Java and C++.
There is no virtual keyword in Java. All non-static methods use dynamic binding, so the virtual
keyword isn't needed for the same purpose that it is used in C++.
Java provides the nal keyword that can be used to specify that a method cannot be overridden and
that it can be statically bound. (The compiler may elect to make it inline in this case.)
The detailed implementation of the exception handling system in Java is signicantly dierent from that
in C++.
Unlike C++, Java does not support operator overloading. However, the (+) and (+=) operators are
automatically overloaded to concatenate strings, and to convert other types to string in the process.
As in C++, Java applications can call functions written in another language. This is commonly referred
to as native methods . However, applets cannot call native methods.
Unlike C++, Java has built-in support for program documentation. Specially written comments can be
automatically stripped out using a separate program named javadoc to produce program documentation.
Generally Java is more robust than C++ due to the following:
4.2.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.3.2 Preface
4.3.2.1 General
This module is part of a sub-collection of modules designed to help you learn to program computers.
This module explains how to get started programming using the Java programming language.
4.3.2.2 Prerequisites
In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to
work through the exercises in these modules:
The minimum prerequisites for understanding the material in these modules include:
• An understanding of algebra.
• An understanding of all of the material covered in the earlier modules in this collection.
4.3.2.3.1 Listings
• Listing 1 (p. 349) . Windows batch le.
• Listing 2 (p. 350) . A test program.
14 http://www.oracle.com/technetwork/java/javase/downloads/index.html
15 http://download.oracle.com/javase/7/docs/api/
16 http://www.oracle.com/technetwork/java/javase/downloads/index.html
17 http://download.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installation-windows.html
echo off
cls
del *.class
pause
4.1
18 http://www.oracle.com/technetwork/java/javase/documentation/index.html
19 http://download.oracle.com/javase/7/docs/api/
20 http://www.oracle.com/technetwork/java/javase/downloads/index.html
• Open a command-line screen for the folder containing the batch le.
• Delete all of the compiled class les from the folder. (If the folder doesn't contain any class les, this
will be indicated on the command-line screen.)
• Attempt to compile the program in the le named hello.java.
• Attempt to run the compiled program using a compiled Java le named hello.class .
• Pause and wait for you to dismiss the command-line screen by pressing a key on the keyboard.
If errors occur, they will be reported on the command-line screen and the program won't be executed.
If your program is named something other than hello , (which it typically would be) substitute the
new name for the word hello where it appears twice in the batch le.
Don't delete the pause command
The pause command causes the command-line window to stay on the screen until you dismiss it by
pressing a key on the keyboard. You will need to examine the contents of the window if there are errors
when you attempt to compile and run your program, so don't delete the pause command.
Translate to other operating systems
The format of the batch le in Listing 1 (p. 349) is a Windows format. If you are using a dierent
operating system, you will need to translate the information in Listing 1 (p. 349) into the correct format for
your operating system.
class hello {
public static void main(String[] args){
System.out.println("Hello World");
}//end main
}//end class
4.2
Instructions
Copy the code shown in Listing 2 (p. 350) into a text le named hello.java and store in an empty
folder somewhere on your disk.
Create a batch le named hello.bat containing the text shown in Listing 1 (p. 349) and store that le
in the same folder as the le named hello.java .
Execute the batch le.
If everything is working, a command-line screen should open and display the following text:
Hello World
Press any key to continue . . .
Congratulations
If that happens, you have just written, compiled and executed your rst Java program.
Oops
If that doesn't happen, you need to go back to the installation instructions and see if you can determine
why the JDK isn't properly installed.
If you get an error message similar to the following, that probably means that you didn't set the path
environment variable correctly.
4.3.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 352) , 2 (p. 352) , 3 (p. 352) , 4 (p. 352) , 5 (p. 352) , 6 (p. 352)
4.4.2 Preface
This module contains review questions and answers keyed to the module titled Jb0110: Java OOP: Pro-
gramming Fundamentals, Getting Started
22 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.4.3 Questions
4.4.3.1 Question 1 .
True or false? You need a special IDE to write Java code.
Answer 1 (p. 355)
4.4.3.2 Question 2
True or false? All of the software that you need to create, compile, and run Java programs is free.
Answer 2 (p. 355)
4.4.3.3 Question 3
True or false? Installing the Java JDK can be a little dicult.
Answer 3 (p. 355)
4.4.3.4 Question 4
True or false? Java is so easy that you don't need documentation to program using Java.
Answer 4 (p. 355)
4.4.3.5 Question 5
True or false? The most fundamental way to compile and run Java applications is from the command line.
Answer 5 (p. 355)
4.4.3.6 Question 6
Write a simple test program that can be used to conrm that the JDK is properly installed on your system.
Answer 6 (p. 354)
4.4.4 Listings
• Listing 1 (p. 354) . A Java test program.
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
Here is another image that was inserted for the same purpose to insert space between the questions
and the answers.
4.4.5 Answers
4.4.5.1 Answer 6
If you can compile and run the program code shown in Listing 1 (p. 354) , the JDK is probably installed
properly on your computer.
class hello {
public static void main(String[] args){
System.out.println("Hello World");
}//end main
}//end class
4.3
4.4.5.2 Answer 5
True. Although a variety of IDEs are available that can be used to compile and run Java applications, the
most fundamental way is to compile and run the programs from the command line. A batch le in Windows,
or the equivalent in other operating systems, can be of some help in reducing the amount of typing required
to compile and run a Java application from the command line.
Back to Question 5 (p. 352)
4.4.5.3 Answer 4
False. Java uses huge class libraries, which few if any of us can memorize. Therefore, it is very dicult to
program in Java without access to the documentation for the JDK.
As of November 2012, several dierent types of Java documentation are available online at
http://www.oracle.com/technetwork/java/javase/documentation/index.html
23 .
Back to Question 4 (p. 352)
4.4.5.4 Answer 3
True. Installing the Java JDK can be a little dicult depending on your experi-
ence and knowledge. As of November 2012, you will nd installation instructions at
http://download.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installation-windows.html
24
.
Back to Question 3 (p. 352)
4.4.5.5 Answer 2
True. You will need to download and install the free Java JDK from
the Oracle/Sun website. As of November, 2012, you will nd that website at
http://www.oracle.com/technetwork/java/javase/downloads/index.html
25
Back to Question 2 (p. 352)
4.4.5.6 Answer 1
False. You can write Java code using any plain text editor. You simply need to cause the output le to have
an extension of .java.
Back to Question 1 (p. 352)
4.4.6 Miscellaneous
This section contains a variety of miscellaneous information.
23 http://www.oracle.com/technetwork/java/javase/documentation/index.html
24 http://download.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installation-windows.html
25 http://www.oracle.com/technetwork/java/javase/downloads/index.html
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.5.2 Preface
The purpose of this module is to present the rst complete Java program of the collection that previews the
most common forms of the three pillars of procedural programming:
• sequence
• selection
• loop
• calling a method,
• passing a parameter to the method, and
• receiving a returned value from the method.
As mentioned above, this is simply a preview. Detailed discussions of these topics will be presented in future
modules.
26 This content is available online at <http://cnx.org/content/m45220/1.2/>.
4.5.2.1.1 Images
• Image 1 (p. 358) . Program output.
4.5.2.1.2 Listings
• Listing 1 (p. 360) . Source code for FirstProgram.
4.5.3 Discussion
4.5.3.1 Instructions for compiling and running the program
Assuming that the Java Development Kit (JDK) is properly installed on your computer (see Jb0110:
Java OOP: Programming Fundamentals, Getting Started 27 ), do the following to compile and run this
program.
1. Copy the text from Listing 1 (p. 360) into a text le named FirstProgram.java and store the le
in a folder on your disk.
2. Open a command-line window in the folder containing the le.
3. Type the following command at the prompt to compile the program:
javac FirstProgram.java
4. Type the following command at the prompt to run the program:
java FirstProgram
4.5.3.2 Comments
Any text in the program code that begins with // is a comment. The compiler will ignore everything from
the // to the end of the line.
Comments were inserted into the program code to explain the code.
The compiler also ignores blank lines.
Note that this program was designed to illustrate the concepts while being as non-cryptic as possible.
27 http://cnx.org/content/m45137
value in = 5
Odd time = 1353849164875
countA = 0
countA = 1
countA = 2
countB = 0
countB = 1
countB = 2
value out = 10
4.4
4.5.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
File: FirstProgram.java
Copyright 2012, R.G. Baldwin
sequence
selection
loop
value in = 5
Odd time = 1353849164875
countA = 0
countA = 1 Available for free at Connexions <http://cnx.org/content/col11441/1.121>
countA = 2
countB = 0
countB = 1
361
-end-
4.6.2 Preface
4.6.2.1 General
This module is part of a sub-collection of modules designed to help you learn to program computers.
It provides a gentle introduction to Java programming.
4.6.2.2 Prerequisites
In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to
work through the exercises in these modules:
The minimum prerequisites for understanding the material in these modules include:
• An understanding of algebra.
• An understanding of all of the material covered in the earlier modules in this collection.
4.6.2.3.1 Images
• Image 1 (p. 364) . A checkout counter algorithm.
4.6.2.3.2 Listings
• Listing 1 (p. 365) . Program named Memory01.
• Listing 2 (p. 366) . Batch le for Memory01.
4.6.3.2 Compartments
As the computer program performs its calculations in the correct order, it is often necessary for it to store
intermediate results someplace, and then come back and get them to use them in subsequent calculations
later. The intermediate results are stored in memory, often referred to as RAM or Random Access Memory
.
A mechanical analogy
We can think of random access memory as being analogous to a metal rack containing a large number of
compartments. The compartments are all the same size and are arranged in a column. Each compartment
has a numeric address printed above it. No two compartments have the same numeric address. Each
compartment also has a little slot into which you can insert a name or a label for the compartment. No two
compartments can have the same name.
Joe, the computer program
Think of yourself as a computer program. You have the ability to write values on little slips of paper and
to put them into the compartments. You also have the ability to read the values written on the little slips
of paper and to use those values for some purpose. However, there are two rules that you must observe:
• You may not remove a slip of paper from a compartment without replacing it by another slip of paper
on which you have written a value.
• You may not put a slip of paper in a compartment without removing the one already there.
Initialization
Each morning, the owner of the grocery store tells you to insert a name in the slot above each compartment
and to place a little slip of paper with a number written on it inside each compartment. (In programming
jargon, we would refer to this as initialization.)
Each of the names on the compartments represents a type of grocery such as
• Beans
• Apples
• Pears
In programming jargon, we would say that as you process each grocery item for the same customer, you are
looping . We would also say that you are executing a procedure or an algorithm .
When you have processed all of the grocery items for a particular customer, you would
4.6
• sequence
• selection
• loop
Sequence
A sequence of operations is illustrated by the three items labeled a, b, and c in Image 1 (p. 364) because
they are executed in sequential order.
Selection
The process of identifying the type of grocery item is often referred to as selection . A selection operation
is the process of selecting among two or more choices.
Loop
The process of repetitively examining each grocery item and processing it is commonly referred to as a
loop . In the early days of programming, for a programming language named FORTRAN, this was referred
to as a do loop .
An algorithm
The entire procedure is often referred to as an algorithm .
Modifying stored data
Sometimes during the day, the owner of the grocery store may come to you and say that he is going to
increase the price of a can of Beans from 15 cents to 25 cents and asks you to take care of the change in
price.
You write 25 on a slip of paper and put it in the compartment labeled Beans, being careful to remove
and destroy the slip of paper that was previously in that compartment. For the rest of the day, the new
price for Beans will be used in your calculations unless the owner asks you to change it again.
//File Memory01.java
class Memory01 {
public static void main(String[] args){
int beans;
beans = 25;
System.out.println(beans);
}//end main
}//End Memory01 class
4.7
Listing 2 (p. 366) shows a batch le that you can use to compile and run this program.
echo off
cls
del *.class
pause
4.8
Using the procedure that you learned in the Getting Started 31 module, you should be able to compile
and execute this program. When you do, the program should display 25 on your computer screen.
Variables
You will learn in a future lesson that the term variable is synonymous with the term compartment
that I have used for illustration purposes in this lesson.
The important lines of code
The use of memory is illustrated by the three lines of code in Listing 1 (p. 365) that begin with int ,
beans , and System . We will ignore the other lines in the program in this module and learn about
them in future modules.
Declaring a variable
A memory compartment (or variable) is set aside and given the name beans by the line that begins
with int in Listing 1 (p. 365) .
In programmer jargon, this is referred to as declaring a variable . The process of declaring a variable
That name can be used later to refer to the value stored in that chunk of memory or variable.
This declaration in Listing 1 (p. 365) species that any value stored in the variable must be of type int
. Basically, this means that the value must be an integer. Beyond that, don't worry about what the type
means at this point. I will explain the concept of type in detail in a future module.
Storing a value in the variable
A value of 25 is stored in the variable named beans by the line in Listing 1 (p. 365) that begins with
the word beans .
In programmer jargon, this is referred to as assigning a value to a variable .
From this point forward, when the code in the program refers to this variable by its name, beans , the
reference to the variable will be interpreted to mean the value stored there.
Retrieving a value from the variable
The line in Listing 1 (p. 365) that begins with the word System reads the value stored in the variable
named beans by referring to the variable by its name.
31 http://cnx.org/content/m45137/latest/
This line also causes that value to be displayed on your computer screen. However, at this point, you
needn't worry about what causes it to be displayed. You will learn those details in a future module. Just
remember that the reference to the variable by its name, beans , reads the value stored in the variable.
The remaining details
Don't be concerned at this point about the other details in the program. They are there to make it
possible for you to compile and execute the program. You will learn about them in future modules.
4.6.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 368) , 2 (p. 368) , 3 (p. 368) , 4 (p. 368) , 5 (p. 368) , 6 (p. 369) , 7 (p. 369) , 8 (p. 369) ,
9 (p. 369) , 10 (p. 369) , 11 (p. 369)
4.7.2 Preface
This module contains review questions and answers keyed to the module titled Jb0120: Java OOP: A Gentle
Introduction to Java Programming
33 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.7.3 Questions
4.7.3.1 Question 1 .
True or false? All data is stored in a computer in numeric form. Computer programs do what they do by
executing a series of calculations on numeric data. It is the order and the pattern of those calculations that
distinguishes one computer program from another.
Answer 1 (p. 372)
4.7.3.2 Question 2
True or false? When we program using Java, we must perform most of the detailed work.
Answer 2 (p. 372)
4.7.3.3 Question 3
True or false? As the computer program performs its calculations in the correct order, it is often necessary
for it to store intermediate results someplace, and then come back and get them to use them in subsequent
calculations later.
Answer 3 (p. 371)
4.7.3.4 Question 4
True or false? The structured solution to a computer programming problem is often called an algorithm.
Answer 4 (p. 371)
4.7.3.5 Question 5
Which, if any of the following activities is not commonly believed to be fundamental activities of any computer
program:
• A. sequence
• B. selection
• C. loop
4.7.3.6 Question 6
True or false? As a programmer using a high-level language such as Java, you usually don't have to be
concerned about the numeric memory addresses of variables.
Answer 6 (p. 371)
4.7.3.7 Question 7
Why is modern computer memory often referred to as RAM?
Answer 7 (p. 371)
4.7.3.8 Question 8
True or false? The process of declaring a variable
4.7.3.9 Question 9
True or false? A value of the type int must be an integer.
Answer 9 (p. 371)
4.7.3.10 Question 10
True or false? In programmer jargon, storing a value in a variable is also referred to as assigning a value to
a variable.
Answer 10 (p. 371)
4.7.3.11 Question 11
True or false? A reference to a variable name in Java code returns the value stored in the variable.
Answer 11 (p. 371)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.7.4 Answers
4.7.4.1 Answer 11
True.
Back to Question 11 (p. 369)
4.7.4.2 Answer 10
True.
Back to Question 10 (p. 369)
4.7.4.3 Answer 9
True.
Back to Question 9 (p. 369)
4.7.4.4 Answer 8
False. The process of declaring a variable
4.7.4.5 Answer 7
Modern computer memory is often called RAM or random access memory because it can be accessed in
any order.
Back to Question 7 (p. 369)
4.7.4.6 Answer 6
True. You are able to think about variables and refer to them in terms of their names. (Names are easier to
remember than numeric addresses). However, deep inside the computer, these names are cross-referenced
to addresses and at the lowest level, the program works with memory addresses instead of names.
Back to Question 6 (p. 369)
4.7.4.7 Answer 5
None. All three are commonly believed to be the fundamental activities of any computer program.
Back to Question 5 (p. 368)
4.7.4.8 Answer 4
True.
Back to Question 4 (p. 368)
4.7.4.9 Answer 3
True.
Back to Question 3 (p. 368)
4.7.4.10 Answer 2
False. Fortunately, when we program using a high-level programming language such as Java, much of the
detailed work is done for us behind the scenes.
Back to Question 2 (p. 368)
4.7.4.11 Answer 1
True.
Back to Question 1 (p. 368)
4.7.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.8.2 Preface
4.8.2.1 General
This module is part of a sub-collection of modules designed to help you learn to program computers.
It provides a gentle introduction to Java programming methods.
4.8.2.2 Prerequisites
In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to
work through the exercises in these modules:
The minimum prerequisites for understanding the material in these modules include:
• An understanding of algebra.
• An understanding of all of the material covered in the earlier modules in this collection.
4.8.2.3.1 Listings
• Listing 1 (p. 376) . The price of beans.
• Listing 2 (p. 376) . Compute the square root of the price of beans.
• Listing 3 (p. 377) . Display the square root value.
• Listing 4 (p. 378) . Calling the same methods again.
• Listing 5 (p. 379) . The program named SqRt01.
• Listing 6 (p. 379) . A batch le for compiling and running the program named SqRt01.
35 http://www.oracle.com/technetwork/java/javase/downloads/index.html
36 http://download.oracle.com/javase/7/docs/api/
• perform an action
• send back an answer. or
• some combination of the two
Performing an action
An example of a method that performs an action is the method named println . We used the println
method in an earlier module to cause information to be displayed on the computer screen. This method does
not need to send back an answer, because that is not the objective of the method. The objective is simply
to display some information.
Sending back an answer
On the other hand, a method that is designed to calculate the square root of a number needs to be able
to send the square-root value back to the program that called the method. After all, it wouldn't be very
useful if the method calculated the square root and then kept it a secret. The process of sending back an
answer is commonly referred to as returning a value .
Returned values can be ignored
Methods can be designed in such a way that they either will or will not return a value. When a method
does return a value, the program that called the method can either pay attention to that value and use it
for some purpose, or ignore it entirely.
For example, in some cases where a method performs an action and also returns a value, the calling
program may elect to ignore the returned value. On the other hand, if the sole purpose of a method is to
return a value, it wouldn't make much sense for a program to call that method and then ignore the value
that is returned (although that would be technically possible) .
double beans;
beans = 25.5;
4.9
4.10
The sqrt method calculates and returns the square root of the number that it receives as its incoming
parameter. In this case, it returns the square root of the price of a can of beans.
A place to save the square root
I needed some place to save the square root value until I could display it on the computer screen later
in the program. I declared another variable named sqRtBns in the code fragment in Listing 2 (p. 376) .
I also caused the value returned from the sqrt method to be stored in, or assigned to, this new variable
named sqRtBns .
How should we interpret this code fragment?
You can think of the process implemented by the code fragment in Listing 2 (p. 376) as follows.
First note that there is an equal sign (=) near the center of the line of code. (Later we will learn that
this is called the assignment operator.)
The code on the left-hand side of the assignment operator causes a new chunk of memory to be set aside
and named sqRtBns . (We call this chunk of code a variable.)
The code on the right-hand side of the assignment operator calls the sqrt method, passing a copy of
the value stored in the beans variable to the method.
When the sqrt method returns the value that is the square root of its incoming parameter, the
assignment operator causes that value to be stored and saved in the variable named sqRtBns .
Now display the square root value
The code in the fragment in Listing 3 (p. 377) causes the value now stored in sqRtBns to be displayed
on the computer screen.
System.out.println(sqRtBns);
4.11
Syntax is a word that is often used in computer programming. The thesaurus in the editor that I am
using to type this document says that a synonym for syntax is grammar.
I also like to think of syntax as meaning something very similar to format.
Syntax for passing parameters
Note the syntax in Listing 2 (p. 376) and Listing 3 (p. 377) for passing a parameter to the method. The
syntax consists of following the name of the method with a pair of matching parentheses that contain the
parameter. If more than one parameter is being passed, they are all included within the parentheses and
separated by commas. Usually, the order of the parameters is important if more than one parameter is being
passed.
Reusing the methods
The purpose of the code fragment in Listing 4 (p. 378) is to illustrate the reusable nature of methods.
double peas;
peas = 36.;
double sqRtPeas = Math.sqrt(peas);
System.out.println(sqRtPeas);
4.12
The code in this fragment calls the same sqrt method that was called before. In this case, the method
is called to calculate the square root of the value stored in the variable named peas instead of the value
stored in the variable named beans .
This fragment saves the value returned from the sqrt method in a new variable named sqRtPeas .
Then the fragment calls the same println method as before to display the value now stored in the variable
named sqRtPeas .
Write once and use over and over
Methods make it possible to write some code once and then use that code many times in the same
program. This is the opposite of in-line code , which requires you to write essentially the same code
multiple times in order to accomplish the same purpose more than once in a program.
//File SqRt01.java
class SqRt01 {
public static void main(String[] args){
double beans;
beans = 25.5;
double sqRtBns = Math.sqrt(beans);
System.out.println(sqRtBns);
double peas;
peas = 36.;
double sqRtPeas = Math.sqrt(peas);
System.out.println(sqRtPeas);
}//end main
}//End SqRt01 class
4.13
Listing 6 (p. 379) contains the commands for a batch le that can be used to compile and run the
program named SqRt01 .
Listing 6: A batch le for compiling and running the program named SqRt01.
echo off
cls
del *.class
pause
4.14
4.8.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 381) , 2 (p. 381) , 3 (p. 381) , 4 (p. 381) , 5 (p. 381) , 6 (p. 382) , 7 (p. 382) , 8 (p. 382) ,
9 (p. 382) , 10 (p. 382) , 11 (p. 382) , 12 (p. 384) , 13 (p. 382) , 14 (p. 383) , 15 (p. 383)
4.9.2 Preface
This module contains review questions and answers keyed to the module titled Jb0130: Java OOP: A Gentle
Introduction to Methods in Java
38 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.9.3 Questions
4.9.3.1 Question 1 .
True or false? Methods are often called functions, procedures, subroutines, and various other names.
Answer 1 (p. 386)
4.9.3.2 Question 2
True or false? A Java method can be thought of as a separate program module that has the ability to do
something useful. Having written the method, you can make it available for use as a helper to your main
program each time your main program needs to have that useful thing done.
Answer 2 (p. 386)
4.9.3.3 Question 3
True or false? In Java, you must write all of the methods that you need.
Answer 3 (p. 385)
4.9.3.4 Question 4
True or false? In the following statement, sqRtPeas is the name of a method.
System.out.println(sqRtPeas);
Answer 4 (p. 385)
4.9.3.5 Question 5
True or false? Java only allows you to use the pre-written methods in the class libraries.
Answer 5 (p. 385)
4.9.3.6 Question 6
Normally, when designing and writing a method such as one that can calculate the square root of a number,
it is desirable to write it in such a way that it can calculate the square root of any number (as opposed to
only one specic number) . How is that accomplished?
Answer 6 (p. 385)
4.9.3.7 Question 7
True or false? According to common programming jargon, the process of causing a method to be executed
is commonly referred to as setting the method.
Answer 7 (p. 385)
4.9.3.8 Question 8
True or false? This process of providing information to a method when you call it is commonly referred to
as sending a message to the method.
Answer 8 (p. 385)
4.9.3.9 Question 9
True or false? When called, a method will usually
• perform an action
• send back an answer. or
• some combination of the two
4.9.3.10 Question 10
True or false? A value of type double can be (almost) any numeric value, positive or negative, with or
without a decimal part.
Answer 10 (p. 385)
4.9.3.11 Question 11
True or false? Java is not a case-sensitive programming language.
Answer 11 (p. 385)
4.9.3.12 Question 12
True or false? The following two rules will generally suce to keep you out of trouble when dening variable
and method names in Java:
4.9.3.13 Question 13
True or false? In Java, the assignment operator is the % character.
Answer 13 (p. 384)
4.9.3.14 Question 14
True or false? The behavior of the sqrt method is to calculate and display the square root of the value
passed to it as a parameter.
Answer 14 (p. 384)
4.9.3.15 Question 15
True or false? The syntax for passing parameters to a method consists of following the name of the method
with a pair of matching parentheses that contain the parameter or parameters. If more than one parameter
is being passed, they are all included within the parentheses and separated by commas. The order of the
parameters is not important.
Answer 15 (p. 384)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.9.4 Answers
4.9.4.1 Answer 15
False. Normally the order in which parameters are passed to a method is very important.
Back to Question 15 (p. 383)
4.9.4.2 Answer 14
False. The behavior of the sqrt method is to calculate and return the square root of the value passed
to it as a parameter.
Back to Question 14 (p. 383)
4.9.4.3 Answer 13
False. In Java, the assignment operator is the = character.
Back to Question 13 (p. 382)
4.9.4.4 Answer 12
True.
Back to Question 12 (p. 382)
4.9.4.5 Answer 11
False. Just like C, C++, and C#, Java is very much a case-sensitive programming language.
Back to Question 11 (p. 382)
4.9.4.6 Answer 10
True.
Back to Question 10 (p. 382)
4.9.4.7 Answer 9
True.
Back to Question 9 (p. 382)
4.9.4.8 Answer 8
False. If you continue in this eld of study, you will learn that we send messages to objects by calling
methods that belong to the objects. The process of providing information to a method when you call it is
commonly referred to as passing parameters to the method.
Back to Question 8 (p. 382)
4.9.4.9 Answer 7
False. The process of causing a method to be executed is commonly referred to as calling or possibly
invoking the method.
Back to Question 7 (p. 382)
4.9.4.10 Answer 6
That is accomplished through the use of something called method parameters .
Back to Question 6 (p. 382)
4.9.4.11 Answer 5
False. In addition to the standard methods that are already available, if you need a method to perform some
function and there is no standard method already available to perform that function, you can write your
own method.
Back to Question 5 (p. 381)
4.9.4.12 Answer 4
False. In the following statement, println is the name of a method. sqRtPeas is the name of a variable
whose contents are being passed as a parameter to the println method.
System.out.println(sqRtPeas);
Back to Question 4 (p. 381)
4.9.4.13 Answer 3
False. The Java programming environment contains a large number of methods (in the class libraries) that
are already available for you to use when you need them.
Back to Question 3 (p. 381)
4.9.4.14 Answer 2
True.
Back to Question 2 (p. 381)
4.9.4.15 Answer 1
True.
Back to Question 1 (p. 381)
4.9.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.10.2 Preface
4.10.2.1 General
This module is part of a sub-collection of modules designed to help you learn to program computers.
It explains Java comments.
4.10.2.2 Prerequisites
In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to
work through the exercises in these modules:
The minimum prerequisites for understanding the material in these modules include:
• An understanding of algebra.
• An understanding of all of the material covered in the earlier modules in this collection.
4.10.2.3.1 Images
• Image 1 (p. 388) . Three styles of comments.
4.10.2.3.2 Listings
• Listing 1 (p. 389) . A multi-line comment.
• Listing 2 (p. 390) . Three single-line comments.
• Listing 3 (p. 390) . The program named Comments01.
• Listing 4 (p. 391) . Batch le to compile and run the program named Comments01.
40 http://www.oracle.com/technetwork/java/javase/downloads/index.html
41 http://download.oracle.com/javase/7/docs/api/
The source code consists of a set of instructions that will later be presented to a special program called a
compiler for the purpose of producing a program that can be executed. In other words, when you write the
source code, you are writing instructions that the compiler will use to produce the executable program.
Some things should be ignored
Sometimes, when you are writing source code, you would like to include information that may be useful
to you, but should be ignored by the compiler. Information of that sort is called a comment .
Three styles of comments
Java supports the three styles of comments shown in Image 1 (p. 388) .
/* This is a
multi-line comment */
//Single-line comment
program code // Another single-line comment
4.15
The multi-line comment style is particularly useful for creating large blocks of information that should
be ignored by the compiler. This style can be used to produce a comment consisting of a single line of text
as well. However, the single-line comment style discussed in the next section requires less typing.
Single-line comments
Single-line comments begin with // and end at the end of the line. The compiler ignores the // and
everything following the slash characters to the end of the line.
This style is particularly useful for inserting short comments throughout the source code. In this case,
the // can appear at the beginning of the line as shown in Image 1 (p. 388) , or can appear anywhere in the
line, including at the end of some valid source code (also shown in Image 1 (p. 388) ) .
/*File Comments01.java
This is a multi-line comment.
*****************************************/
4.16
Single-line comments
Listing 2 (p. 390) shows three single-line comments. Can you spot them? Remember, single-line com-
ments begin with //.
class Comments01 {
//This is a single-line comment
public static void main(String[] args){
System.out.println("Hello World");
}//end main
}//End class
4.17
One of the comments in Listing 2 (p. 390) starts at the beginning of the line. The other two comments
follow some program code.
/*File Comments01.java
This is a multi-line comment.
*****************************************/
class Comments01 {
//This is a single-line comment
public static void main(String[] args){
System.out.println("Hello World");
}//end main
}//End class
4.18
Listing 4 (p. 391) contains the commands for a batch le that can be used to compile and run the
program named Comments01 .
Listing 4: Batch le to compile and run the program named Comments01.
echo off
cls
del *.class
pause
4.19
4.10.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 392) , 2 (p. 392) , 3 (p. 392) , 4 (p. 392) , 5 (p. 392) , 6 (p. 392) , 7 (p. 393) , 8 (p. 393)
4.11.2 Preface
This module contains review questions and answers keyed to the module titled Jb0140: Java OOP: Java
comments
43 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.11.3 Questions
4.11.3.1 Question 1 .
True or false? Comments in your source code are ignored by the compiler.
Answer 1 (p. 395)
4.11.3.2 Question 2
True or false? Java supports the four styles of comments.
Answer 2 (p. 395)
4.11.3.3 Question 3
True or false? The javadoc tool is a special program that is used to compile Java programs.
Answer 3 (p. 395)
4.11.3.4 Question 4
True or false? Comments recognized by the javadoc tool begin with /** and end with */
Answer 4 (p. 395)
4.11.3.5 Question 5
True or false? Multi-line comments begin with /# and end with #/
Answer 5 (p. 394)
4.11.3.6 Question 6
True or false? The multi-line comment style is particularly useful for creating large blocks of information
that should be ignored by the compiler.
Answer 6 (p. 394)
4.11.3.7 Question 7
True or false? The multi-line comment style cannot be used to produce a comment consisting of a single line
of text.
Answer 7 (p. 394)
4.11.3.8 Question 8
True or false? Single-line comments begin with // and end at the end of the line.
Answer 8 (p. 394)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.11.4 Answers
4.11.4.1 Answer 8
True.
Back to Question 8 (p. 393)
4.11.4.2 Answer 7
False. The multi-line comment style can be used to produce a comment consisting of none, one, or more
lines of text.
Back to Question 7 (p. 393)
4.11.4.3 Answer 6
True.
Back to Question 6 (p. 392)
4.11.4.4 Answer 5
False. Multi-line comments begin with /* and end with */
Back to Question 5 (p. 392)
4.11.4.5 Answer 4
True.
Back to Question 4 (p. 392)
4.11.4.6 Answer 3
False. The javadoc tool is a special program that is used to produce documentation for Java program.
Back to Question 3 (p. 392)
4.11.4.7 Answer 2
False. Java supports the three styles of comments.
Back to Question 2 (p. 392)
4.11.4.8 Answer 1
True.
Back to Question 1 (p. 392)
4.11.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.12.2 Preface
4.12.2.1 General
This module is part of a sub-collection of modules designed to help you learn to program computers.
It introduces Java data types.
4.12.2.2 Prerequisites
In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to
work through the exercises in these modules:
The minimum prerequisites for understanding the material in these modules include:
• An understanding of algebra.
• An understanding of all of the material covered in the earlier modules in this collection.
4.12.2.3.1 Images
• Image 1 (p. 401) . Range of values for whole-number types.
• Image 2 (p. ??) . Denition of oating point.
• Image 3 (p. 402) . Dierent ways to represent 623.57185.
• Image 4 (p. 403) . Relationships between multiplicative factors and exponentiation.
• Image 5 (p. 404) . Other ways to represent the same information.
• Image 6 (p. 404) . Still other ways to represent 623.57185.
• Image 7 (p. 406) . Range of values for oating-point types.
• Image 8 (p. 407) . Example of the use of the boolean type.
4.12.3 Discussion
4.12.3.1 Introduction
Type-sensitive languages
Java and some other modern programming languages make heavy use of a concept that we refer to as
type , or data type .
We refer to those languages as type-sensitive languages . Not all languages are type-sensitive languages.
In particular, some languages hide the concept of type from the programmer and automatically deal with
type issues behind the scenes.
So, what do we mean by type?
One analogy that comes to my mind is international currency. For example, many years ago, I spent a
little time in Japan and quite a long time on an island named Okinawa (Okinawa is now part of Japan) .
Types of currency
At that time, as now, the type of currency used in the United States was the dollar. The type of currency
used in Japan was the yen, and the type of currency used on the island of Okinawa was also the yen. However,
even though two of the currencies had the same name, they were dierent types of currency, as determined
by the value relationships among them.
The exchange rate
As I recall, at that time, the exchange rate between the Japanese yen and the U.S. dollar was 360 yen for
each dollar. The exchange rate between the Okinawan yen and the U.S. dollar was 120 yen for each dollar.
This suggests that the exchange rate between the Japanese yen and the Okinawan yen would have been 3
Japanese yen for each Okinawan yen.
Analogous to dierent types of data
So, why am I telling you this? I am telling you this to illustrate the concept that dierent types of
currency are roughly analogous to dierent data types in programming.
Purchasing transactions were type sensitive
In particular, because there were three dierent types of currency involved, the dierences in the types
had to be taken into account in any purchasing transaction to determine the price in that particular currency.
In other words, the purchasing process was sensitive to the type of currency being used for the purchase
(type sensitive) .
Dierent types of data
Type-sensitive programming languages deal with dierent types of data. Some data types such at type
int involve whole numbers only (no fractional parts are allowed) .
Other data types such as double involve numbers with fractional parts.
Some data types conceptually have nothing to do with numeric values, but deal only with the concept of
true or false ( boolean ) or with the concept of the letters of the alphabet and the punctuation characters
( char ) .
Type specication
For every dierent type of data used with a particular programming language, there is a specication
somewhere that denes two important characteristics of the type:
1. What is the set of all possible data values that can be stored in an instance of the type (we will learn
some other names for instance later) ?
2. Once you have an instance of the type, what are the operations that you can perform on that instance
alone, or in combination with other instances?
There are some other operations that are allowed as well. In fact, there is a well-dened set of operations
that you are allowed to perform on those instances. That set of operations is dened in the specication for
the type short .
What if you want to do something dierent?
However, if you want to perform an operation that is not allowed by the type specication, then you will
have to nd another way to accomplish that purpose.
For example, some programming languages allow you to raise whole-number types to a power (examples:
four squared, six cubed, nine to the fourth power, etc.) . However, that operation is not allowed by the
Java specication for the type short . If you need to do that operation with a data value of the Java
short type, you must nd another way to do it.
• Primitive types
• User-dened or reference types
• Whole-number types
• Floating-point types
• Character types
• Boolean types
Hopefully this categorization will make it possible for me to explain these types in a way that is easier for
you to understand.
• byte
• short
• int
• long
(The char type is also a whole number type, but since it is not intended to be used for arithmetic, I discuss
it later as a character type.)
The four types dier primarily in terms of the range of values that they can accommodate and the amount
of computer memory required to store instances of the types.
Dierences in operations?
Although there are some subtle dierences among the four whole-number types in terms of the operations
that you can perform on them, I will defer a discussion of those dierences until a more advanced module.
(For example some operations require instances of the byte and short types to be converted to type
int before the operation takes place.)
Algebraically signed values
All four of these types can be used to represent algebraically signed values ranging from a specic negative
value to a specic positive value.
Range of the byte type
byte type
For example, the can be used to represent the set of whole numbers ranging from -128 to
+127 inclusive. (This constitutes a set of 256 dierent values, including the value zero.)
The byte type cannot be used to represent any value outside this range. For example, the byte type
cannot be used to represent either -129 or +128.
No fractional parts allowed by the byte type
Also, thebyte type cannot be used to represent fractional values within the allowable range. For
example, the byte type cannot be used to represent the value of 63.5 or any other value that has a fractional
part.
Like a strange odometer
To form a crude analogy, the byte type is sort of like a strange odometer in a new (and unusual) car
that shows a mileage value of -128 when you rst purchase the car. As you drive the car, the negative values
shown on the odometer increment toward zero and then pass zero. Beyond that point they increment up
toward the value of +127.
Oops, numeric overow!
When the value passes (or attempts to pass) +127 miles, something bad happens. From that point
forward, the value shown on the odometer is not a reliable indicator of the number of miles that the car has
been driven.
Ranges for each of the whole-number types
Image 1 (p. 401) shows the range of values that can be accommodated by each of the four whole-number
types supported by the Java programming language:
byte
-128 to +127
short
-32768 to +32767
int
-2147483648 to +2147483647
long
-9223372036854775808 to +9223372036854775807
4.20
A number representation consisting of a mantissa, M, an exponent, E, and an (assumed) radix (or "base") . The number
4.21
47 http://foldoc.org/oating+point
.62357185*1000
6.2357185*100
62.357185*10
623.57185*1
6235.7185*0.1
62357.185*0.01
623571.85*0.001
6235718.5*0.0001
62357185.*0.00001
4.22
In other words, I can represent the value as a mantissa (62357185) multiplied by a factor where the
purpose of the factor is to represent a left or right shift in the position of the decimal point.
Now consider the factor
Each of the factors shown in Image 3 (p. 402) represents the value of ten raised to some specic power,
such as ten squared, ten cubed, ten raised to the fourth power, etc.
Exponentiation
If we allow the following symbol (^) to represent exponentiation (raising to a power) and allow the
following symbol (/) to represent division, then we can write the values for the above factors in the ways
shown in Image 4 (p. 403) .
Note in particular the characters following the rst equal character (=) on each line, which I will refer
to later as the exponents.
4.23
In the above notation, the term 10^+3 means 10 raised to the third power.
The zeroth power
By denition, the value of any value raised to the zeroth power is 1. (Check this out in your high-school
algebra book.)
The exponent and the factor
Hopefully, at this point you will understand the relationship between the exponent and the factor intro-
duced earlier in Image 3 (p. 402) .
Dierent ways to represent the same value
Having reached this point, by using substitution, I can rewrite the original set of representations (p. 402)
of the value 623.57185 in the ways shown in Image 5 (p. 404) .
(It is very important to for you to understand that these are simply dierent ways to represent the same
value.)
.62357185*10^+3
6.2357185*10^+2
62.357185*10^+1
623.57185*10^+0
6235.7185*10^-1
62357.185*10^-2
623571.85*10^-3
6235718.5*10^-4
62357185.*10^-5
4.24
.62357185E+3
6.2357185E+2
62.357185E+1
623.57185E+0
6235.7185E-1
62357.185E-2
623571.85E-3
6235718.5E-4
62357185.E-5
4.25
value which tells how many places to shift the decimal point to the left or to the right in order to determine
the true value.
Positive exponent values mean that the decimal point should be shifted to the right. Negative exponent
values mean that the decimal point should be shifted to the left.
Maintaining fractional parts
One advantage of oating-point types is that they can be used to maintain fractional parts in data values,
such as 6.3 pounds of hamburger.
Accommodating a very large range of values
Another advantage is that a very large range of values can be represented using a reasonably small amount
of computer memory for storage of the values.
Another example
For example (assuming that I counted the number of digits correctly) the following very large value
62357185000000000000000000000000000000.0
can be represented as
6.2357185E+37
Similarly, again assuming that I counted the digits correctly, the following very small value
0.0000000000000000000000000000062357185
can be represented as
6.2357185E-30
When would you use oating-point?
If you happen to be working in an area where you
• need to keep track of fractional parts (such as the amount of hamburger in a package) ,
• have to work with extremely large numbers (distances between galaxies) , or
• have to work with extremely small values (the size of atomic particles) ,
• oat
• double
These two types dier primarily in terms of the range of values that they can support.
Range of values for oating point types
The table in Image 7 (p. 406) shows the smallest and largest values that can be accommodated by
each of the oating-point types. Values of either type can be either positive or negative.
float
1.4E-45 to 3.4028235E38
double
4.9E-324 to 1.7976931348623157E308
4.26
I will discuss the operations that can be performed on oating-point types in a future module.
• true
• false
Generally speaking, about the only operations that can be directly applied to an instance of the boolean
type are to change it from true to false , and vice versa. However, the boolean type can be included
in a large number of somewhat higher-level operations.
The boolean type is commonly used in some sort of a test to determine what to do next, such as that
shown in Image 8 (p. 407) .
4.27
I will discuss the operations that can be performed on the boolean type in more detail in a future module.
The biggest conceptual dierence between the String type and the Person type is that the String
type is contained in the standard Java library while the Person type isn't in that library. However, you
could put it in a library of your own design if you choose to do so.
Removing types
You could easily remove the String type from your copy of the standard Java library if you choose
to do so, although that would probably be a bad idea. However, you cannot remove the primitive double
type from the core language without making major modications to the language.
The company telephone book
A programmer responsible for producing the company telephone book might create a new type that can
be used to store the rst and last names along with the telephone number of an individual. That programmer
might choose to give the new type the name Employee .
The programmer could create an instance of the Employee type to represent each employee in the
company, populating each such instance with the name and telephone number for an individual employee.
(At this point, let me sneak a little jargon in and tell you that we will be referring to such instances as
objects.)
A comparison operation
The programmer might dene one of the allowable operations for the new Employee type to be a
comparison between two objects of the new type to determine which is greater in an alphabetical sorting sense.
This operation could be used to sort the set of objects representing all of the employees into alphabetical
order. The set of sorted objects could then be used to print a new telephone book.
A name-change operation
Another allowable operation that the programmer might dene would be the ability to change the name
stored in an object representing a particular employee. For example when Suzie Smith marries Tom Jones,
she might elect to thereafter be known as
• Suzie Smith
• Suzie Jones,
• Suzie Smith-Jones,
• Suzie Jones-Smith, or
• something entirely dierent.
In this case, there would be a need to modify the object that represents Suzie in order to reect her newly-
elected surname. (Or perhaps Tom Jones might elect to thereafter be known as Tom Jones-Smith, in which
case it would be necessary to modify the object that represents him.)
An updated telephone book
The person charged with maintaining the database could
• use the name-changing operation to modify the object and change the name,
• make use of the sorting operation to re-sort the set of objects, and
• print and distribute an updated version of the telephone book.
You can dene new types. Unlike earlier procedural programming languages such as C and Pascal, you
are no longer forced to adapt your problem to the available tools. Rather, you now have the opportunity to
extend the tools to make them better suited to solve your problem.
The class denition
The specic Java mechanism that makes it possible for you to dene new types is a mechanism known
as the class denition .
In Java, whenever you dene a new class, you are at the same time dening a new type. Your new type
can be as simple, or as complex and powerful as you want it to be.
An object (instance) of your new type can contain a very small amount of data, or it can contain a very
large amount of data. The operations that you allow to be performed on an object of your new type can be
rudimentary, or they can be very powerful.
It is all up to you
Whenever you dene a new class (type) you not only have the opportunity to dene the data denition
and the operations, you also have a responsibility to do so.
Much to learn and much to do
But, you still have much to learn and much to do before you will need to dene new types.
There are a lot of fundamental programming concepts that we will need to cover before we seriously
embark on a study involving the denition of new types.
For the present then, simply remember that such a capability is available, and if you work to expand
your knowledge of Java programming one small step at a time, when we reach the point of dening new
types, you will be ready and eager to do so.
4.12.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 410) , 2 (p. 410) , 3 (p. 410) , 4 (p. 410) , 5 (p. 410) , 6 (p. 411) , 7 (p. 411) , 8 (p. 411) ,
9 (p. 411) , 10 (p. 411) , 11 (p. 411) , 12 (p. 416) , 13 (p. 412) , 14 (p. 412) , 15 (p. 412) , 16
(p. 412) , 17 (p. 412) , 18 (p. 412) , 19 (p. 412) , 20 (p. 412) , 21 (p. 413) , 22 (p. 413) , 23 (p.
413) , 24 (p. 413) , 25 (p. 413) ,
4.13.2 Preface
This module contains review questions and answers keyed to the module titled Jb0150: Java OOP: A Gentle
Introduction to Java Data Types
49 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.13.3 Questions
4.13.3.1 Question 1 .
True or false? Java is a type-sensitive language.
Answer 1 (p. 417)
4.13.3.2 Question 2
True or false? Data type double involves whole numbers only (no fractional parts are allowed) .
Answer 2 (p. 417)
4.13.3.3 Question 3
True or false? Type double involves numbers with fractional parts.
Answer 3 (p. 417)
4.13.3.4 Question 4
True or false? All Java data types conceptually have something to do with numeric values.
Answer 4 (p. 417)
4.13.3.5 Question 5
True or false? The Java char type deals conceptually with the letters of the alphabet, the numeric
characters, and the punctuation characters.
Answer 5 (p. 417)
4.13.3.6 Question 6
True or false? For every dierent type of data used with a particular programming language, there is a
specication somewhere that denes two important characteristics of the type:
1. What is the set of all possible data values that can be stored in an instance of the type?
2. Once you have an instance of the type, what are the operations that you can perform on that instance
alone, or in combination with other instances?
4.13.3.7 Question 7
True or false? If you have an instance of the byte type, the set of all possible values that you can store in
that instance is the set of all the whole numbers ranging from -256 to +255.
Answer 7 (p. 417)
4.13.3.8 Question 8
Name or describe four of the operations that you can perform with data of type short .
Answer 8 (p. 416)
4.13.3.9 Question 9
True or false? Java data types can be subdivided into two major categories:
• Primitive types
• User-dened or reference types
4.13.3.10 Question 10
True or false? The primitive types are not part of the core language.
Answer 10 (p. 416)
4.13.3.11 Question 11
True or false? For purposes of discussion, primitive types can be subdivided into four categories:
• Whole-number types
• Floating-point types
• Character types
• Boolean types
4.13.3.12 Question 12
True or false? In Java, there are three dierent whole-number types:
• byte
• short
• int
4.13.3.13 Question 13
True or false? The whole-number types dier in terms of the range of values that they can accommodate
and the amount of computer memory required to store instances of the types.
Answer 13 (p. 416)
4.13.3.14 Question 14
True or false? Java provides an unsigned version of all of the primitive whole-number types.
Answer 14 (p. 416)
4.13.3.15 Question 15
True or false? Floating point types represent values as a mantissa containing a decimal point along with an
exponent value that tells how many places to shift the decimal point to the left or to the right in order to
determine the true value.
Answer 15 (p. 416)
4.13.3.16 Question 16
True or false? With a oating point type, positive exponent values mean that the decimal point should be
shifted to the left. Negative exponent values mean that the decimal point should be shifted to the right.
Answer 16 (p. 416)
4.13.3.17 Question 17
True or false? Java supports two dierent oating point types:
• oat
• double
4.13.3.18 Question 18
True or false? The purpose of the char type is to make it possible to represent the letters of the alphabet,
the punctuation characters, and the numeric characters internally in the computer. This is accomplished by
assigning a numeric value to each character.
Answer 18 (p. 415)
4.13.3.19 Question 19
True or false? The char type uses a standard character representation known as Unicode to represent
up to 65,535 dierent characters.
Answer 19 (p. 415)
4.13.3.20 Question 20
True or false? In Java, you usually represent a character in your program by surrounding it with quotation
marks as shown below:
"A".
Answer 20 (p. 415)
4.13.3.21 Question 21
True or false? The boolean type can have three values:
• true
• false
• maybe
4.13.3.22 Question 22
True or false? Java is an extensible programming language, meaning that there is a core component to
the language that is always available. Beyond the core component, dierent programmers can extend the
language in dierent ways to meet their individual needs.
Answer 22 (p. 415)
4.13.3.23 Question 23
True or false? As is the case in C++, one of the ways that individual programmers can extend the Java
language is to create overloaded operators for the primitive types.
Answer 23 (p. 415)
4.13.3.24 Question 24
True or false? One of the ways that individual programmers can extend the Java language is to create new
types.
Answer 24 (p. 415)
4.13.3.25 Question 25
True or false? The specic Java mechanism that makes it possible for programmers to dene new types is a
mechanism known as the class denition .
Answer 25 (p. 415)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.13.4 Answers
4.13.4.1 Answer 25
True.
Back to Question 25 (p. 413)
4.13.4.2 Answer 24
True.
Back to Question 24 (p. 413)
4.13.4.3 Answer 23
False. Java does not allow programmers to create overloaded operators for the primitive types.
Back to Question 23 (p. 413)
4.13.4.4 Answer 22
True.
Back to Question 22 (p. 413)
4.13.4.5 Answer 21
False. The boolean type can have only two values:
• true
• false
4.13.4.6 Answer 20
False. In Java, you usually represent a character in your program by surrounding it with apostrophes as
shown below:
'A'.
Back to Question 20 (p. 412)
4.13.4.7 Answer 19
True.
Back to Question 19 (p. 412)
4.13.4.8 Answer 18
True.
Back to Question 18 (p. 412)
4.13.4.9 Answer 17
True.
Back to Question 17 (p. 412)
4.13.4.10 Answer 16
False. With a oating point type, positive exponent values mean that the decimal point should be shifted
to the right . Negative exponent values mean that the decimal point should be shifted to the left .
Back to Question 16 (p. 412)
4.13.4.11 Answer 15
True.
Back to Question 15 (p. 412)
4.13.4.12 Answer 14
False. Other than type char , there are no unsigned whole-number primitive types in Java.
Back to Question 14 (p. 412)
4.13.4.13 Answer 13
True.
Back to Question 13 (p. 412)
4.13.4.14 Answer 12
False. In Java, there are ve dierent whole-number types:
• byte
• short
• int
• long
• char
4.13.4.15 Answer 11
True.
Back to Question 11 (p. 411)
4.13.4.16 Answer 10
False. The primitive types are part of the core language.
Back to Question 10 (p. 411)
4.13.4.17 Answer 9
True.
Back to Question 9 (p. 411)
4.13.4.18 Answer 8
Four of the possible operations are:
4.13.4.19 Answer 7
False. If you have an instance of the byte type, the set of all possible values that you can store in that
instance is the set of all the whole numbers ranging from -128 to +127.
Back to Question 7 (p. 411)
4.13.4.20 Answer 6
True.
Back to Question 6 (p. 411)
4.13.4.21 Answer 5
True.
Back to Question 5 (p. 410)
4.13.4.22 Answer 4
False. In Java, data type boolean conceptually has nothing to do with numeric values, but deals only
with the concept of true or false .
Back to Question 4 (p. 410)
4.13.4.23 Answer 3
True.
Back to Question 3 (p. 410)
4.13.4.24 Answer 2
False. Some data types such at type int involve whole numbers only (no fractional parts are allowed) .
Back to Question 2 (p. 410)
4.13.4.25 Answer 1
True.
Back to Question 1 (p. 410)
4.13.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.14.2 Preface
It is traditional in introductory programming courses to write and explain a simple program that prints the
text "Hello World" on the computer screen.
This module continues that tradition.
4.14.2.1.1 Images
• Image 1 (p. ??) . How to compile and run a Java application.
4.14.2.1.2 Listings
• Listing 1 (p. 421) . Beginning of the class named hello1.
• Listing 2 (p. 421) . Beginning of the main method.
• Listing 3 (p. 422) . Display the string Hello World.
• Listing 4 (p. 422) . End of the class named hello1.
• Listing 5 (p. 424) . Complete program listing.
4.14.3 Introduction
This module introduces you to Java programming by presenting and discussing a traditional Hello World
program.
Two approaches
Java programs can be written and executed in several dierent ways, including the following:
It is also possible in many cases to write applets, which can be run in a stand-alone mode from the command
line, or can be run under control of a Java-capable browser. An example of such an applet will be presented
in a future module.
Applets vs. applications
Programming an "application" in Java is signicantly dierent from programming an "applet." Applets
are designed to be downloaded and executed on-line under control of a browser.
Restrictions on applets
Their functionality of an applet is usually restricted in an attempt to prevent downloaded applets from
damaging your computer or your data. No such restrictions apply to the functionality of a Java application.
Class denitions
All Java programs consist of one or more class denitions. In this course, I will often refer to the
primary class denition for a Java application as the controlling class .
The main method
A stand-alone Java application requires a method named main in its controlling class .
An Applet does not require a main method. The reason that a Java Applet does not require a
main method will be explained in a future module.
Getting started
Image 1 (p. ??) shows the steps for compiling and running a Java application.
1. Download and install the JDK from Oracle. Also consider downloading and installing the documen-
tation, which is a separate download.
2. Using any editor that can produce a plain text le (such as Notepad), create a source code le with
the extension on the le name being .java This le contains your actual Java instructions. (You can copy
some sample programs from the early lessons in this collection to get started.)
3. Open a command-line window and change directory to the directory containing the source le. It
doesn't really matter which directory the source le is in, but I normally put my Java les in a directory all
their own.
4. Assume that the name of the le is joe.java , just to have something denitive to refer to.
5. To compile the le, enter the following command at the prompt:
javac joe.java
6. Correct any compiler errors that show up. Once you have corrected all compiler errors, the javac
program will execute and return immediately to the prompt with no output. At that point, the directory
should also contain a le named joe.class and possibly some other les with a .class extension as well.
These are the compiled Java les.
7. To run the program, enter the following command:
java joe
8. If your program produces the correct output, congratulations. You have written, compiled, and
executed a Java application. If not, you will need to determine why not.
1. Download and install the JDK from Oracle. Also consider downloading and installing the documen-
tation, which is a separate download.
2. Using any editor that can produce a plain text le (such as Notepad), create a source code le with
the extension on the le name being .java This le contains your actual Java instructions. (You can copy
some sample programs from the early lessons in this collection to get started.)
3. Open a command-line window and change directory to the directory containing the source le. It
doesn't really matter which directory the source le is in, but I normally put my Java les in a directory all
their own.
4. Assume that the name of the le is joe.java , just to have something denitive to refer to.
5. To compile the le, enter the following command at the prompt:
javac joe.java
6. Correct any compiler errors that show up. Once you have corrected all compiler errors, the javac
program will execute and return immediately to the prompt with no output. At that point, the directory
should also contain a le named joe.class and possibly some other les with a .class extension as well.
These are the compiled Java les.
7. To run the program, enter the following command:
java joe
8. If your program produces the correct output, congratulations. You have written, compiled, and
executed a Java application. If not, you will need to determine why not.
Here are the steps for compiling and running a Java application, based on the assumption that you are running under Win
4.28
This command instructs the operating system to start the JVM, and then instructs the JVM to nd and
execute the java application stored in the le named hello1.class . (Note that the .class extension is not
included in the command (p. 420) .)
This sample program is a Java application named hello1.java .
When compiled, it produces a class le named hello1.class .
When the program is run, the JVM calls the main method dened in the controlling class .
The main method is a class method.
Class methods can be called without a requirement to instantiate an object of the class.
The program displays the following words on the screen:
Hello World
4.29
The code fragment in Listing 2 (p. 421) begins the denition of the main method. I will also discuss
method denitions in detail in a future module.
4.30
The fragment in Listing 3 (p. 422) causes the string Hello World to be displayed on the command-line
screen.
The statement in Listing 3 (p. 422) is an extremely powerful statement from an object-oriented pro-
gramming viewpoint. When you understand how it works, you will be well on your way to understanding
the Java version of Object-Oriented Programming (OOP).
I will discuss this statement in more detail later in a future module.
System.out.println("Hello World");
4.31
Listing 4 (p. 422) ends the main method and also ends the class denition for the class named hello1
.
}//end main
}//End hello1 class
4.32
4.14.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
hello1.class
java hello1
Hello World
*********************************************************/
class hello1 { //define the controlling class
//define main method
public static void main(String[] args){
//display text string
System.out.println("Hello World");
}//end main
}//End hello1 class.
4.33
-end-
· 1 (p. 425) , 2 (p. 425) , 3 (p. 425) , 4 (p. 425) , 5 (p. 425) , 6 (p. 426) , 7 (p. 426) , 8 (p. 426) ,
9 (p. 426) , 10 (p. 426) , 11 (p. 426) , 12 (p. 429) , 13 (p. 426)
4.15.2 Preface
This module contains review questions and answers keyed to the module titled Jb0160: Java OOP: Hello
World
52 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.15.3 Questions
4.15.3.1 Question 1 .
True or false? Applications are designed to be downloaded and executed on-line under control of a web
browser, while applets are designed to be executed in a stand-alone mode from the command line.
Answer 1 (p. 431)
4.15.3.2 Question 2
True or false? All applications and applets written in Java require a main method.
Answer 2 (p. 430)
4.15.3.3 Question 3
Explain the relationship between the name of the class le for a Java application and the location of the
main method in the application.
Answer 3 (p. 430)
4.15.3.4 Question 4
Explain how you cause a method to be a class method in Java.
Answer 4 (p. 430)
4.15.3.5 Question 5
True or false? Class methods can be called without the requirement to instantiate an object of the class:
Answer 5 (p. 430)
4.15.3.6 Question 6
Write the source code for a Java application that will display your name and address on the standard output
device. Show the command-line statement that would be required to execute a compiled version of your
application.
Answer 6 (p. 430)
4.15.3.7 Question 7
Show the three styles of comment indicators that are supported by Java.
Answer 7 (p. 429)
4.15.3.8 Question 8
True or false? Java allows free-standing methods outside of a class denition?
Answer 8 (p. 429)
4.15.3.9 Question 9
What is the relationship between the name of the controlling class in an application and the names of the
les that comprise that application.
Answer 9 (p. 429)
4.15.3.10 Question 10
What is the relationship between the number of classes in an application and the number of separate les
with the class extension that go to make up that application? How does this change when all the classes
are dened in the same source le?
Answer 10 (p. 429)
4.15.3.11 Question 11
True or false? Class methods in Java can only be called relative to a specic object.
Answer 11 (p. 429)
4.15.3.12 Question 12
Write the signature line for the main method in a Java application.
Answer 12 (p. 429)
4.15.3.13 Question 13
Write a Java application that will display your name on the screen.
Answer 13 (p. 428)
4.15.4 Listings
• Listing 1 (p. 428) . Listing for Answer 13.
• Listing 2 (p. 429) . Listing for Answer 7.
• Listing 3 (p. 430) . Listing for Answer 6.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.15.5 Answers
4.15.5.1 Answer 13
4.34
4.15.5.2 Answer 12
note:
4.15.5.3 Answer 11
False. Class methods can be called by joining the name of the class with the name of the method using
a period.
Back to Question 11 (p. 426)
4.15.5.4 Answer 10
Each class denition results in a separate class le regardless of whether or not the classes are dened
in separate source les.
Back to Question 10 (p. 426)
4.15.5.5 Answer 9
One of the les must have the same name as the controlling class with an extension of class .
Back to Question 9 (p. 426)
4.15.5.6 Answer 8
False.
Back to Question 8 (p. 426)
4.15.5.7 Answer 7
4.35
4.15.5.8 Answer 6
/*File Name01.java
This is a Java application that will display a
name on the standard output device.
java Name01
**********************************************************/
4.36
Note that the \n characters in Listing 3 (p. 430) cause the output display to advance to the next line.
Back to Question 6 (p. 426)
4.15.5.9 Answer 5
True.
Back to Question 5 (p. 425)
4.15.5.10 Answer 4
Preface or precede the name of the method with the static keyword.
Back to Question 4 (p. 425)
4.15.5.11 Answer 3
The name of the class le must be the same as the name of the class that contains the main method
(sometimes called the controlling class) .
Back to Question 3 (p. 425)
4.15.5.12 Answer 2
False. Applets do not require a main method while applications do require a main method.
Back to Question 2 (p. 425)
4.15.5.13 Answer 1
False. Applications are for stand-alone use while applets are for browsers.
Back to Question 1 (p. 425)
4.15.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.16.2 Preface
This module is part of a sub-collection of modules designed to help you learn to program computers.
This module sheds a little more light on the Java construct called a class .
4.16.3 Listings
• Listing 1 (p. 432) . General syntax for dening a Java class.
4.16.4 Introduction
New types
Java makes extensive use of classes. When a class is dened in Java, a new type comes into being. The
new type denition can then be used to instantiate (create instances of) one or more objects of that new
type.
A blueprint
The class denition provides a blueprint that describes the data contained within, and the behavior
of objects instantiated according to the new type.
The data
The data is contained in variables dened within the class (often called member variables, data members,
attributes, elds, properties, etc. ).
The behavior
The behavior is controlled by methods dened within the class.
State and behavior
An object is said to have state and behavior . At any instant in time, the state of an object is
determined by the values stored in its variables and its behavior is determined by its methods .
Class vs. instance
It is possible to dene:
Instance variables and instance methods can only be accessed through an object instantiated from the class.
They belong to the individual objects, (which is why they are called instance variables and instance methods)
.
Class variables and class methods can be accessed without rst instantiating an object. They are
shared among all of the objects instantiated from the class and are even accessible in the total absence of an
object of the class.
The class name alone is sucient for accessing class variables and class methods by joining the name
of the class to the name of the variable or method using a period.
class MyClassName{
. . .
} //End of class definition.
4.37
This syntax denes a class and creates a new type named MyClassName .
The denitions of variables, methods, constructors, and a variety of other members are inserted between
the opening and closing curly brackets.
4.16.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 434) , 2 (p. 434) , 3 (p. 434) , 4 (p. 434) , 5 (p. 434) , 6 (p. 434) , 7 (p. 435) , 8 (p. 435)
4.17.2 Preface
This module contains review questions and answers keyed to the module titled Jb0170: Java OOP: A little
more information about classes
55 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.17.3 Questions
4.17.3.1 Question 1 .
List two of the many names commonly used for variables dened within a class in Java.
Answer 1 (p. 437)
4.17.3.2 Question 2
List two of the many names commonly used for the functions dened within a class in Java.
Answer 2 (p. 437)
4.17.3.3 Question 3
An object is said to have state and behavior . At any instant in time, the state of an object is determined
by the values stored in its (a)___________ and its behavior is determined by its (b)__________.
Answer 3 (p. 437)
4.17.3.4 Question 4
What keyword is used to cause a variable or method to become a class variable or class method in Java?
Answer 4 (p. 436)
4.17.3.5 Question 5
True or false? Instance variables and instance methods can only be accessed through an object of the
class in Java.
Answer 5 (p. 436)
4.17.3.6 Question 6
True or false? In Java, the class name alone is sucient for accessing class variables and class methods
by joining the name of the class with the name of the variable or method using a colon.
Answer 6 (p. 436)
4.17.3.7 Question 7
True or false? Show the general syntax of an empty class denition in Java.
Answer 7 (p. 436)
4.17.3.8 Question 8
True or false? The syntax for a class denition in Java requires a semicolon following the closing curly
bracket.
Answer 8 (p. 436)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.17.4 Answers
4.17.4.1 Answer 8
False. Java does not require the use of a semicolon following the closing curly bracket in a class denition.
Back to Question 8 (p. 435)
4.17.4.2 Answer 7
class NameOfClass{}
Back to Question 7 (p. 435)
4.17.4.3 Answer 6
False. A colon is not used in Java. Instead, a period is used in Java.
Back to Question 6 (p. 434)
4.17.4.4 Answer 5
True.
Back to Question 5 (p. 434)
4.17.4.5 Answer 4
static
Back to Question 4 (p. 434)
4.17.4.6 Answer 3
• (a) instance variables
• (b) methods
4.17.4.7 Answer 2
Member functions and instance methods.
Back to Question 2 (p. 434)
4.17.4.8 Answer 1
Instance variables and attributes.
Back to Question 1 (p. 434)
4.17.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.18.2 Preface
This module is part of a sub-collection of modules designed to help you learn to program computers.
Every Java application requires a class containing a method named main . This module provides
information on the main method.
4.18.2.1.1 Images
• Image 1 (p. ??) . The method signature according to Niemeyer and Peck.
• Image 2 (p. ??) . The method signature according to Oracle.
• Image 3 (p. 439) . Allowable signatures for the main method.
"A method signature is a collection of information about the method, as in a C prototype or a forward function declaratio
4.38
Type
Apparently in this denition, the authors are referring to the type of the method as distinguishing
between static and non-static. (Other literature refers to the type of a function or method as being the
return type which according to the above denition is a separate part of the signature.)
Visibility
Apparently also the use of the word visibility in the above denition refers to the use of public ,
private , etc.
According to Oracle...
Oracle's Java Tutorials
57 , on the other hand, describe the method signature as in Image 2 (p. ??) .
57 http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Denition: Two of the components of a method declaration comprise the method signaturethe method's name and the pa
4.39
As you can see, the Oracle denition is more restrictive than the Niemeyer and Peck denition.
Bottom line on method signature
The method signature can probably be thought of as providing information about the programming
interface to the method. In other words, it provides the information that you need to be able to call the
method in your program code.
Signature of main method
The controlling class of every Java application must contain a main method having one of the signatures
shown in Image 3 (p. 439) .
4.40
(I prefer the rst signature in Image 3 (p. 439) as being the most descriptive of an array of String
references which is what is passed in as an argument.)
public
The keyword public indicates that the method can be called by any object. A future module will
discuss the keywords public , private , and protected in more detail.
static
The keyword static indicates that the method is a class method, which can be called without the
requirement to instantiate an object of the class. This is used by the JVM to launch the program by calling
the main method of the class identied in the command to start the program.
void
The keyword void indicates that the method doesn't return any value.
args
The formal parameter args is a reference to an array object of type String . The array elements
contain references to String objects that encapsulate String representations of the arguments, if any,
entered at the command line.
Note that the args parameter must be specied whether or not the user is required to enter command-
line arguments and whether or not the code in the program actually makes use of the argument. Also note
that the name can be any legal Java identier. It doesn't have to be args . It could be joe or sue, for
example.
The length property
args is a reference to an array object.
The parameter named Java array objects have a property named
length , which species the number of elements in the array.
The runtime system monitors for the entry of command-line arguments by the user and constructs the
String array containing those arguments.
Processing command-line arguments
The args.length property can be used by the code in the program to determine the number of arguments
actually entered by the user.
If the length property is not equal to zero, the rst string in the array corresponds to the rst argument
entered on the command line.
Command-line arguments along with strings and String arrays will be discussed in more detail in a
future module.
4.18.4 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 441) , 2 (p. 441) , 3 (p. 441) , 4 (p. 441) , 5 (p. 441) , 6 (p. 441) , 7 (p. 442) , 8 (p. 442)
4.19.2 Preface
This module contains review questions and answers keyed to the module titled Jb0180: Java OOP: The main
method
59 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.19.3 Questions
4.19.3.1 Question 1 .
Write the method signature for the main method in a Java application.
Answer 1 (p. 444)
4.19.3.2 Question 2
Briey explain the reason that the main method in a Java application is declared public .
Answer 2 (p. 444)
4.19.3.3 Question 3
Explain the reason that the main method in a Java application must be declared static .
Answer 3 (p. 444)
4.19.3.4 Question 4
Describe the purpose of the keyword void when used as the return type for the main method.
Answer 4 (p. 444)
4.19.3.5 Question 5
True or false? If the Java application is not designed to use command-line arguments, it is not necessary to
include a formal parameter for the main method.
Answer 5 (p. 443)
4.19.3.6 Question 6
True or false? When using command-line arguments in Java, if the name of the string array is args ,
the args.length variable can be used by the code in the program to determine the number of arguments
actually entered.
Answer 6 (p. 443)
4.19.3.7 Question 7
True or false? The rst string in the array of command-line arguments contains the name of the Java
application
Answer 7 (p. 443)
4.19.3.8 Question 8
The controlling class of every Java application must contain a main method. Can other classes in the
same application also have a main method? If not, why not? If so, why might you want to do that?
Answer 8 (p. 443)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.19.4 Answers
4.19.4.1 Answer 8
Any and all classes in a Java application can have a main method. Only the one in the controlling class
for the program being executed is actually called.
It is often desirable to provide a main method for a class that will not ultimately be the controlling
class to allow the class to be tested in a stand-alone mode, independent of other classes.
Back to Question 8 (p. 442)
4.19.4.2 Answer 7
False. Unlike C++, the rst string in the array of command-line arguments in a Java application does not
contain the name of the application.
Back to Question 7 (p. 442)
4.19.4.3 Answer 6
True.
Back to Question 6 (p. 441)
4.19.4.4 Answer 5
False. The main method in a Java program must always provide the formal argument list regardless of
whether it is actually used in the program.
Back to Question 5 (p. 441)
4.19.4.5 Answer 4
The void keyword when used as the return type for any Java method indicates that the method does not
return anything.
Back to Question 4 (p. 441)
4.19.4.6 Answer 3
The keyword static indicates that the method is a class method which can be called without the
requirement to instantiate an object of the class. This is used by the Java virtual machine to launch the
program by calling the main method of the class identied in the command to start the program.
Back to Question 3 (p. 441)
4.19.4.7 Answer 2
The keyword public indicates that the method can be called by any object.
Back to Question 2 (p. 441)
4.19.4.8 Answer 1
note:
4.19.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.20 Jb0190: Java OOP: Using the System and PrintStream Classes 60
4.20.2 Preface
This module takes a preliminary look at the complexity of OOP by examining some aspects of the System
and PrintStream classes.
4.20.2.1.1 Listings
• Listing 1 (p. 446) . The program named hello1.
• Listing 2 (p. 447) . Display the string "Hello World".
4.20.3 Introduction
This lesson introduces you to the use of the System and PrintStream classes in Java. This is our rst
introduction to the complexity that can accompany the OOP paradigm. It gets a little complicated, so
you might need to pay special attention to the discussion.
4.20.4 Discussion
What does the main method do?
The main method in the controlling class of a Java application controls the ow of the program.
The main method can also access other classes along with the variables and methods of those classes
and of objects instantiated from those classes.
The hello1 Application
Listing 1 (p. 446) shows a simple Java application named hello1 .
(By convention, class denitions should begin with an upper-case character. However, the original
version of this module was written and published in 1997, before that convention was rmly established.)
60 This content is available online at <http://cnx.org/content/m45148/1.2/>.
4.41
note: System.out
accesses the class variable named out in the Java class named System .
System.out.println("Hello World");
4.42
This statement calls the println method of an object instantiated from the PrintStream class,
which is referred to (pointed to) by the variable named out , which is a class variable of the System
class.
Read the previous paragraph very carefully. As I indicated when I started this module, this is our rst
introduction to the complexity that can result from use of the OOP paradigm. (It can get even more
complicated.) If this is not clear to you, go back over it and think about it until it becomes clear.
As a side note, in addition to class variables, Java provides instance variables and instance methods .
Every instance of a class has its own set of instance variables. You can only access instance variables and
instance methods through an object of the class.
4.20.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 449) , 2 (p. 449) , 3 (p. 449) , 4 (p. 449) , 5 (p. 449) , 6 (p. 450) , 7 (p. 450) , 8 (p. 450) ,
9 (p. 450) , 10 (p. 450) , 11 (p. 450) , 12 (p. 453) , 13 (p. 450) , 14 (p. 450) , 15 (p. 451) , 16
(p. 451) , 17 (p. 451) , 18 (p. 451)
4.21.2 Preface
This module contains review questions and answers keyed to the module titled Jb0190: Java OOP: Using
the System and PrintStream Classes
62 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.21.3 Questions
4.21.3.1 Question 1 .
True or false? The main method in the controlling class of a Java application controls the ow of the
program.
Answer 1 (p. 455)
4.21.3.2 Question 2
True or false? The main method cannot access the variables and methods of objects instantiated from
other classes.
Answer 2 (p. 454)
4.21.3.3 Question 3
True or false? The main method must instantiate objects of other classes in order for the program to
execute.
Answer 3 (p. 454)
4.21.3.4 Question 4
True or false? In order to be useful, the System class must be used to instantiate objects in a Java
application.
Answer 4 (p. 454)
4.21.3.5 Question 5
True or false? Class variables such as the out variable of the System class must be of some specic
type.
Answer 5 (p. 454)
4.21.3.6 Question 6
True or false? Class variables must be of a primitive type such as int or oat .
Answer 6 (p. 454)
4.21.3.7 Question 7
True or false? The out variable in the System class is of a primitive type.
Answer 7 (p. 454)
4.21.3.8 Question 8
True or false? What does the following code fragment access?
note:
System.out
4.21.3.9 Question 9
True or false? An object of type PrintStream is automatically instantiated when the System class is
loaded into an application.
Answer 9 (p. 454)
4.21.3.10 Question 10
True or false? The out variable in the System class refers to an instance of what class?
Answer 10 (p. 454)
4.21.3.11 Question 11
True or false? The println method is an instance method of what class?
Answer 11 (p. 453)
4.21.3.12 Question 12
What is the primary behavior of the println method?
Answer 12 (p. 453)
4.21.3.13 Question 13
How can the println method be accessed?
Answer 13 (p. 453)
4.21.3.14 Question 14
Assuming that the standard output device has not been redirected, write a code fragment that will cause
your name to be displayed on the screen.
Answer 14 (p. 453)
4.21.3.15 Question 15
Explain how your code fragment in Answer 14 (p. 453) produces the desired result.
Answer 15 (p. 453)
4.21.3.16 Question 16
If you have a class named MyClass that has a class variable named myClassVariable that requires
four bytes of memory and you instantiate ten objects of type MyClass , how much total memory will
be allocated to contain the allocated variables (assume that the class denition contains no other class,
instance, or local variables) .
Answer 16 (p. 453)
4.21.3.17 Question 17
How many actual instances of the variable named out are allocated in memory by the following code
fragment?
note:
System.out.println("Dick Baldwin");
4.21.3.18 Question 18
If you have a class named MyClass that has an instance variable named myInstanceVariable that
requires four bytes of memory and you instantiate ten objects of type MyClass , how much total memory
will be allocated to contain the allocated variables (assume that the class denition contains no other class,
instance, or local variables) .
Answer 18 (p. 453)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.21.4 Answers
4.21.4.1 Answer 18
Every instance of a class has its own set of instance variables. You can only access instance variables and
instance methods through an object of the class. In this case, forty bytes of memory would be required to
contain the instance variables of the ten objects.
Back to Question 18 (p. 451)
4.21.4.2 Answer 17
Only one, because out is a class variable of the System class.
Back to Question 17 (p. 451)
4.21.4.3 Answer 16
The runtime system allocates a class variable only once no matter how many instances of the class are
instantiated. Thus, all objects of the class share the same physical memory space for the class variable, and
in this case, only four bytes of memory will be allocated to contain the allocated variables.
Back to Question 16 (p. 451)
4.21.4.4 Answer 15
The statement in Answer 14 (p. 453) calls the println method belonging to an object of the PrintStream
class, which is referenced (pointed to) by the out variable, which is a class variable of the System
class.
Back to Question 15 (p. 451)
4.21.4.5 Answer 14
note:
System.out.println("Dick Baldwin");
4.21.4.6 Answer 13
The println method can be accessed by joining the name of a variable that references a PrintStream
object to the name of the println method using a period.
Back to Question 13 (p. 450)
4.21.4.7 Answer 12
The println method causes its argument to be displayed on the standard output device. (The standard
output device is the screen by default, but can be redirected by the user at the operating system level.)
Back to Question 12 (p. 450)
4.21.4.8 Answer 11
The println method is an instance method of the PrintStream class.
Back to Question 11 (p. 450)
4.21.4.9 Answer 10
The out variable in the System class refers to an instance of the PrintStream class (a PrintStream
object), which is automatically instantiated when the System class is loaded into the application.
Back to Question 10 (p. 450)
4.21.4.10 Answer 9
True.
Back to Question 9 (p. 450)
4.21.4.11 Answer 8
The code fragment accesses the contents of the class variable named out in the class named System .
Back to Question 8 (p. 450)
4.21.4.12 Answer 7
False. the variable named out dened in the System class is a reference variable that points to an object
of another type.
Back to Question 7 (p. 450)
4.21.4.13 Answer 6
False. A class variable can be a primitive type, or it can be a reference variable that points to another
object.
Back to Question 6 (p. 450)
4.21.4.14 Answer 5
True.
Back to Question 5 (p. 449)
4.21.4.15 Answer 4
False. The System class has several class variables (including out and in ) that are useful
without the requirement to instantiate an object of the System class.
Back to Question 4 (p. 449)
4.21.4.16 Answer 3
False. While it is probably true that the main method must instantiate objects of other classes in order
to accomplish much that is of value, this is not a requirement. The main method in the "Hello World"
program of this module
63 does not instantiate objects of any class at all.
Back to Question 3 (p. 449)
4.21.4.17 Answer 2
False. The main method can access the variables and methods of objects instantiated from other classes.
Otherwise, the ow of the program would be stuck within the main method itself and wouldn't be very
useful.
Back to Question 2 (p. 449)
63 http://cnx.org/content/m45148/latest/
4.21.4.18 Answer 1
True.
Back to Question 1 (p. 449)
4.21.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.22.2 Preface
Earlier modules have touched briey on the topic of variables. This module discusses Java variables in depth.
4.22.2.1.1 Images
• Image 1 (p. 459) . Screen output from the program named simple1.
• Image 2 (p. 462) . Information about the primitive types in Java.
• Image 3 (p. 466) . Rules for naming variables.
• Image 4 (p. 466) . Rules for legal identiers.
• Image 5 (p. 467) . Scope categories.
4.22.2.1.2 Listings
• Listing 1 (p. 458) . Source code for the program named simple1.
• Listing 2 (p. 459) . Declaring and initializing two variables named ch1 and ch2.
• Listing 3 (p. 460) . Display the character.
• Listing 4 (p. 461) . Beginning of a while loop.
• Listing 5 (p. 461) . Beginning of the main method.
• Listing 6 (p. 464) . The program named wrapper1.
• Listing 7 (p. 465) . Aspects of using a wrapper class.
• Listing 8 (p. 468) . The program named member1.
• Listing 9 (p. 469) . Initialization of variables.
4.22.3 Introduction
The rst step
The rst step in learning to use a new programming language is usually to learn the foundation concepts
such as
• variables
• types
• expressions
• ow-of-control, etc.
(This program contains a lot of code that you are not yet prepared to understand. For the time being,
just concentrate on the use of variables in the program. You will learn about the other aspects of the program
in future modules.)
The program loops, saving individual characters until encountering the # character. When it encounters
the # character, it terminates and displays the character entered immediately prior to the # character.
System.out.println(
"Enter some text, terminate with #");
4.43
Program output
The output produced by compiling and running this program is shown in Image 1 (p. 459) . The second
line of text in Image 1 (p. 459) ending with the # character was typed by the user.
4.44
4.22.5 Variables
note: What is a variable? Variables are used in a Java program to contain data that changes
during the execution of the program.
Declaring a variable
To use a variable, you must rst notify the compiler of the name and the type of the variable. This
is known as declaring a variable .
The syntax for declaring a variable is to precede the name of the variable with the name of the type
of the variable as shown in Listing 2 (p. 459) . It is also possible (but not required) to initialize a variable
in Java when it is declared as shown in Listing 2 (p. 459) .
Listing 2: Declaring and initializing two variables named ch1 and ch2.
4.45
The statement in Listing 2 (p. 459) declares two variables of type int , initializing the second variable
(ch2) to the value of the zero character (0). (Note that I didn't say initialized to the value zero.)
note: Dierence between zero and '0' - Unicode characters The value of the zero
character is not the same as the numeric value of zero, but hopefully you already knew that.
As an aside, characters in Java are 16-bit entities called Unicode characters instead of 8-bit entities
as is the case with many programming languages. The purpose is to provide many more possible
characters including characters used in alphabets other than the one used in the United States.
4.46
note: Initialization of instance variables and local variables: As another aside, member
variables in Java are automatically initialized to zero or the equivalent of zero. However, local
variables , of which ch2 is an example, are not automatically initialized.
4.47
Java provides very strict type checking and generally refuses to compile statements with type mismatches.
(There is a lot of complicated code in Listing 4 (p. 461) that I haven't previously explained. I will
explain that code later in this and future modules.)
Another variable declaration
The program in Listing 1 (p. 458) also makes another variable declaration shown by the statement in
Listing 5 (p. 461) .
4.48
For example, the int type can only contain whole numbers (integers) . A whole host of operations are
possible with an int variable including add, subtract, divide, etc.
Signed vs. unsigned variables
Unlike C++, all variables of type int in Java contain signed values. In fact, with the exception of type
char , all primitive numeric types in Java contain signed values.
Platform independence
At this point in the history of Java, a variable of a specied type is represented exactly the same way
regardless of the platform on which the application or applet is being executed.
This is one of the features that causes compiled Java programs to be platform-independent.
• primitive types
• reference (or object) types.
Primitive variables contain a single value of one of the eight primitive types shown in Listing 2 (p. 459) .
Reference variables contain references to objects (or null, meaning that they don't refer to anything) .
The eight primitive types in Java?
The table in Image 2 (p. 462) lists all of the primitive types in Java along with their size and format,
and a brief description of each.
4.49
Later on in this course of study, you will learn that much of the power of Java derives from the ability
to deal with objects of any type as the generic type Object . For example, several of the standard classes
in the API (such as the powerful Vector class) are designed to work only with objects of type Object .
(Note that this document was originally published prior to the introduction of generics in Java. The
introduction of generics makes it possible to cause the Vector class to deal with objects of types other
than Object . However, that doesn't eliminate the need for wrapper classes.)
Converting primitives to objects
Because it is sometimes necessary to deal with a primitive value as though it were an object, Java provides
wrapper classes that support object-oriented functionality for Java's primitive data types.
The Double wrapper class
This is illustrated in the program shown in Listing 6 (p. 464) that deals with a double type as an
object of the class Double .
(Remember, Java is a case-sensitive language. Note the dierence between the primitive double type
and the class named Double .)
**********************************************************/
class wrapper1 { //define the controlling class
public static void main(String[] args){//define main
4.50
The operation of this program is explained in the comments, and the output from the program is shown
in the comments at the beginning.
note: The above statement may not really be true? However, we can think of it that
way. Depending on the particular JVM in use, the reference variable may refer to a table in memory
where the address of the object is stored. In that case the second level of indirection is handled
behind the scenes and we don't have to worry about it.
Why would a JVM elect to implement another level of indirection? Wouldn't that make programs
run more slowly?
One reason has to do with the need to compact memory when it becomes highly fragmented. If the
reference variables all refer directly to memory locations containing the objects, there may be many
reference variables that refer to the same object. If that object is moved for compaction purposes,
then the values stored in every one of those reference variables would have to be modied.
However, if those reference variables all refer to a table that has one entry that species where the
object is stored, then when the object is moved, only the value of that one entry in the table must
be modied.
Fortunately, that all takes place behind the scenes and we as programmers don't need to worry
about it.
• declares,
• instantiates,
• initializes, and
• manipulates a variable of a reference type named myWrappedData .
In Listing 7 (p. 465) , the variable named myWrappedData contains a reference to an object of type
Double .
4.51
• Must be a legal Java identier (see below) consisting of a series of Unicode characters. Unicode
characters are stored in sixteen bits, allowing for a very large number of dierent characters. A
subset of the possible character values matches the 127 possible characters in the ASCII character
set, and the extended 8-bit character set, ISO-Latin-1 (The Java Handbook, page 60, by Patrick
Naughton).
• Must not be the same as a Java keyword and must not be true or false.
• Must not be the same as another variable whose declaration appears in the same scope.
4.52
The rules for legal identiers are shown in Image 4 (p. 466) .
• In Java, a legal identier is a sequence of Unicode letters and digits of unlimited length.
• The rst character must be a letter.
• All subsequent characters must be letters or numerals from any alphabet that Unicode supports.
• In addition, the underscore character (_) and the dollar sign ($) are considered letters and may be
used as any character including the rst one.
4.53
4.22.6 Scope
What is the scope of a Java variable?
The scope of a Java variable is dened by the block of code within which the variable is accessible.
(Briey, a block of code consists of none, one, or more statements enclosed by a pair of matching curly
brackets.)
The scope also determines when the variable is created (memory set aside to contain the data stored in
the variable) and when it possibly becomes a candidate for destruction (memory returned to the operating
system for recycling and re-use) .
Scope categories
The scope of a variable places it in one of the four categories shown in Image 5 (p. 467) .
• member variable
• local variable
• method parameter
• exception handler parameter
4.54
Member variable
A member variable is a member of a class (class variable) or a member of an object instantiated from
that class (instance variable) . It must be declared within a class, but not within the body of a method or
constructor of the class.
Local variable
A local variable is a variable declared within the body of a method or constructor or within a block of
code contained within the body of a method or constructor.
Method parameters
Method parameters are the formal arguments of a method. Method parameters are used to pass values
into and out of methods. The scope of a method parameter is the entire method for which it is a parameter.
Exception handler parameters
Exception handler parameters are arguments to exception handlers. Exception handlers will be discussed
in a future module.
Illustrating dierent types of variables in Java
The Java program shown in Listing 8 (p. 468) illustrates
An illustration of exception handler parameters will be deferred until exception handlers are discussed in a
future module.
Class variable is 5
Instance variable is 6
Method parameter is 7
Local variable is 8
**********************************************************/
class member1 { //define the controlling class
//declare and initialize class variable
static int classVariable = 5;
//declare and initialize instance variable
int instanceVariable = 6;
}//end main
4.55
note: Special case, scope within a for loop Java treats the scope of a variable declared
for statement
within the initialization clause of a to be limited to the total extent of the for
statement.
A future module will explain what is meant by a for statement or a for loop.
4.56
4.22.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 471) , 2 (p. 471) , 3 (p. 471) , 4 (p. 471) , 5 (p. 471) , 6 (p. 472) , 7 (p. 472) , 8 (p. 472) ,
9 (p. 472) , 10 (p. 472) , 11 (p. 472) , 12 (p. 481) , 13 (p. 472) , 14 (p. 472) , 15 (p. 472) , 16
(p. 473) , 17 (p. 473) , 18 (p. 473) , 19 (p. 473) , 20 (p. 473) , 21 (p. 473) , 22 (p. 473) , 23 (p.
473) , 24 (p. 473) , 25 (p. 473) , 26 (p. 474) , 27 (p. 474) , 28 (p. 474) , 29 (p. 474) , 30 (p. 474)
, 31 (p. 474) , 32 (p. 474) , 33 (p. 474) , 34 (p. 474) , 35 (p. 474) , 36 (p. 475) , 37 (p. 475) , 38
(p. 475) , 39 (p. 475)
4.23.2 Preface
This module contains review questions and answers keyed to the module titled Jb0200: Java OOP: Variables
66 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.23.3 Questions
4.23.3.1 Question 1 .
Write a Java application that reads characters from the keyboard until encountering the # character. Echo
each character to the screen as it is read. Terminate the program when the user enters the # character.
Answer 1 (p. 483)
4.23.3.2 Question 2
What is the common name for the Java program element that is used to contain data that changes during
the execution of the program?
Answer 2 (p. 482)
4.23.3.3 Question 3
What must you do to make a variable available for use in a Java program?
Answer 3 (p. 482)
4.23.3.4 Question 4
True or false? In Java, you are required to initialize the value of all variables when they are declared.
Answer 4 (p. 482)
4.23.3.5 Question 5
Show the proper syntax for declaring two variables and initializing one of them using a single Java statement.
Answer 5 (p. 482)
4.23.3.6 Question 6
True or false? The Java compiler will accept statements with type mismatches provided that a suitable type
conversion can be implemented by the compiler at compile time.
Answer 6 (p. 481)
4.23.3.7 Question 7
Show the proper syntax for the declaration of a variable of type String[] in the argument list of the main
method of a Java program and explain its purpose.
Answer 7 (p. 481)
4.23.3.8 Question 8
Describe the purpose of the type denition in Java.
Answer 8 (p. 481)
4.23.3.9 Question 9
True or false? Variables of type int can contain either signed or unsigned values.
Answer 9 (p. 481)
4.23.3.10 Question 10
What is the important characteristic of type denitions in Java that strongly supports the concept of
platform independence of compiled Java programs?
Answer 10 (p. 481)
4.23.3.11 Question 11
What are the two major categories of types in Java?
Answer 11 (p. 481)
4.23.3.12 Question 12
What is the maximum number of values that can be stored in a variable of a primitive type in Java?
Answer 12 (p. 481)
4.23.3.13 Question 13
List the primitive types in Java.
Answer 13 (p. 481)
4.23.3.14 Question 14
True or false? Java stores variables of type char according to the 8-bit extended ASCII table.
Answer 14 (p. 480)
4.23.3.15 Question 15
True or false? In Java, the name of a primitive variable evaluates to the value stored in the variable.
Answer 15 (p. 480)
4.23.3.16 Question 16
True or false? Variables of primitive data types in Java are true objects.
Answer 16 (p. 480)
4.23.3.17 Question 17
Why do we care that variables of primitive types are not true objects?
Answer 17 (p. 480)
4.23.3.18 Question 18
What is the name of the mechanism commonly used to convert variables of primitive types to true objects?
Answer 18 (p. 480)
4.23.3.19 Question 19
How can you tell the dierence between a primitive type and a wrapper for the primitive type when the
two are spelled the same?
Answer 19 (p. 480)
4.23.3.20 Question 20
Show the proper syntax for declaring a variable of type double and initializing its value to 5.5.
Answer 20 (p. 480)
4.23.3.21 Question 21
Show the proper syntax for declaring a variable of type Double and initializing its value to 5.5.
Answer 21 (p. 479)
4.23.3.22 Question 22
Show the proper syntax for extracting the value from a variable of type Double .
Answer 22 (p. 479)
4.23.3.23 Question 23
True or false? In Java, the name of a reference variable evaluates to the address of the location in memory
where the variable is stored.
Answer 23 (p. 479)
4.23.3.24 Question 24
What is a legal identier in Java?
Answer 24 (p. 479)
4.23.3.25 Question 25
What are the rules for variable names in Java?
Answer 25 (p. 478)
4.23.3.26 Question 26
What is meant by the scope of a Java variable?
Answer 26 (p. 478)
4.23.3.27 Question 27
What are the four possible scope categories for a Java variable?
Answer 27 (p. 478)
4.23.3.28 Question 28
What is a member variable?
Answer 28 (p. 478)
4.23.3.29 Question 29
Where are local variables declared in Java?
Answer 29 (p. 478)
4.23.3.30 Question 30
What is the scope of a local variable in Java?
Answer 30 (p. 478)
4.23.3.31 Question 31
What denes a block of code in Java?
Answer 31 (p. 478)
4.23.3.32 Question 32
What is the scope of a variable that is declared within a block of code that is dened within a method and
which is a subset of the statements that make up the method?
Answer 32 (p. 477)
4.23.3.33 Question 33
What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide
an example code fragment.
Answer 33 (p. 477)
4.23.3.34 Question 34
What are method parameters and what are they used for?
Answer 34 (p. 477)
4.23.3.35 Question 35
What is the scope of a method parameter ?
Answer 35 (p. 477)
4.23.3.36 Question 36
What are exception handler parameters ?
Answer 36 (p. 477)
4.23.3.37 Question 37
Write a Java application that illustrates member variables (class and instance) , local variables, and method
parameters.
Answer 37 (p. 477)
4.23.3.38 Question 38
True or false? Member variables in a Java class can be initialized when the class is dened.
Answer 38 (p. 477)
4.23.3.39 Question 39
How are method parameters initialized in Java?
Answer 39 (p. 477)
4.23.4 Listings
• Listing 1 (p. 479) . Listing for Answer 22.
• Listing 2 (p. 483) . Listing for Answer 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.23.5 Answers
4.23.5.1 Answer 39
Method parameters are initialized by the values passed to the method.
Back to Question 39 (p. 475)
4.23.5.2 Answer 38
True.
Back to Question 38 (p. 475)
4.23.5.3 Answer 37
See the application named member1 in this module
67 for an example of such an application.
Back to Question 37 (p. 475)
4.23.5.4 Answer 36
Exception handler parameters are arguments to exception handlers, which will be discussed in a future
module.
Back to Question 36 (p. 475)
4.23.5.5 Answer 35
The scope of a method parameter is the entire method for which it is a parameter.
Back to Question 35 (p. 474)
4.23.5.6 Answer 34
Method parameters are the formal arguments of a method. Method parameters are used to pass values
into and out of methods.
Back to Question 34 (p. 474)
4.23.5.7 Answer 33
Java treats the scope of a variable declared within the initialization clause of a for statement to be limited
to the total extent of the for statement. A sample code fragment follows where cnt is the variable being
discussed:
note:
4.23.5.8 Answer 32
In Java, the scope can be reduced by placing it within a block of code within the method. The scope
extends from the point at which it is declared to the end of the block of code in which it is declared.
Back to Question 32 (p. 474)
67 http://cnx.org/content/m45150/latest/#Listing_8
4.23.5.9 Answer 31
A block of code is dened by enclosing it within curly brackets as shown below
{ ... } .
Back to Question 31 (p. 474)
4.23.5.10 Answer 30
The scope of a local variable extends from the point at which it is declared to the end of the block of code
in which it is declared.
Back to Question 30 (p. 474)
4.23.5.11 Answer 29
In Java, local variables are declared within the body of a method or constructor, or within a block of code
contained within the body of a method or constructor.
Back to Question 29 (p. 474)
4.23.5.12 Answer 28
A member variable is a member of a class ( class variable) or a member of an object instantiated from
instance
that class ( variable). It must be declared within a class, but not within the body of a method or
constructor of the class.
Back to Question 28 (p. 474)
4.23.5.13 Answer 27
The scope of a variable places it in one of the following four categories:
• member variable
• local variable
• method parameter
• exception handler parameter
4.23.5.14 Answer 26
The scope of a Java variable is the block of code within which the variable is accessible.
Back to Question 26 (p. 474)
4.23.5.15 Answer 25
The rules for Java variable names are as follows:
4.23.5.16 Answer 24
In Java, a legal identier is a sequence of Unicode letters and digits of unlimited length. The rst character
must be a letter. All subsequent characters must be letters or numerals from any alphabet that Unicode
supports. In addition, the underscore character ( _ ) and the dollar sign ( $ ) are considered letters and
may be used as any character including the rst one.
Back to Question 24 (p. 473)
4.23.5.17 Answer 23
False. The name of a reference variable evaluates to either null, or to information that can be used to access
an object whose reference has been stored in the variable.
Back to Question 23 (p. 473)
4.23.5.18 Answer 22
Later versions of Java support either syntax shown in Listing 1 (p. 479) .
class test{
public static void main(String[] args){
Double var1 = 5.5;
double var2 = var1.doubleValue();
System.out.println(var2);
4.57
4.23.5.19 Answer 21
The proper syntax for early versions of Java is shown below. Note the upper-case D . Also note the
instantiation of a new object of type Double .
note:
Later versions of Java support the following syntax with the new object of type Double being instantiated
automatically:
note:
4.23.5.20 Answer 20
The proper syntax is shown below. Note the lower-case d .
note:
4.23.5.21 Answer 19
The name of the primitive type begins with a lower-case letter and the name of the wrapper type begins
with an upper-case letter such as double and Double . Note that in some cases, however, that they are
not spelled the same. For example, the Integer class is the wrapper for type int .
Back to Question 19 (p. 473)
4.23.5.22 Answer 18
Wrapper classes
Back to Question 18 (p. 473)
4.23.5.23 Answer 17
This has some ramications as to how variables can be used (passing to methods, returning from methods,
etc.) . For example, all variables of primitive types are passed by value to methods meaning that the code
in the method only has access to a copy of the variable and does not have the ability to modify the variable.
Back to Question 17 (p. 473)
4.23.5.24 Answer 16
False. Primitive data types in Java (int, double, etc.) are not true objects.
Back to Question 16 (p. 473)
4.23.5.25 Answer 15
True.
Back to Question 15 (p. 472)
4.23.5.26 Answer 14
False. The char type in Java is a 16-bit Unicode character.
Back to Question 14 (p. 472)
4.23.5.27 Answer 13
• byte
• short
• int
• long
• oat
• double
• char
• boolean
4.23.5.28 Answer 12
Primitive types contain a single value.
Back to Question 12 (p. 472)
4.23.5.29 Answer 11
Java supports both primitive types and reference (or object) types.
Back to Question 11 (p. 472)
4.23.5.30 Answer 10
In Java, a variable of a specied type is represented exactly the same way regardless of the platform on
which the application or applet is being executed.
Back to Question 10 (p. 472)
4.23.5.31 Answer 9
False. In Java, all variables of type int contain signed values.
Back to Question 9 (p. 472)
4.23.5.32 Answer 8
All variables in Java must have a dened type . The denition of the type determines the set of values
that can be stored in the variable and the operations that can be performed on the variable.
Back to Question 8 (p. 472)
4.23.5.33 Answer 7
The syntax is shown in boldface below:
In this case, the type of variable declared is an array of type String named args (type String[]) .
The purpose of the String array variable in the argument list is to make it possible to capture arguments
entered on the command line.
Back to Question 7 (p. 472)
4.23.5.34 Answer 6
False. Fortunately, Java provides very strict type checking and generally refuses to compile statements with
type mismatches.
Back to Question 6 (p. 472)
4.23.5.35 Answer 5
note:
4.23.5.36 Answer 4
False: In Java, it is possible to initialize the value of a variable when it is declared, but initialization is not
required. (Note however that in some situations, the usage of the variable may require that it be purposely
initialized.) .
Back to Question 4 (p. 471)
4.23.5.37 Answer 3
To use a variable, you must notify the compiler of the name and the type of the variable (declare the
variable).
Back to Question 3 (p. 471)
4.23.5.38 Answer 2
variable
Back to Question 2 (p. 471)
4.23.5.39 Answer 1
/*File simple4.java
This application reads characters from the keyboard until
encountering the # character and echoes each character to
the screen. The program terminates when the user enters
the # character.
**********************************************************/
class simple4 { //define the controlling class
public static void main(String[] args)
throws java.io.IOException {
int ch1 = 0;
System.out.println(
"Enter some text, terminate with #");
while( (ch1 = System.in.read() ) != '#')
System.out.print((char)ch1);
System.out.println("Goodbye");
}//end main
}//End simple4 class.
4.58
4.23.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.24.2 Preface
Earlier modules have touched briey on the topic of operators . This module discusses Java operators
in depth.
4.24.2.1.1 Listings
• Listing 1 (p. 487) . Illustration of prex and postx notation.
• Listing 2 (p. 490) . Illustration of relational operators.
4.24.3 Introduction
The rst step in learning to use a new programming language is usually to learn the foundation concepts
such as
• variables,
• operators,
• types,
• expressions,
• ow-of-control, etc.
4.24.4 Operators
Unary and binary operators
Java provides a set of operators that can be used to perform an action on one, two, or three (p. 485)
operands. An operator that operates on one operand is called a unary operator. An operator that operates
on two operands is called a binary operator. An operator that operates on three operands is called a
ternary operator.
Some operators can behave either as a unary or as a binary operator. The best known such operator s
probably the minus sign (-) . As a binary operator, the minus sign causes its right operand to be subtracted
from its left operand. As a unary operator, the minus sign causes the algebraic sign of the right operand to
be changed.
A ternary operator
Java has only one operator that takes three operands. It is a conditional operator, which I sometimes
refer to as a cheap if statement.
The rst operand is a boolean expression, which is followed by a question mark character (?) . The
question mark is followed by a second operand, which is followed by a colon character (:) . The colon
character is followed by the third operand.
If the boolean expression evaluates to true, the value of the operand following the ? is returned.
Otherwise, the value of the operand following the : is returned.
An example of the syntax follows:
Overloaded operators
Unlike C++, Java does not support the creation of overloaded operators in program code. (If you don't
know what this means, don't worry about it.)
Operators from previous programs
The statements in the following note box illustrate the use of the following operators from Java programs
in earlier modules :
• =
• !=
• +
• (char)
note: The decrement operator There is also a decrement operator () that causes the
value of its operand to be decreased by one.
The increment and decrement operators are used in both prex and postx notation.
Prex and postx increment and decrement operators
With the prex version, the operand appears to the right of the operator ( ++X) , while with the
postx version, the operand appears to the left of the operator (X++) .
What's the dierence in prex and postx?
The dierence in prex and postx has to do with the point in the sequence of operations that the
increment (or decrement) actually occurs if the operator and its operand appear as part of a larger overall
expression.
(There is eectively no dierence if the operator and its operand do not appear as part of a larger overall
expression.)
Prex behavior
With the prex version, the variable is incremented (or decremented) before it is used to evaluate the
larger overall expression.
Postx behavior
With the postx version, the variable is used to evaluate the larger overall expression before it is
incremented (or decremented) .
Illustration of prex and postx behavior
The use of both the prex and postx versions of the increment operator is illustrated in the Java
program shown in Listing 1 (p. 487) . The output produced by the program is show in the comments at the
beginning of the program.
a = 5
b = 5
a + b++ = 10
b = 6
c = 5
d = 5
c + ++d = 11
d = 6
*********************************************************/
class incr01 { //define the controlling class
public static void main(String[] args){ //main method
int a = 5, b = 5, c = 5, d = 5;
System.out.println("a = " + a );
System.out.println("b = " + b );
System.out.println("a + b++ = " + (a + b++) );
System.out.println("b = " + b );
System.out.println();
System.out.println("c = " + c );
System.out.println("d = " + d );
System.out.println("c + ++d = " + (c + ++d) );
System.out.println("d = " + d );
}//end main
}//End incr01 class.
4.59
note: Evaluating to a value To evaluate to a value means that after the action is performed,
the operator and its operands are eectively replaced in the expression by the value that is returned.
Operator categories
I will divide Java's operators into the following categories for further discussion:
• arithmetic operators
• relational and conditional (logical) operators
• bitwise operators
• assignment operators
Operator Description
Operator Description
Conditional expressions
Relational operators are frequently used in the conditional expressions of control statement such as the
one in the code fragment shown below.
Output is
*********************************************************/
class relat01 { //define the controlling class
public static void main(String[] args){ //main method
System.out.println("The relational 6<5 is "
+(6<5));
System.out.println("The relational 6>5 is "
+(6>5));
}//end main
}//End relat01 class.
4.60
Conditional operators
The relational operators are often combined with another set of operators (referred to as conditional or
logical operators) to construct more complex expressions.
Java supports three such operators as shown in the following table.
The operands shown in the table (p. 490) must be boolean types, or must have been created by the
evaluation of an expression that returns a boolean type.
Left to right evaluation
An important characteristic of the behavior of the logical and and the logical or operators is that
the expressions are evaluated from left to right, and the evaluation of the expression is terminated as soon
as the result of evaluating the expression can be determined.
For example, in the following expression, if the variable a is less than the variable b , there is no
need to evaluate the right operand of the || to determine that the result of evaluating the entire expression
would be true . Therefore, evaluation will terminate as soon as the answer can be determined.
(a < b) || (c < d)
One author states that in Java, the bitwise and operator can be used as a synonym for the logical and
and the bitwise or can be used as a synonym for the logical inclusive or if both of the operands are
boolean . (I recommend that you don't do that because it could cause confusion for someone reading
your code.)
Note however that according to a dierent author, in this case, the evaluation of the expression is not
terminated until all operands have been evaluated, thus eliminating the possible advantage of the left-to-right
evaluation.
Another way to state this is if the bits are dierent, the result is a 1. If the two bits are the same, the
result is a 0.
The complement operator
Finally, the complement operator changes each 1 to a 0 and changes each 0 to a 1.
+=
-=
*=
/=
%=
&=
|=
^=
=
=
>=
For example, the two statements that follow perform the same operation.
x += y;
x = x + y;
4.24.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 494) , 2 (p. 494) , 3 (p. 494) , 4 (p. 494) , 5 (p. 494) , 6 (p. 495) , 7 (p. 495) , 8 (p. 495) ,
9 (p. 495) , 10 (p. 495) , 11 (p. 495) , 12 (p. 509) , 13 (p. 495) , 14 (p. 496) , 15 (p. 496) , 16
(p. 496) , 17 (p. 496) , 18 (p. 497) , 19 (p. 497) , 20 (p. 497) , 21 (p. 497) , 22 (p. 497) , 23 (p.
497) , 24 (p. 498) , 25 (p. 498) , 26 (p. 498) , 27 (p. 498) , 28 (p. 498) , 29 (p. 498) , 30 (p. 498)
, 31 (p. 498) , 32 (p. 499) , 33 (p. 499) , 34 (p. 499) , 35 (p. 499) , 36 (p. 499) , 37 (p. 499) , 38
(p. 499)
4.25.2 Preface
This module contains review questions and answers keyed to the module titled Jb0210: Java OOP: Operators
70 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.25.3 Questions
4.25.3.1 Question 1 .
An operator performs an action on what? Provide the name.
Answer 1 (p. 510)
4.25.3.2 Question 2
What do we call an operator that operates on only one operand?
Answer 2 (p. 510)
4.25.3.3 Question 3
What do we call an operator that operates on two operands?
Answer 3 (p. 510)
4.25.3.4 Question 4
Is the minus sign a unary or a binary operator, or both? Explain your answer.
Answer 4 (p. 510)
4.25.3.5 Question 5
Describe operator overloading.
Answer 5 (p. 510)
4.25.3.6 Question 6
True or false? Java programmers may overload operators.
Answer 6 (p. 510)
4.25.3.7 Question 7
Show the symbols used for the following operators in Java: assignment , not equal , addition , cast .
Answer 7 (p. 510)
4.25.3.8 Question 8
Are any operators automatically overloaded in Java? If so, identify one and describe its overloaded behavior.
Answer 8 (p. 510)
4.25.3.9 Question 9
What is the purpose of the cast operator?
Answer 9 (p. 509)
4.25.3.10 Question 10
True or false? The increment operator is a binary operator.
Answer 10 (p. 509)
4.25.3.11 Question 11
Show the symbol for the increment operator.
Answer 11 (p. 509)
4.25.3.12 Question 12
Describe the appearance and the behavior of the increment operator with both prex and postx notation.
Show example, possibly incomplete, code fragments illustrating both notational forms.
Answer 12 (p. 509)
4.25.3.13 Question 13
Show the output that would be produced by the Java application in Listing 1 (p. 496) .
4.61
4.25.3.14 Question 14
True or false? Binary operators use outx notation. If your answer is False, explain why.
Answer 14 (p. 509)
4.25.3.15 Question 15
In practice, what does it mean to say that an operator that has performed an action returns a value (or
evaluates to a value) of a given type?
Answer 15 (p. 509)
4.25.3.16 Question 16
Show and describe at least ve of the binary arithmetic operators supported by Java (Clarication: binary
operators does not mean bitwise operators).
Answer 16 (p. 508)
4.25.3.17 Question 17
In addition to arithmetic addition, what is another use for the plus operator (+) ? Show an example code
fragment to illustrate your answer. The code fragment need not be a complete statement.
Answer 17 (p. 508)
4.25.3.18 Question 18
When the plus operator (+) is used as a concatenation operator, what is the nature of its behavior if its
left operand is of type String and its right operand is not of type String ? If the right operand is a
variable that is not of type String , what is the impact of this behavior on that variable.
Answer 18 (p. 508)
4.25.3.19 Question 19
Show and describe four unary arithmetic operators supported by Java.
Answer 19 (p. 508)
4.25.3.20 Question 20
What is the type returned by relational operators in Java?
Answer 20 (p. 507)
4.25.3.21 Question 21
Show and describe six dierent relational operators supported by Java.
Answer 21 (p. 507)
4.25.3.22 Question 22
Show the output that would be produced by the Java application shown in Listing 2 (p. 497) .
4.62
4.25.3.23 Question 23
Show and describe three operators (frequently referred to as conditional or logical operators) that are
often combined with relational operators to construct more complex expressions (often called conditional
expressions) . Hint: The || operator returns true if either the left operand, the right operand, or both
operands are true. What are the other two and how do they behave?
Answer 23 (p. 507)
4.25.3.24 Question 24
Describe the special behavior of the || operator in the following expression for the case where the value of
the variable a is less than the value of the variable b .
note:
(a < b) || (c < d)
4.25.3.25 Question 25
Show the symbols used for the bitwise and operator and the bitwise inclusive or operator.
Answer 25 (p. 506)
4.25.3.26 Question 26
Show and describe seven operators in Java that perform actions on the operands one bit at a time (bitwise
operators) .
Answer 26 (p. 506)
4.25.3.27 Question 27
True or false? In Java, the signed right shift operation populates the vacated bits with the zeros, while the
left shift and the unsigned right shift populate the vacated bits with the sign bit. If your answer is False,
explain why.
Answer 27 (p. 506)
4.25.3.28 Question 28
True or false? In a signed right-shift operation in Java, the bits shifted o the right end are lost. If your
answer is False, explain why.
Answer 28 (p. 506)
4.25.3.29 Question 29
Using the symbols 1 and 0, construct a truth table showing the four possible combinations of 1 and 0. Using
a 1 or a 0, show the result of the bitwise and operation on these four combinations of 1 and 0.
Answer 29 (p. 505)
4.25.3.30 Question 30
Using the symbols 1 and 0 construct a truth table showing the four possible combinations of 1 and 0. Using
a 1 or a 0, show the result of the bitwise inclusive or operation on these four combinations of 1 and 0.
Answer 30 (p. 505)
4.25.3.31 Question 31
Using the symbols 1 and 0 construct a truth table showing the four possible combinations of 1 and 0. Using
a 1 or a 0, show the result of the bitwise exclusive or operation on these four combinations of 1 and 0.
Answer 31 (p. 505)
4.25.3.32 Question 32
True or false? For the exclusive or , if the two bits are dierent, the result is a 1. If the two bits are the
same, the result is a 0. If your answer is False, explain why.
Answer 32 (p. 505)
4.25.3.33 Question 33
Is the assignment operator a unary operator or a binary operator. Select one or the other.
Answer 33 (p. 505)
4.25.3.34 Question 34
True or false? In Java, when using the assignment operator, the value stored in memory and represented by
the right operand is copied into the memory represented by the left operand. If your answer is False, explain
why.
Answer 34 (p. 505)
4.25.3.35 Question 35
Show two of the shortcut assignment operators and explain how they behave by comparing them with the
regular (non-shortcut) versions. Hint: the (^=) operator is a shortcut assignment operator.
Answer 35 (p. 504)
4.25.3.36 Question 36
Write a Java application that clearly illustrates the dierence between the prex and the postx versions of
the increment operator. Provide a termination message that displays your name.
Answer 36 (p. 504)
4.25.3.37 Question 37
Write a Java application that illustrates the use of the following relational operators:
note:
<
>
<=
>=
==
!=
Provide appropriate text in the output. Also provide a termination message with your name.
Answer 37 (p. 503)
4.25.3.38 Question 38
write a Java application that illustrates the use of the following logical or conditional operators:
&&
||
!
Provide appropriate text in the output. Also provide a termination message with your name.
Answer 38 (p. 502)
4.25.4 Listings
• Listing 1 (p. 496) . Listing for Question 13.
• Listing 2 (p. 497) . Listing for Question 22.
• Listing 3 (p. 502) . Listing for Answer 38.
• Listing 4 (p. 503) . Listing for Answer 37.
• Listing 5 (p. 504) . Listing for Answer 36.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.25.5 Answers
4.25.5.1 Answer 38
&& || !
4.63
4.25.5.2 Answer 37
4.64
4.25.5.3 Answer 36
4.65
4.25.5.4 Answer 35
Java supports the following list of shortcut assignment operators. These operators allow you to perform
an assignment and another operation with a single operator.
note:
+=
-=
*=
/=
%=
&=
|=
^=
=
=
>=
For example, the two statements that follow perform the same operation.
• x += y;
• x = x + y;
The behavior of each of the shortcut assignment operators follows this same pattern.
Back to Question 35 (p. 499)
4.25.5.5 Answer 34
True.
Back to Question 34 (p. 499)
4.25.5.6 Answer 33
The assignment operator is a binary operator.
Back to Question 33 (p. 499)
4.25.5.7 Answer 32
True.
Back to Question 32 (p. 499)
4.25.5.8 Answer 31
The answer for the bitwise exclusive or is:
• 11 1 xor 1 produces 0
• 10 1 xor 0 produces 1
• 01 0 xor 1 produces 1
• 00 0 xor 0 produces 0
4.25.5.9 Answer 30
The answer for the bitwise inclusive or is:
• 11 1 or 1 produces 1
• 10 1 or 0 produces 1
• 01 0 or 1 produces 1
• 00 0 or 0 produces 0
4.25.5.10 Answer 29
The answer for the bitwise and is:
• 11 1 and 1 produces 1
• 10 1 and 0 produces 0
• 01 0 and 1 produces 0
• 00 0 and 0 produces 0
4.25.5.11 Answer 28
True: Bits shifted o the right end are lost.
Back to Question 28 (p. 498)
4.25.5.12 Answer 27
False: In Java, the signed right shift operation populates the vacated bits with the sign bit, while the left
shift and the unsigned right shift populate the vacated bits with zeros.
Back to Question 27 (p. 498)
4.25.5.13 Answer 26
The following table shows the seven bitwise operators supported by Java.
4.25.5.14 Answer 25
The bitwise and operator and the bitwise inclusive or operator are shown below.
4.25.5.15 Answer 24
An important characteristic of the behavior of the logical and operator and the logical or operator
in Java is that the expressions containing them are evaluated from left to right. The evaluation of the
expression is. terminated as soon as the result of evaluating the expression can be determined. For example,
in the expression given in Question 24 (p. 498) , if the variable a is less than the variable b , there is
no need to evaluate the right operand of the || operator to determine the value of the entire expression.
Therefore, evaluation will terminate as soon as it is determined that a is less than b .
Back to Question 24 (p. 498)
4.25.5.16 Answer 23
The following three logical or conditional operators are supported by Java.
4.25.5.17 Answer 22
This program produces the following output:
note:
4.25.5.18 Answer 21
Java supports the following set of relational operators:
4.25.5.19 Answer 20
Relational operators return the boolean type in Java.
Back to Question 20 (p. 497)
4.25.5.20 Answer 19
Java supports the following four unary arithmetic operators.
Operator Description
+ Indicates a positive value
- Negates, or changes algebraic sign
++ Adds one to the operand,
both prefix and postfix
-- Subtracts one from operand,
both prefix and postfix
4.25.5.21 Answer 18
The operator coerces the value of the right operand to a string representation for use in the expression only.
If the right operand is a variable, the value stored in the variable is not modied in any way.
Back to Question 18 (p. 497)
4.25.5.22 Answer 17
The plus operator (+) is also used to concatenate strings as in the following code fragment:
4.25.5.23 Answer 16
Java support various arithmetic operators on oating point and integer numbers. The following table lists
ve of the binary arithmetic operators supported by Java.
Operator Description
4.25.5.24 Answer 15
As a result of performing the specied action, an operator can be said to return a value (or evaluate to a
value) of a given type. The type depends on the operator and the type of the operands. To evaluate to a
value means that after the action is performed, the operator and its operands are eectively replaced in the
expression by the value that is returned.
Back to Question 15 (p. 496)
4.25.5.25 Answer 14
False: Binary operators use inx notation, which means that the operator appears between its operands.
Back to Question 14 (p. 496)
4.25.5.26 Answer 13
The output from this Java application follows:
• x = 5
• X = 5
• x + X++ = 10
• X = 6
• y = 5
• Y = 5
• y + ++Y = 11
• Y = 6
4.25.5.27 Answer 12
The increment operator may be used with both prex and postx notation. Basically, the increment
operator causes the value of the variable to which it is applied to be increased by one.
With prex notation, the operand appears to the right of the operator (++X) , while with postx
notation, the operand appears to the left of the operator (X++) .
The dierence in behavior has to do with the point in the sequence of operations that the increment
actually occurs.
With the prex version, the variable is incremented before it is used to evaluate the larger overall
expression in which it appears. With the postx version, the variable is used to evaluate the larger overall
expression and then the variable is incremented.
Back to Question 12 (p. 495)
4.25.5.28 Answer 11
The symbol for the increment operator is two plus signs with no space between them (++).
Back to Question 11 (p. 495)
4.25.5.29 Answer 10
False: The increment operator is a unary operator.
Back to Question 10 (p. 495)
4.25.5.30 Answer 9
The cast operator is used to purposely convert from one type to another.
Back to Question 9 (p. 495)
4.25.5.31 Answer 8
The plus sign (+) is automatically overloaded in Java. The plus sign can be used to perform arithmetic
addition. It can also be used to concatenate strings. However, the plus sign does more than concatenate
strings. It also performs a conversion to String type. When the plus sign is used to concatenate strings
and one operand is a string, the other operand is automatically converted to a character string before being
concatenated with the existing string.
Back to Question 8 (p. 495)
4.25.5.32 Answer 7
The operators listed in order are:
• =
• !=
• +
• (char)
where the cast operator is being used to cast to the type char .
Back to Question 7 (p. 495)
4.25.5.33 Answer 6
Java does not support operator overloading by programmers.
Back to Question 6 (p. 495)
4.25.5.34 Answer 5
For those languages that support it (such as C++) operator overloading means that the programmer can
redene the behavior of an operator with respect to objects of a new type dened by that program.
Back to Question 5 (p. 494)
4.25.5.35 Answer 4
Both. As a binary operator, the minus sign causes its right operand to be subtracted from its left operand.
As a unary operator, the minus sign causes the algebraic sign of the right operand to be changed.
Back to Question 4 (p. 494)
4.25.5.36 Answer 3
An operator that operates on two operands is called a binary operator.
Back to Question 3 (p. 494)
4.25.5.37 Answer 2
An operator that operates on only one operand is called a unary operator.
Back to Question 2 (p. 494)
4.25.5.38 Answer 1
An operator performs an action on one or two operands.
Back to Question 1 (p. 494)
4.25.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.26.2 Preface
Java programs are composed of statements, and statements are constructed from expressions. This module
takes a very brief look at Java statements and expressions.border width
4.26.3 Introduction
The rst step
The rst step in learning to use a new programming language is usually to learn the foundation concepts
such as variables, types, expressions, ow-of-control, etc. This module concentrates on expressions and
statements.
71 This content is available online at <http://cnx.org/content/m45192/1.3/>.
4.26.4 Expressions
The hierarchy
Java programs are composed of statements, and statements are constructed from expressions.
An expression is a specic combination of operators and operands, that evaluates to a single value. The
operands can be variables, constants, or method calls.
A method call evaluates to the value returned by the method.
Named constants
Java supports named constants that are implemented through the use of the nal keyword.
The syntax for creating a named constant in Java is as follows:
While this is not a constant type, it does produce a value that can be referenced in the program and which
cannot be modied.
The nal keyword prevents the value of PI from being modied in this case (p. 512) . You will learn
later that there are some other uses for the nal keyword in Java as well.
Operator precedence
In some cases, the order in which the operations are performed determines the result. You can control
the order of evaluation by the use of matching parentheses.
If you don't provide such parentheses, the order will be determined by the precedence of the operators
(you should nd and review a table of Java operator precedence) with the operations having higher
precedence being evaluated rst.
4.26.5 Statements
According to The Java Tutorials
72 , "A statement forms a complete unit of execution."
A statement is constructed by combining one or more expressions into a compound expression and
terminating that expression with a semicolon.
4.26.7 Miscellaneous
This section contains a variety of miscellaneous information.
72 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
73 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 514) , 2 (p. 514) , 3 (p. 514) , 4 (p. 514) , 5 (p. 514) , 6 (p. 514) , 7 (p. 515) , 8 (p. 515) ,
9 (p. 515)
4.27.2 Preface
This module contains review questions and answers keyed to the module titled Jb0220: Java OOP: State-
ments and Expressions
75 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.27.3 Questions
4.27.3.1 Question 1 .
A Java program is composed of a series of what?
Answer 1 (p. 517)
4.27.3.2 Question 2
Statements in Java are constructed from what?
Answer 2 (p. 517)
4.27.3.3 Question 3
Describe an expression in Java.
Answer 3 (p. 517)
4.27.3.4 Question 4
What does a method call evaluate to in Java?
Answer 4 (p. 517)
4.27.3.5 Question 5
True or false? Java supports named constants. If false, explain why.
Answer 5 (p. 517)
4.27.3.6 Question 6
Provide a code fragment that illustrates the syntax for creating a named constant in Java.
Answer 6 (p. 516)
4.27.3.7 Question 7
True or false? Java supports a constant type. If false, explain why.
Answer 7 (p. 516)
4.27.3.8 Question 8
What is the common method of controlling the order of evaluation of expressions in Java?
Answer 8 (p. 516)
4.27.3.9 Question 9
If you don't use matching parentheses to control the order of evaluation of expressions, what is it that
controls the order of evaluation?
Answer 9 (p. 516)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.27.4 Answers
4.27.4.1 Answer 9
If you don't provide matching parentheses to control the order of evaluation, the order will be determined
by the precedence of the operators with the operations having higher precedence being evaluated rst. For
example, multiply and divide have higher precedence than add and subtract.
Back to Question 9 (p. 515)
4.27.4.2 Answer 8
You can control the order of evaluation by the use of matching parentheses.
Back to Question 8 (p. 515)
4.27.4.3 Answer 7
False. Java does not support a constant type. However, in Java, it is possible to achieve the same result by
declaring and initializing a variable and making it nal .
Back to Question 7 (p. 515)
4.27.4.4 Answer 6
The syntax for creating a named constant in Java is shown below.
4.27.4.5 Answer 5
True. Java supports named constants that are constructed using variable declarations with the nal
keyword.
Back to Question 5 (p. 514)
4.27.4.6 Answer 4
A method call evaluates to the value returned by the method.
Back to Question 4 (p. 514)
4.27.4.7 Answer 3
An expression is a specic combination of operators and operands that evaluates to a particular value. The
operands can be variables, constants, or method calls.
Back to Question 3 (p. 514)
4.27.4.8 Answer 2
Statements in Java re constructed from expressions.
Back to Question 2 (p. 514)
4.27.4.9 Answer 1
A Java program is composed of a series of statements.
Back to Question 1 (p. 514)
4.27.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.28.2 Preface
Java supports several dierent statements designed to alter or control the logical ow of the program. This
module explores those statements.
4.28.2.1.1 Images
• Image 1 (p. 520) . Statements that support ow of control.
• Image 2 (p. 521) . Syntax of a while statement.
• Image 3 (p. 522) . Syntax of an if-else statement.
4.28.2.1.2 Listings
• Listing 1 (p. 521) . Sample Java while statement.
• Listing 2 (p. 525) . A program that won't compile.
• Listing 3 (p. 526) . Another program that won't compile.
• Listing 4 (p. 527) . A program that will compile.
• Listing 5 (p. 528) . Another program that will compile.
• Listing 6 (p. 531) . The program named switch1.java.
• Listing 7 (p. 533) . The program named switch2.java.
4.28.3 Introduction
The rst step
The rst step in learning to use a new programming language is usually to learn the foundation concepts
such as variables, types, expressions, ow-of-control, etc. This module concentrates on ow-of-control .
Statement Type
if-else selection
switch-case selection
for loop
for-each loop
while loop
do-while loop
try-catch-finally exception handling
throw exception handling
break miscellaneous
continue miscellaneous
label: miscellaneous
return miscellaneous
goto reserved by Java but not supported
4.66
4.67
The while statement is commonly used to create a loop structure, often referred to as a while loop .
Once the while statement is encountered in the sequence of code, the program will continue to execute
the statement or compound statement shown in Image 2 (p. 521) for as long as the conditional expression
evaluates to true. (Note that a compound statement is created by enclosing two or more statements inside
a pair of matching curly brackets, thus creating a block of code as the body of the while statement or
loop.)
Sample Java while statement
The while statement shown in Listing 1 (p. 521) was extracted from a Java program in an earlier
module.
4.68
Therefore, the expressionSystem.in.read() in Listing 1 (p. 521) constitutes a call to the read
method of the object referred to by the in variable of the System class.
A while loop is an entry condition loop
The while statement is used to form an entry condition loop. The signicance of an entry condition
loop is that the conditional expression is tested before the statements in the loop are executed. If it tests
false initially, the statements in the loop are never executed.
The while loop shown in Listing 1 (p. 521) will continue reading characters from the keyboard for as
long as the character entered is not the # character. (Recall the not equal (!=) operator from an earlier
module.)
if(conditional expression)
statement or compound statement;
else //optional
statement or compound statement; //optional
4.69
The if-else statement is the most basic of the statements used to control the logical ow of a Java
program. It is used to satisfy the selection pillar mentioned earlier (p. 521) .
This statement will execute a specied block of code if some particular condition is true, and optionally,
will execute a dierent block of code if the condition is not true.
The else clause shown in Image 3 (p. 522) is optional. If it is not provided and the condition is not
true, control simply passes to the next statement following the If statement with none of the code in the
body of the if statement being executed. If the condition is true, the code in the body of the if statement
is executed.
If the else clause is provided and the condition is true, the code in the body of the if clause is executed
and the code in the body of the else clause is ignored.
If the else clause is provided and the condition is false, the code in the body of the if clause is ignored
and the code in the body of the else clause is executed.
In all cases, control passes to the next statement following the if-else statement when the code in the
if-else statement has nished executing. In other words, this is not a loop structure.
switch(expression){
case constant:
//sequence of optional statements
break; //optional
case constant:
//sequence of optional statements
break; //optional
.
.
.
default //optional
//sequence of optional statements
}
4.70
4.71
Multiple expressions can appear in the third clause, separated by the comma operator. Again, those
expressions will be executed from left to right. If variables are updated in the third clause and used in the
body of the loop, it is important to understand that they do not get updated until the execution of the body
is completed.
Declaring a variable in a for loop
As mentioned earlier, it is allowable to declare variables in the rst clause of a for loop.
You can declare a variable with a given name outside (prior to) the for loop, or you can declare it
inside the for loop, but not both.
If you declare it outside the for loop, you can access it either outside or inside the loop.
If you declare it inside the loop, you can access it only inside the loop. In other words, the scope of
variables declared inside a for loop is limited to the loop.
This is illustrated in following sequence of four simple programs.
This program won't compile
The Java program shown in Listing 2 (p. 525) refuses to compile with a complaint that a variable named
cnt has already been declared in the method when the attempt is made to declare it in the for loop.
System.out.println(
"Value of method var named cnt is " + cnt);
}//end main
}//End controlling class. Note no semicolon required
4.72
The program shown in Listing 3 (p. 526) also won't compile, but for a dierent reason.
System.out.println(
"Value of method var named cnt is " + cnt);
}//end main
}//End controlling class. Note no semicolon required
4.73
The declaration of the variable named cnt , outside the for loop, was removed from Listing 3 (p.
526) and the declaration inside the loop was allowed to remain. This eliminated the problem of attempting
to declare the variable twice.
However, this program refused to compile because an attempt was made to access the variable named
cnt outside the for loop. This was not allowed because the variable was declared inside the for loop and
the scope of the variable was limited to the loop.
This program will compile
The Java program shown in Listing 4 (p. 527) will compile and run because the variable named cnt
that is declared inside the for loop is accessed only inside the for loop. No reference to a variable with
the same name appears outside the loop.
4.74
System.out.println(
"Value of method var named cnt is " + cnt);
}//end main
}//End controlling class. Note no semicolon required
4.75
77 http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
do {
statements
} while (conditional expression);
4.76
Behavior
The statements in the body of the loop continue to be executed for as long as the conditional expression
evaluates to true. An exit-condition loop guarantees that the body of the loop will be executed at least one
time, even if the conditional expression evaluates to false the rst time it is tested.
A labeled continue statement can cause control to be passed to the next iteration of an outer enclosing
loop in a nested loop situation.
An example of the use of an unlabeled switch statement is given in the next section.
myLabel: myStatement;
4.77
/*File switch1.java
This is a Java application which serves as a baseline
comparison for switch2.java which uses a labeled break.
Note that the program uses nested switch statements.
********************************************************/
class switch1 { //define the controlling class
public static void main(String[] args){ //main method
4.78
After reviewing switch1.java , consider the same program named switch2.java shown in Listing 7
(p. 533) , which was modied to use a labeled break.
The outputs from both programs are shown in the comments at the beginning of the program. By
examining the second program, and comparing the output from the second program with the rst program,
you should be able to see how the use of the labeled break statement causes control to break all the way out
of the labeled switch statement.
/*File switch2.java
This is a Java application which uses a labeled break.
Note that the program uses nested switch statements.
case 6: System.out.println(
"Case 6 in outer switch");
default: System.out.println("Default in outer switch");
}//end outer switch statement
4.79
The modied program in Listing 7 (p. 533) uses a labeled break statement in the code group for case 1
whereas the original program in Listing 6 (p. 531) has an unlabeled break in that position.
By comparing the output from this program with the output from the previous program, you can see
that execution of the labeled break statement caused control to break all the way out of the labeled switch
statement completely bypassing case 6 and default.
As you can see from examining the output, the labeled break statement causes the program to break all
the way out of the switch statement which bears a matching label.
A similar situation exists when a labeled break is used in nested loops with one of the enclosing outer
loops being labeled. Control will break out of the enclosing loop to which the labeled break refers. It will
be left as an exercise for the student to demonstrate this behavior to his or her satisfaction.
return;
4.80
Returning a value
If the method returns a value, follow the word return with an expression (or constant) that evaluates
to the value being returned as shown in Image 9 (p. 535) .
return x+y;
4.81
78 http://cnx.org/content/m44148
79 http://cnx.org/content/m44153
4.28.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 537) , 2 (p. 537) , 3 (p. 537) , 4 (p. 537) , 5 (p. 537) , 6 (p. 538) , 7 (p. 538) , 8 (p. 538) ,
9 (p. 538) , 10 (p. 538) , 11 (p. 538) , 12 (p. 542) , 13 (p. 538) , 14 (p. 538) , 15 (p. 538) , 16
(p. 539) , 17 (p. 539) , 18 (p. 539) , 19 (p. 539) , 20 (p. 539) , 21 (p. 539)
4.29.2 Preface
This module contains review questions and answers keyed to the module titled Jb0230: Java OOP: Flow of
Control
81 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.29.3 Questions
4.29.3.1 Question 1 .
List and describe eight of the statements used in Java programs to alter or control the logical ow of the
program.
Answer 1 (p. 544)
4.29.3.2 Question 2
Provide pseudo-code that illustrates the general syntax of a while statement.
Answer 2 (p. 544)
4.29.3.3 Question 3
True or false? During the execution of a while statement, the program will continue to execute the
statement or compound statement for as long as the conditional expression evaluates to true, or until a
break or continue statement is encountered. If false, explain why.
Answer 3 (p. 544)
4.29.3.4 Question 4
True or false? A while loop is an entry condition loop. If false, explain why.
Answer 4 (p. 543)
4.29.3.5 Question 5
What is the signicance of an entry condition loop?
Answer 5 (p. 543)
4.29.3.6 Question 6
Provide pseudo-code illustrating the general syntax of the if-else statement.
Answer 6 (p. 543)
4.29.3.7 Question 7
Provide pseudo-code illustrating the general syntax of the switch-case statement.
Answer 7 (p. 543)
4.29.3.8 Question 8
Describe the behavior of a switch-case statement. Provide a pseudo-code fragment that illustrates your
description of the behavior. Do not include a description of labeled break statements.
Answer 8 (p. 542)
4.29.3.9 Question 9
What are the three actions normally involved in the operation of a loop (in addition to executing the code
in the body of the loop) ?
Answer 9 (p. 542)
4.29.3.10 Question 10
True or false? A for loop header consists of three clauses separated by colons. If false, explain why.
Answer 10 (p. 542)
4.29.3.11 Question 11
Provide pseudo-code illustrating the general syntax of a for loop
Answer 11 (p. 542)
4.29.3.12 Question 12
True or false? In a for loop, the rst and third clauses within the parentheses can contain one or more
expressions, separated by the comma operator. If False, explain why.
Answer 12 (p. 542)
4.29.3.13 Question 13
What is the guarantee made by the comma operator ?
Answer 13 (p. 541)
4.29.3.14 Question 14
True or false? The expressions within the rst clause in the parentheses in a for loop are executed only
once during each iteration of the loop. If false, explain why.
Answer 14 (p. 541)
4.29.3.15 Question 15
While any legal expression(s) may be contained in the rst clause within the parentheses of a for loop, the
rst clause has a specic purpose. What is that purpose?
Answer 15 (p. 541)
4.29.3.16 Question 16
True or false? Variables can be declared and initialized within the rst clause in the parentheses of a for
loop. If false, explain why.
Answer 16 (p. 541)
4.29.3.17 Question 17
True or false? The second clause in the parentheses of a for loop consists of a single expression which must
eventually evaluate to true to cause the loop to terminate. If false, explain why.
Answer 17 (p. 541)
4.29.3.18 Question 18
True or false? A for loop is an exit condition loop. If false, explain why.
Answer 18 (p. 541)
4.29.3.19 Question 19
True or false? Because a for loop is an entry condition loop, the third clause inside the parentheses is
executed at the beginning of each iteration. If false, explain why.
Answer 19 (p. 541)
4.29.3.20 Question 20
True or false? A return statement is used to terminate a method and (optionally) return a value to the
calling method. If False, explain why.
Answer 20 (p. 541)
4.29.3.21 Question 21
True or false? Exception handling modies the ow of control of a Java program. If false, explain why.
Answer 21 (p. 541)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.29.4 Answers
4.29.4.1 Answer 21
True.
Back to Question 21 (p. 539)
4.29.4.2 Answer 20
True.
Back to Question 20 (p. 539)
4.29.4.3 Answer 19
False. Although the third clause appears physically at the top of the loop, it isn't executed until the
statements in the body of the loop have completed execution. This is an important point since this clause is
typically used to update the control variable, and perhaps other variables as well. If variables are updated
in the third clause and used in the body of the loop, it is important to understand that they do not get
updated until the execution of the body is completed.
Back to Question 19 (p. 539)
4.29.4.4 Answer 18
False. The value of the second clause is tested when the statement rst begins execution, and at the beginning
of each iteration thereafter. Therefore, the for loop is an entry condition loop.
Back to Question 18 (p. 539)
4.29.4.5 Answer 17
False. The second clause consists of a single expression which must eventually evaluate to false (not true)
to cause the loop to terminate.
Back to Question 17 (p. 539)
4.29.4.6 Answer 16
True.
Back to Question 16 (p. 539)
4.29.4.7 Answer 15
Typically the rst clause is used for initialization. The intended purpose of the rst clause is initialization.
Back to Question 15 (p. 538)
4.29.4.8 Answer 14
False. The expressions in the rst clause are executed only once, at the beginning of the loop, regardless of
the number of iterations.
Back to Question 14 (p. 538)
4.29.4.9 Answer 13
The comma operator guarantees that its left operand will be executed before its right operand.
Back to Question 13 (p. 538)
4.29.4.10 Answer 12
True.
Back to Question 12 (p. 538)
4.29.4.11 Answer 11
The general syntax of a for loop follows:
4.29.4.12 Answer 10
False: A for loop header consists of three clauses separated by semicolons, not colons.
Back to Question 10 (p. 538)
4.29.4.13 Answer 9
The operation of a loop normally involves the following three actions in addition to executing the code in
the body of the loop:
4.29.4.14 Answer 8
The pseudo-code fragment follows:
switch(expression){
case constant:
sequence of optional statements
break; //optional
case constant:
sequence of optional statements
break; //optional
.
.
.
default //optional
sequence of optional statements
}
An expression is tested against a series of unique integer constants. If a match is found, the sequence of
optional statements associated with the matching constant is executed. Execution of statements continues
until an optional break is encountered. When break is encountered, execution of the switch statement
is terminated and control is passed to the next statement following the switch statement.
If no match is found and the optional default keyword along with a sequence of optional statements
has been provided, those statements will be executed.
Back to Question 8 (p. 538)
4.29.4.15 Answer 7
The general syntax of the switch-case statement follows:
switch(expression){
case constant:
sequence of optional statements
break; //optional
case constant:
sequence of optional statements
break; //optional
.
.
.
default //optional
sequence of optional statements
}
4.29.4.16 Answer 6
The general syntax of the if-else statement is:
if(conditional expression)
statement or compound statement;
else //optional
statement or compound statement; //optional
4.29.4.17 Answer 5
The signicance of an entry condition loop is that the conditional expression is tested before the statements
in the loop are executed. If it tests false initially, the statements in the loop will not be executed.
Back to Question 5 (p. 537)
4.29.4.18 Answer 4
True.
Back to Question 4 (p. 537)
4.29.4.19 Answer 3
True.
Back to Question 3 (p. 537)
4.29.4.20 Answer 2
The general syntax of a while statement follows :
4.29.4.21 Answer 1
The following table lists the statements supported by Java for controlling the logical ow of the program.
4.29.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.30.2 Preface
This module takes a preliminary look at arrays and strings. More in-depth discussions will be provided in
future modules. For example, you will nd a more in-depth discussions of array objects in the following
modules:
4.30.2.1.1 Images
• Image 1 (p. 547) . Formats for declaring a reference variable for an array object.
• Image 2 (p. 547) . Allocating memory for the array object.
• Image 3 (p. 548) . Declaration and instantiation can be separated.
• Image 4 (p. 548) . General syntax for combining declaration and instantiation.
• Image 5 (p. 549) . An example of array indexing syntax.
• Image 6 (p. 549) . The use of the length property in the conditional clause of a for loop.
• Image 7 (p. 556) . A string literal.
• Image 8 (p. 556) . String concatenation.
• Image 9 (p. 557) . Declaring and instantiating a String array.
• Image 10 (p. 557) . Allocating memory to contain the String objects.
4.30.2.1.2 Listings
• Listing 1 (p. 551) . The program named array01.
• Listing 2 (p. 553) . The program named array02.
• Listing 3 (p. 555) . The program named array03.
4.30.3 Introduction
The rst step
The rst step in learning to use a new programming language is usually to learn the foundation concepts
such as variables, types, expressions, ow-of-control, arrays, strings, etc. This module concentrates on arrays
and strings.
Array and String types
Java provides a type for both arrays and strings from which objects of the specic type can be instantiated.
Once instantiated, the methods belonging to those types can be called by way of the object.
4.30.4 Arrays
Arrays and Strings
Java has a true array type and a true String type with protective features to prevent your program
from writing outside the memory bounds of the array object or the String object. Arrays and strings are
true objects.
Declaring an array
You must declare an array before you can use it. (More properly, you must declare a reference variable
to hold a reference to the array object.) In declaring the array, you must provide two important pieces of
information:
int[] myArray;
int myArray[];
4.82
4.83
The statements in Image 2 (p. 547) simultaneously declare the reference variable and cause memory to
be allocated to contain the array.
Also note that the last statement in Image 2 (p. 547) is dierent from the rst two statements. This
syntax not only sets aside the memory for the array object, the elements in the array are initialized by
evaluating the expressions shown in the coma-separated list inside the curly brackets.
On the other hand, the array elements in the rst two statements in Image 2 (p. 547) are automatically
initialized with the default value for the type.
Declaration and allocation can be separated
It is not necessary to combine these two processes. You can execute one statement to declare the reference
variable and another statement to cause the array object to be instantiated some time later in the program
int[] myArray;
. . .
myArray = new int[25];
4.84
Causing memory to be set aside to contain the array object is commonly referred to as instantiating the
array object (creating an instance of the array object) .
If you prefer to declare the reference variable and instantiate the array object at dierent points in your
program, you can use the syntax shown in Image 3 (p. 548) . This pattern is very similar to the declaration
and instantiation of all objects.
General syntax for combining declaration and instantiation
The general syntax for declaring and instantiating an array object is shown in Image 4 (p. 548) .
typeOfElements[] nameOfRefVariable =
new typeOfElements[sizeOfArray]
4.85
myArray[5] = 6;
myVar = myArray[5];
4.86
Image 6: The use of the length property in the conditional clause of a for loop.
4.87
All array objects have a length property that can be accessed to determine the number of elements in
the array. (The number of elements cannot change once the array object is instantiated.)
Types of data that you can store in an array object
Array elements can contain any Java data type including primitive values and references to ordinary
objects or other array objects.
Constructing multi-dimensional arrays
All array objects contains a one-dimensional array structure. You can create multi-dimensional arrays
by causing the elements in one array object to contain references to other array objects. In eect, you can
create a tree structure of array objects that behaves like a multi-dimensional array.
Odd-shaped multi-dimensional arrays
The programarray01 shown in Listing 1 (p. 551) illustrates an interesting aspect of the Java arrays.
Java can produce multi-dimensional arrays that can be thought of as an array of arrays. However, the
00
012
0246
Attempt to access array out of bounds
java.lang.ArrayIndexOutOfBoundsException:
at array01.main(array01.java: 47)
**********************************************************/
class array01 { //define the controlling class
public static void main(String[] args){ //main method
//Declare a two-dimensional array with a size of 3 on
// the primary dimension but with different sizes on
// the secondary dimension.
//Secondary size not specified initially
int[][] myArray = new int[3][];
myArray[0] = new int[2];//secondary size is 2
myArray[1] = new int[3];//secondary size is 3
myArray[2] = new int[4];//secondary size is 4
}//end main
}//End array01 class.
4.88
552 CHAPTER 4. PROGRAMMING FUNDAMENTALS
firstArray contents
0 1 2
secondArray contents
0 1 2
Change a value in firstArray and display both again
firstArray contents
0 10 2
secondArray contents
0 10 2
**********************************************************/
class array02 { //define the controlling class
int[] firstArray;
int[] secondArray;
array02() {//constructor
firstArray = new int[3];
for(int cnt = 0; cnt < 3; cnt++) firstArray[cnt] = cnt;
System.out.println();
System.out.println(
"Change value in firstArray and display both again");
obj.firstArray[1] = 10;
System.out.println(
Available"secondArray contents"
for free at Connexions );
<http://cnx.org/content/col11441/1.121>
• Declare a reference variable to an array of type Date . (The actual type of the variable is Date[].)
• Instantiate a three-element array of reference variables of type Date .
• Display the contents of the array elements and conrm that they are all null as they should be.
(When created using this syntax, new array elements contain the default value, which is null for
reference types.)
• Instantiate three objects of type Date and store the references to those objects in the three elements
of the array.
• Access the references from the array and use them to display the contents of the individual Date
objects.
As you might expect from the name of the class, each object contains information about the date.
myArrayOfRefs contains
null
null
null
myArrayOfRefs contains
Sat Dec 20 16:56:34 CST 1997
Sat Dec 20 16:56:34 CST 1997
Sat Dec 20 16:56:34 CST 1997
**********************************************************/
import java.util.*;
array03() {//constructor
//Instantiate the array of three reference variables
// of type Date. They will be initialized to null.
myArrayOfRefs = new Date[3];
}//end constructor
//-----------------------------------------------------//
4.30.6 Strings
What is a string?
A string is commonly considered to be a sequence of characters stored in memory and accessible as a
unit.
Java implements strings using the String class and the StringBuer class.
What is a string literal?
Java considers a series of characters surrounded by quotation marks as shown in Image 7 (p. 556) to be
a string literal.
4.91
4.92
4.93
4.94
4.30.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
86 http://cnx.org/content/m44148
87 http://cnx.org/content/m44153
· 1 (p. 559) , 2 (p. 559) , 3 (p. 559) , 4 (p. 559) , 5 (p. 559) , 6 (p. 560) , 7 (p. 560) , 8 (p. 560) ,
9 (p. 560) , 10 (p. 560) , 11 (p. 560) , 12 (p. 566) , 13 (p. 560) , 14 (p. 561) , 15 (p. 561) , 16
(p. 561) , 17 (p. 561) , 18 (p. 561)
4.31.2 Preface
This module contains review questions and answers keyed to the module titled Jb0240: Java OOP: Arrays
and Strings
89 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.31.3 Questions
4.31.3.1 Question 1 .
True or false? Arrays and Strings are true objects. If false, explain why.
Answer 1 (p. 568)
4.31.3.2 Question 2
True or false? It is easy to write outsides the bounds of a String or an array. If false, explain why.
Answer 2 (p. 568)
4.31.3.3 Question 3
You must declare a variable capable of holding a reference to an array object before you can use it. In
declaring the variable, you must provide two important pieces of information. What are they?
Answer 3 (p. 567)
4.31.3.4 Question 4
Provide code fragments that illustrate the two dierent syntaxes that can be used to declare a variable
capable of holding a reference to an array object that will store data of type int.
Answer 4 (p. 567)
4.31.3.5 Question 5
True or false? When you declare a variable capable of holding a reference to an array object, the memory
required to contain the array object is automatically allocated. If false, explain why and show how memory
can be allocated.
Answer 5 (p. 567)
4.31.3.6 Question 6
True or false? It is required that you simultaneously declare the name of the variable and cause memory to
be allocated to contain the array object in a single statement. If false, explain why and show code fragments
to illustrate your answer.
Answer 6 (p. 567)
4.31.3.7 Question 7
True or false? Array indices always begin with 1. If false, explain why.
Answer 7 (p. 566)
4.31.3.8 Question 8
What is the name of the property of arrays that can be accessed to determine the number of elements in the
array? Provide a sample code fragment that illustrates the use of this property.
Answer 8 (p. 566)
4.31.3.9 Question 9
What types of data can be stored in array objects?
Answer 9 (p. 566)
4.31.3.10 Question 10
True or false? Just as in other languages, when you create a multi-dimensional array, the secondary arrays
must all be of the same size. If false, explain your answer. Then provide a code fragment that illustrates
your answer or refer to a sample program in Jb0240: Java OOP: Arrays and Strings
90 that illustrates your
answer.
Answer 10 (p. 566)
4.31.3.11 Question 11
True or false? Just as in other languages, when declaring a two-dimensional array, it is necessary to declare
the size of the secondary dimension when the array is declared. If false, explain your answer. Then provide
a code fragment that illustrates your answer or refer to a sample program in Jb0240: Java OOP: Arrays and
Strings
91 that illustrates your answer.
Answer 11 (p. 566)
4.31.3.12 Question 12
True or false? Java allows you to assign one array to another. Explain what happens when you do this.
Then provide a code fragment that illustrates your answer or refer to a sample program in Jb0240: Java
OOP: Arrays and Strings
92 that illustrates your answer.
Answer 12 (p. 566)
4.31.3.13 Question 13
Give a brief description of the concept of a string and list the names of two classes used to implement strings?
Answer 13 (p. 566)
90 http://cnx.org/content/m45214
91 http://cnx.org/content/m45214
92 http://cnx.org/content/m45214
4.31.3.14 Question 14
What is the syntax that is used to create a literal string? Provide a code fragment to illustrate your answer.
Answer 14 (p. 565)
4.31.3.15 Question 15
Explain the dierence between objects of types String and StringBuer .
Answer 15 (p. 565)
4.31.3.16 Question 16
Provide a code fragment that illustrates how to concatenate strings.
Answer 16 (p. 565)
4.31.3.17 Question 17
Provide a code fragment that declares and instantiates an array object capable of storing references to two
String objects. Explain what happens when this code fragment is executed. Then show a code fragment
that will allocate memory for the actual String objects.
Answer 17 (p. 565)
4.31.3.18 Question 18
Write a Java application that illustrates the creation and manipulation of a two-dimensional array with the
sub arrays being of dierent lengths. Also cause your application to illustrate that an attempt to access an
array element out of bounds results in an exception being thrown. Catch and process the exception. Display
a termination message with your name.
Answer 18 (p. 564)
4.31.4 Listings
• Listing 1 (p. 564) . Listing for Answer 18.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.31.5 Answers
4.31.5.1 Answer 18
}//end main
}//End SampProg10 class. Note no semicolon required
4.95
4.31.5.2 Answer 17
The following statement declares and instantiates an array object capable of storing references to two String
objects.
note:
Note however, that this array object doesn't contain the actual string data. Rather, it simply sets aside
memory for storage of two references to String objects. No memory has been set aside to store the
characters that make up the individual strings. You must allocate the memory for the actual String
objects separately using code similar to the following.
note:
4.31.5.3 Answer 16
Java supports string concatenation using the overloaded + operator as shown in the following code fragment:
note:
4.31.5.4 Answer 15
String objects cannot be modied once they have been created. StringBuer objects can be modied
Back to Question 15 (p. 561)
4.31.5.5 Answer 14
The Java compiler considers a series of characters surrounded by quotation marks to be a literal string, as
in the following code fragment:
note:
4.31.5.6 Answer 13
A string is commonly considered to be a sequence of characters stored in memory and accessible as a unit.
Java implements strings using the String class and the StringBuer class.
Back to Question 13 (p. 560)
4.31.5.7 Answer 12
Java allows you to assign one array to another. When you do this, you are simply making another copy of
the reference to the same data in memory. Then you have two references to the same data in memory. This
is illustrated in the program named array02.java in Jb0240: Java OOP: Arrays and Strings
93 .
Back to Question 12 (p. 560)
4.31.5.8 Answer 11
False. When declaring a two-dimensional array, it is not necessary to declare the size of the secondary
dimension when the array is declared. Declaration of the size of each sub-array can be deferred until later
as illustrated in the program named array01.java in Jb0240: Java OOP: Arrays and Strings
94 .
Back to Question 11 (p. 560)
4.31.5.9 Answer 10
False. Java can be used to produce multi-dimensional arrays that can be viewed as an array of arrays.
However, the secondary arrays need not all be of the same size. See the program named array01.java in
Jb0240: Java OOP: Arrays and Strings
95 .
Back to Question 10 (p. 560)
4.31.5.10 Answer 9
Array objects can contain any Java data type including primitive values, references to ordinary objects, and
references to other array objects.
Back to Question 9 (p. 560)
4.31.5.11 Answer 8
All array objects have a length property that can be accessed to determine the number of elements in the
array as shown below.
note:
4.31.5.12 Answer 7
False. Array indices always begin with 0.
Back to Question 7 (p. 560)
93 http://cnx.org/content/m45214
94 http://cnx.org/content/m45214
95 http://cnx.org/content/m45214
4.31.5.13 Answer 6
False. While it is possible to simultaneously declare the name of the variable and cause memory to be
allocated to contain the array object, it is not necessary to combine these two processes. You can execute
one statement to declare the variable and another statement to cause the memory for the array object to be
allocated as shown below.
note:
int[] myArray;
.
.
.
myArray = new int[25];
4.31.5.14 Answer 5
False. As with other objects. the declaration of the variable does not allocate memory to contain the array
object. Rather it simply allocates memory to contain a reference to the array object. Memory to contain
the array object must be allocated from dynamic memory using statements such as the following.
note:
4.31.5.15 Answer 4
note:
int[] myArray;
int myArray[];
4.31.5.16 Answer 3
In declaring the variable, you must provide two important pieces of information:
4.31.5.17 Answer 2
False. Java has a true array type and a true String type with protective features to prevent your program
from writing outside the memory bounds of the array or the String .
Back to Question 2 (p. 559)
4.31.5.18 Answer 1
True.
Back to Question 1 (p. 559)
4.31.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.32.2 Preface
This module provides a very brief treatment of exception handling. The topic is discussed in detail in the
module titled Java OOP: Exception Handling
97 . The topic is included in this Programming Fundamentals
section simply to introduce you to the concept.
4.32.2.1.1 Listings
• Listing 1 (p. 570) . The program named simple1.
4.32.3 Discussion
What is an exception?
According to The Java Tutorials
98 ,
"An exception is an event that occurs during the execution of a
program that disrupts the normal ow of instructions."
A very common example of an exception given in textbooks is code that attempts to divide by zero (this
is easy to demonstrate) .
Throwing an exception
Common terminology states that when this happens, the system throws an exception . If a thrown
exception is not caught , a runtime error may occur.
Purpose of exception handling
The purpose of exception handling is to make it possible for the program to either attempt to recover
from the problem, or at worst shut down the program in a graceful manner, whenever an exception occurs.
Java supports exception handling
Java, C++, and some other programming languages support exception handling in similar ways.
In Java, the exception can be thrown either by the system or by code created by the programmer. There
is a fairly long list of exceptions that will be thrown automatically by the Java runtime system.
Checked exceptions cannot be ignored
Included in that long list of automatic exceptions is a subset known as "checked" exceptions. Checked
exceptions cannot be ignored by the programmer. A method must either specify (declare) or catch all
"checked" exceptions that can be thrown in order for the program to compile.
An example of specifying an exception
I explain the dierence between specifying and catching an exception in Java OOP: Exception Handling
99 . For now, suce it to say that the code that begins with the word "throws" in Listing 1 (p. 570) species
(declares) an exception that can be thrown by the code inside the main method.
If this specication is not made, the program will not compile.
97 http://cnx.org/content/m44202
98 http://docs.oracle.com/javase/tutorial/essential/exceptions/
99 http://cnx.org/content/m44202
System.out.println(
"Enter some text, terminate with #");
4.96
The program in Listing 1 (p. 570) does not throw any exceptions directly nor does it attempt to catch
any exceptions. However, it can throw exceptions indirectly through its call to System.in.read .
Because IOException is a checked exception, the main method must either specify it or catch it .
Otherwise the program won't compile. In this case, the main method species the exception as opposed
to catching it.
Very brief treatment
As mentioned earlier, this is a very brief treatment of a fairly complex topic that is discussed in much
more detail in the module titled Java OOP: Exception Handling
100 . The topic was included at this point
simply to introduce you to the concept of exceptions.
100 http://cnx.org/content/m44202
101 http://cnx.org/content/m44148
4.32.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.33.2 Preface
Although the use of command-line arguments is rare is this time of Graphical User Interfaces (GUI) , they
are still useful for testing and debugging code. This module explains the use of command-line arguments in
Java.
102 http://cnx.org/content/m44153
103 This content is available online at <http://cnx.org/content/m45246/1.4/>.
4.33.2.1.1 Listings
• Listing 1 (p. 573) . Illustration of command-line arguments.
4.33.3 Discussion
Familiar example from DOS
Java programs can be written to accept command-line-arguments.
DOS users will be familiar with commands such as the following:
In this case, copy is the name of the program to be executed, while leA and leB are command-line
arguments.
Java syntax for command-line arguments
The Java syntax for supporting command-line arguments is shown below (note the formal argument list
for the main method) .
In Java, the formal argument list for the main method must appear in the method signature whether or
not the program is written to support the use of command-line arguments. If the argument isn't used, it is
simply ignored.
Where the arguments are stored
args contains a reference to a one-dimensional array object of type String
The parameter .
Each of the elements in the array (including the element at index zero) contains a reference to an object
of type String . Each object of type String encapsulates one command-line argument.
The number of arguments entered by the user
Recall from an earlier module on arrays that the number of elements in a Java array can be obtained
from the length property of the array. Therefore, the number of arguments entered by the user is equal
to the value of the length property. If the user didn't enter any arguments, the value will be zero.
Command-line arguments are separated by the space character. If you need to enter an argument that
contains a space, surround the entire argument with quotation mark characters as in "My command line
argument" .
The rst command-line argument is encapsulated in the String object referred to by the contents of
the array element at index 0, the second argument is referred to by the element at index 1, etc.
Sample Java program
The sample program in Listing 1 (p. 573) illustrates the use of command-line arguments.
My
command
line
arguments
********************************************************/
class cmdlin01 { //define the controlling class
public static void main(String[] args){ //main method
for(int i=0; i < args.length; i++)
System.out.println( args[i] );
}//end main
}//End cmdlin01 class.
4.97
The output from running this program for a specic input is shown in the comments at the beginning of
the program.
104 http://cnx.org/content/m44148
105 http://cnx.org/content/m44153
4.33.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 575) , 2 (p. 575) , 3 (p. 575) , 4 (p. 575) , 5 (p. 575) , 6 (p. 576)
4.34.2 Preface
This module contains review questions and answers keyed to the module titled Jb0260: Java OOP: Command-
Line Arguments
107 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.34.3 Questions
4.34.3.1 Question 1 .
Provide a common example of a command-line statement that illustrates the use of command-line-arguments.
Answer 1 (p. 579)
4.34.3.2 Question 2
Describe the purpose of command-line-arguments.
Answer 2 (p. 579)
4.34.3.3 Question 3
True or false? In Java, syntax provisions must be made in the method signature for the main method to
accommodate command-line-arguments even if the remainder of the program is not designed to make use of
them. If False, explain why.
Answer 3 (p. 579)
4.34.3.4 Question 4
Provide the method signature for the main method in a Java application that is designed to accommodate
the use of command-line-arguments. Identify the part of the method signature that applies to command-
line-arguments and explain how it works.
Answer 4 (p. 578)
4.34.3.5 Question 5
Explain how a Java application can determine the number of command-line-arguments actually entered by
the user.
Answer 5 (p. 578)
4.34.3.6 Question 6
Write a program that illustrates the handling of command-line arguments in Java.
Answer 6 (p. 578)
4.34.4 Listings
• Listing 1 (p. 578) . Handling command-line arguments in Java.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.34.5 Answers
4.34.5.1 Answer 6
4.98
4.34.5.2 Answer 5
The number of command-line arguments is equal to the number of elements in the array of references to
String objects referred to by args . The number of elements is indicated by the value of the length
property of the array. If the value is zero, the user didn't enter any command-line arguments.
Back to Question 5 (p. 575)
4.34.5.3 Answer 4
The Java syntax for command-line arguments is shown below.
Each of the elements in the array object referred to by args (including the element at position zero)
contains a reference to a String object that encapsulates one of the command-line arguments.
Back to Question 4 (p. 575)
4.34.5.4 Answer 3
True.
Back to Question 3 (p. 575)
4.34.5.5 Answer 2
Command-line-arguments are used in many programming and computing environments to provide informa-
tion to the program at startup that it will need to fulll its mission during that particular invocation.
Back to Question 2 (p. 575)
4.34.5.6 Answer 1
DOS users will be familiar with commands such as the following:
In this case, copy is the name of the program to be executed, while leA and leB are command-line
arguments.
Back to Question 1 (p. 575)
4.34.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.35.2 Preface
This module explains the concept of packages and provides a sample program that illustrates the concept.
4.35.2.1.1 Listings
• Listing 1 (p. 585) . File: Package00.java.
• Listing 2 (p. 586) . File Package01.java.
• Listing 3 (p. 586) . File Package02.java.
• Listing 4 (p. 587) . File: CompileAndRun.bat.
4.35.3 Introduction
Before you can understand much about packages, you will need to understand the classpath environment
variable , so that is where I will begin the discussion.
After learning about the classpath environment variable, you will learn how to create your own packages.
note: In a nutshell Environment variables provide information that the operating system
uses to do its job.
There are usually a fairly large number of environment variables installed on a machine at any give time. If
you would like to see what kind of environment variables are currently installed on your machine, bring up
a command-line prompt and enter the command set . This should cause the names of several environment
variables, along with their settings to be displayed on your screen.
While you are at it, see if any of those items begin with CLASSPATH= . If so, you already have a
classpath environment variable set on your machine, but it may not contain everything that you need.
I am currently using a Windows 7 operating system and no classpath environment variable is set on it. I
tend to use the -cp switch option (see Listing 4 (p. 587) ) in the JDK to set the classpath on a temporary
basis when I need it to be set.
Rather than trying to explain all of the ramications regarding the classpath, I will simply refer you to
an Oracle document on the topic titled Setting the class path
109 .
I will also refer you to Java OOP: The Guzdial-Ericson Multimedia Class Library
110 where I discuss the
use of the classpath environment variable with a Java multimedia class library.
Some rules
There are some rules that you must follow when working with the classpath variable, and if you fail to
do so, things simply won't work.
For example, if your class les are in a jar le, the classpath must end with the name of that jar le.
On the other hand, if the class les are not in a jar le, the classpath must end with the name of the
folder that contains the class les.
Your classpath must contain a fully-qualied path name for every folder that contains class les of interest,
or for every jar le of interest. The paths should begin with the letter specifying the drive and end either
with the name of the jar le or the name of the folder that contains the class les. .
If you followed the default JDK installation procedure and are simply compiling and executing Java
programs in the current directory you probably won't need to set the classpath. By default, the system
already knows (or can gure out) how to allow you to compile and execute programs in the current
directory and how to use the JDK classes that come as part of the JDK.
However, if you are using class libraries other than the standard Java library, are saving your class les
in one or more dierent folders, or are ready to start creating your own packages, you will need to set the
classpath so that the system can nd the class les in your packages.
109 http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
110 http://cnx.org/content/m44148
hierarchy. The remaining hierarchy structure is encoded into our programs using package directives and
import directives.
Now here is a little jewel of information that cost me about seven hours of eort to discover when I
needed it badly.
When I rst started developing my own packages, I spent about seven hours trying to determine why the
compiler wouldn't recognize the top-level folder in my hierarchy of package folders.
I consulted numerous books by respected authors and none of them was any help at all. I nally found the
following statement in the Java documentation (when all else fails, read the documentation) . By the way,
a good portion of that wasted seven hours was spent trying to nd this information in the documentation
which is voluminous.
note: The following text was extracted directly from the JDK 1.1 documentation
If you want the CLASSPATH to point to class les that belong to a package, you should specify a
path name that includes the path to the directory one level above the directory having the name
of your package.
For example, suppose you want the Java interpreter to be able to nd classes in the package
mypackage. If the path to the mypackage directory is C:\java\MyClasses\mypackage, you would
set the CLASSPATH variable as follows:
set CLASSPATH=C:\java\MyClasses
If you didn't catch the signicance of this, read it again. When you are creating a classpath variable to
point to a folder containing classes, it must point to the folder. However, when you are creating a classpath
variable to point to your package, it must point to the folder that is one level above the directory that is the
top-level folder in your package.
Once I learned that I had to cause the classpath to point to the folder immediately above the rst folder
in the hierarchy that I was including in my package directives, everything started working.
note: Purpose of a package directive The purpose of the package directive is to identify
a particular class (or group of classes contained in a single source le (compilation unit)) as
belonging to a specic package.
This is very important information for a variety of reasons, not the least of which is the fact that the entire
access control system is wrapped around the concept of a class belonging to a specic package. For example,
code in one package can only access public classes in a dierent package.
Stated in the simplest possible terms, a package is a group of class les contained in a single folder on
your hard drive.
At compile time, a class can be identied as being part of a particular package by providing a package
directive at the beginning of the source code..
A package directive, if it exists, must occur at the beginning of the source code (ignoring comments and
white space) . No text other than comments and whitespace is allowed ahead of the package directive.
If your source code le does not contain a package directive, the classes in the source code le become
part of the default package . With the exception of the default package, all packages have names, and
those names are the same as the names of the folders that contain the packages. There is a one-to-one
correspondence between folder names and package names. The default package doesn't have a name.
Some examples of package directives that you will see in upcoming sample programs follow:
package Combined.Java.p1;
package Combined.Java.p2;
note:
c:\Baldwin\JavaProg\Combined\Java\p1
c:\Baldwin\JavaProg\Combined\Java\p2
Notice how I concatenated the package directive to the classpath setting and substituted the backslash
character for the period when converting from the package directive to the fully-qualied path name.
Code in one package can refer to a class in another package (if it is otherwise accessible) by qualifying
the class name with its package name as follows :
note:
Combined.Java.p2.Access02 obj02 =
new Combined.Java.p2.Access02();
Obviously, if we had to do very much of that, it would become very burdensome due to the large amount of
typing required. As you already know, the import directive is available to allow us to specify the package
containing the class just once at the beginning of the source le and then refer only to the class name for
the remainder of that source le.
import java.awt.*
import java.awt.event.ActionEvent
The rst import directive makes all of the class les in the java.awt package available for use in the code
in a dierent package by referring only to their le names.
The second import directive makes only the class le named ActionEvent in the java.awt.event
package available by referring only to the le name.
In other words, in this sample program, we create our own package structure and populate it with a set
of cooperating class les.
A folder named jnk is a child of the root folder on the M-drive.
A folder named SampleCode is a child of the folder named jnk .
A folder named Combined is a child of the folder named SampleCode .
A folder named Java is a child of the folder named Combined .
Folders named p1 and p2 are children of the folder named Java .
The le named Package00.java , shown in Listing 1 (p. 585) is stored in the folder named Java .
Starting Package00
Instantiate obj of public classes in different packages
Constructing Package01 object in folder p1
Constructing Package02 object in folder p2
Back in main of Package00
**********************************************************/
package Combined.Java; //package directive
class Package00{
public static void main(String[] args){ //main method
System.out.println("Starting Package00");
4.99
The le named Package01.java , shown in Listing 2 (p. 586) is stored in the folder named p1 .
4.100
The le named Package02.java , shown in Listing 3 (p. 586) is stored in the folder named p2 .
4.101
The le named CompileAndRun .bat, shown in Listing 4 (p. 587) is stored in the folder named
SampleCode .
echo off
rem This file is located in folder named M:\SampleCode,
rem which is Parent of folder Combined.
del Combined\Java\*.class
del Combined\Java\p1\*.class
del Combined\Java\p2\*.class
pause
4.102
The controlling class named Package00 is stored in the package named Combined.Java , as declared
in Listing 1 (p. 585) .
The class named Package01 is stored in the package named Combined.Java.p1 , as declared in
Listing 2 (p. 586) .
The class named Package02 is stored in the package named Combined.Java.p2 , as declared in
Listing 3 (p. 586) .
The controlling class named Package00 imports Combined.Java.p1.Package01 and Com-
bined.Java.p2.* , as declared in Listing 1 (p. 585) .
Code in the main method of the controlling class in Listing 1 (p. 585) instantiates objects of the
other two classes in dierent packages. The constructors for those two classes announce that they are being
constructed.
The two classes being instantiated are public . Otherwise, it would not be possible to instantiate them
from outside their respective packages.
This program was tested using JDK 7 under Windows by executing the batch le named CompileAn-
dRun.bat .
The classpath is set to the parent folder of the folder named Combined (M:\jnk\SampleCode) by
the -cp switch in the le named CompileAndRun.bat .
The output from running the program is shown in the comments at the beginning of Listing 1 (p. 585) .
4.35.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
111 http://cnx.org/content/m44148
112 http://cnx.org/content/m44153
113 This content is available online at <http://cnx.org/content/m45237/1.3/>.
4.36.2 Preface
This module discusses the String and StringBuer classes in detail.
4.36.2.1.1 Listings
• Listing 1 (p. 590) . File String01.java
• Listing 2 (p. 592) . File String02.java.
4.36.3 Introduction
A string in Java is an object. Java provides two dierent string classes from which objects that encapsulate
string data can be instantiated:
• String
• StringBuer
The String class is used for strings that are not allowed to change once an object has been instantiated
(an immutable object) . The StringBuer class is used for strings that may be modied by the program.
4.36.4 You can't modify a String object, but you can replace it
While the contents of a String object cannot be modied, a reference to a String object can be caused
to point to a dierent String object as illustrated in the sample program shown in Listing 1 (p. 590) .
Sometimes this makes it appear that the original String object is being modied.
**********************************************************/
class String01{
String str1 = "THIS STRING IS NAMED str1";
String str2 = "This string is named str2";
4.103
It is important to note that the following statement does not modify the original object pointed to by
the reference variable named str1 .
note:
Rather, this statement creates a new object, which is concatenation of two existing objects and causes the
reference variable named str1 to point to the new object instead of the original object.
The original object then becomes eligible for garbage collection (unless there is another reference to the
object hanging around somewhere) .
Many aspects of string manipulation can be accomplished in this manner, particularly when the methods
of the String class are brought into play.
note: "Because they are constants, Strings are typically cheaper than StringBuers and they can
be shared. So it's important to use Strings when they're appropriate."
114 http://cnx.org/content/m45117
**********************************************************/
class String02{
void d(String displayString){//method to display strings
System.out.println(displayString);
}//end method d()
o.d(str2 + "\n");
The rst approach uses the new operator to instantiate an object while the shorter version doesn't use
the new operator.
Later I will discuss the fact that
• the second approach is not simply a shorthand version of the rst construct, but that
• they involve two dierent compilation scenarios with the second construct being more ecient than
the rst.
//allowed
StringBuffer str3 = new StringBuffer(
"StringBuffer named str3");
//not allowed
//StringBuffer str4 = "StringBuffer named str4";
• declaration
• memory allocation
• initialization
StringBuffer str3 =
new StringBuffer("StringBuffer named str3");
The code
StringBuer str3
declares the type and name of a reference variable of the correct type for the benet of the compiler.
The new operator allocates memory for the new object.
The constructor call
StringBuer("StringBuer named str3")
constructs and initializes the object.
It is also possible to specify the capacity when you instantiate a StringBuer object.
Some authors suggest that if you know the nal length of such an object, it is more ecient to specify
that length when the object is instantiated than to start with the default length and then require the system
to increase the length "on the y" as you manipulate the object.
This is illustrated in the following code fragment. This fragment also illustrates the use of the length
method of the String class just to make things interesting. (A simple integer value for the capacity of
the StringBuer object would have worked just as well.)
note: "An object's instance variables are encapsulated within the object, hidden inside, safe
from inspection or manipulation by other objects. With certain well-dened exceptions, the ob-
ject's methods are the only means by which other objects can inspect or alter an object's instance
variables. Encapsulation of an object's data protects the object from corruption by other objects
and conceals an object's implementation details from outsiders. This encapsulation of data behind
an object's methods is one of the cornerstones of object-oriented programming."
The above statement lays out an important consideration in good object-oriented programming.
The methods used to obtain information about an object are often referred to as accessor methods .
note:
In this case, I applied thelength method to a literal string, but it can be applied to any valid representation
of an object of type String .
I then passed the value returned by the length method to the constructor for a StringBuer object.
As you can determine by examining the argument lists for the various methods of the String class,
• some methods return data stored in the string while
• other methods return information about that data.
For example, the length method returns information about the data stored in the String object.
Methods such as charAt and substring return portions of the actual data.
Methods such toUpperCase can be thought of as returning the data, but returning it in a dierent
format.
You can use literal strings anywhere you would use a String object.
You can also apply String methods directly to a literal string as in an earlier program (p. 592) that
calls the length method on a literal string as shown below.
Because the compiler automatically creates a new String object for every literal string, you can use a
literal string to initialize a String object (without use of the new operator) as in the following code
fragment from a previous program (p. 590) :
note:
The above construct is equivalent to, but more ecient than the following, which, according to The Java
Tutorial by Campione and Walrath, ends up creating two String objects instead of one:
116 http://cnx.org/content/m44190
note:
In this case, the compiler creates the rst String object when it encounters the literal string, and the
second one when it encounters new String() .
note:
According to Campione and Walrath, Java uses StringBuer objects behind the scenes to implement
concatenation. They indicate that the above code fragment compiles to:
note:
Fortunately, that takes place behind the scenes and we don't have to deal directly with the syntax.
117 http://cnx.org/content/m45222
118 http://cnx.org/content/m44148
119 http://cnx.org/content/m44153
4.36.14 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
· 1 (p. 599) , 2 (p. 599) , 3 (p. 599) , 4 (p. 599) , 5 (p. 599) , 6 (p. 600) , 7 (p. 600) , 8 (p. 600) ,
9 (p. 600) , 10 (p. 600) , 11 (p. 600) , 12 (p. 600) , 13 (p. 601) , 14 (p. 601)
4.37.2 Preface
This module contains review questions and answers keyed to the module titled Jb0280: Java OOP: String
and StringBuer
121 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
4.37.3 Questions
4.37.3.1 Question 1 .
Java provides two dierent string classes from which string objects can be instantiated. What are they?
Answer 1 (p. 607)
4.37.3.2 Question 2
True or false? The StringBuer class is used for strings that are not allowed to change. The String
class is used for strings that are modied by the program. If false, explain why.
Answer 2 (p. 607)
4.37.3.3 Question 3
True or false? While the contents of a String object cannot be modied, a reference to a String object
can be caused to point to a dierent String object. If false, explain why.
Answer 3 (p. 607)
4.37.3.4 Question 4
True or false? The use of the new operator is required for instantiation of objects of type String . If
false, explain your answer.
Answer 4 (p. 607)
4.37.3.5 Question 5
True or false? The use of the new operator is required for instantiation of objects of type StringBuer
. If false, explain your answer
Answer 5 (p. 606)
4.37.3.6 Question 6
Provide a code fragment that illustrates how to instantiate an empty StringBuer object of a default
length and then use a version of the append method to put some data into the object.
Answer 6 (p. 606)
4.37.3.7 Question 7
Without specifying any explicit numeric values, provide a code fragment that will instantiate an empty
StringBuer object of the correct initial length to contain the string "StringBuer named str6" and then
store that string in the object.
Answer 7 (p. 606)
4.37.3.8 Question 8
Provide a code fragment consisting of a single statement showing how to use the Integer wrapper class to
convert a string containing digits to an integer and store it in a variable of type int .
Answer 8 (p. 606)
4.37.3.9 Question 9
Explain the dierence between the capacity method and the length method of the StringBuer
class.
Answer 9 (p. 606)
4.37.3.10 Question 10
True or false? The following is a valid code fragment. If false, explain why.
note:
StringBuffer str6 =
new StringBuffer("StringBuffer named str6".length());
4.37.3.11 Question 11
Which of the following code fragments is the most ecient, rst or second?
note:
4.37.3.12 Question 12
Write a Java application that illustrates the fact that while a String object cannot be modied, the
reference variable can be modied to point to a new String object, which can have the appearance of
modifying the original String object.
Answer 12 (p. 605)
4.37.3.13 Question 13
Write a Java application that illustrates dierent ways to create String objects and StringBuer objects.
Answer 13 (p. 604)
4.37.3.14 Question 14
Write a Java application that illustrates conversion from string to numeric.
Answer 14 (p. 603)
4.37.4 Listings
• Listing 1 (p. 603) . File SampProg26.java.
• Listing 2 (p. 604) . File SampProg25.java.
• Listing 3 (p. 605) . File SampProg24.java.
This image was also inserted for the purpose of inserting space between the questions and the answers.
4.37.5 Answers
4.37.5.1 Answer 14
class SampProg26{
public static void main(String[] args){
int num = new Integer("3625").intValue();
System.out.println(
"The value of the int variable num is " + num);
}//end main()
}//end class SampProg26
4.105
4.37.5.2 Answer 13
class SampProg25{
void d(String displayString){//method to display strings
System.out.println(displayString);
}//end method d()
o.d(
"Create a String without using new and display it");
String str2 = "String named str1";
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
o.d(str2 + "\n");
4.37.5.3 Answer 12
class SampProg24{
String str1 = "THIS STRING IS NAMED str1";
String str2 = "This string is named str2";
4.107
4.37.5.4 Answer 11
The rst code fragment is the most ecient.
Back to Question 11 (p. 600)
4.37.5.5 Answer 10
True.
Back to Question 10 (p. 600)
4.37.5.6 Answer 9
The capacity method returns the amount of space currently allocated for the StringBuer object. The
length method returns the amount of space used.
Back to Question 9 (p. 600)
4.37.5.7 Answer 8
note:
4.37.5.8 Answer 7
note:
StringBuffer str6 =
new StringBuffer("StringBuffer named str6".length());
str6.append("StringBuffer named str6");
4.37.5.9 Answer 6
note:
StringBuffer str5 =
new StringBuffer();//accept default initial length
str5.append(
"StringBuffer named str5");//modify length as needed
4.37.5.10 Answer 5
True.
Back to Question 5 (p. 599)
4.37.5.11 Answer 4
False. A String object can be instantiated using either of the following statements:
note:
4.37.5.12 Answer 3
True.
Back to Question 3 (p. 599)
4.37.5.13 Answer 2
False. This statement is backwards. The String class is used for strings that are not allowed to change.
The StringBuer class is used for strings that are modied by the program.
Back to Question 2 (p. 599)
4.37.5.14 Answer 1
The two classes are:
• String
• StringBuer
4.37.6 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
4.38.2 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
122 This content is available online at <http://cnx.org/content/m45257/1.3/>.
123 http://cnx.org/content/m45179
124 http://cnx.org/content/m45252
125 http://cnx.org/content/m45222
126 http://cnx.org/content/m44148
127 http://cnx.org/content/m44153
5.1.2 Welcome
Welcome to the course material for ITSE 2321 - Object-Oriented Programming (Java) , which I
teach at Austin Community College
2 in Austin, TX.
The college website for this course is: http://www.austincc.edu/baldwin/
3
609
610 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
• You understand and can answer at least 80-percent of the questions in modules Ap0005
4 through
Ap0060
5 in the section titled OOP Self-Assessment 6 in a "closed-book" setting.
• You understand and can write at least 80-percent of the programs in the Challenge program questions
in modules Ap0005
7 through Ap0060 8 9
in the section titled OOP Self-Assessment in a "closed-book"
setting.
• You understand and can answer at least 80-percent of the questions posed on the Review pages in
the section titled Programming Fundamentals
10 in a "closed-book" setting
• Essence of OOP
4 http://cnx.org/content/m45252
5 http://cnx.org/content/m45264
6 http://cnx.org/content/m45252
7 http://cnx.org/content/m45252
8 http://cnx.org/content/m45264
9 http://cnx.org/content/m45252
10 http://cnx.org/content/m45179
11 http://cnx.org/content/m45284
12 http://cnx.org/content/m45264
13 http://cnx.org/content/m45252
14 http://cnx.org/content/m45252
15 http://cnx.org/content/m45264
16 http://cnx.org/content/m45252
17 http://cnx.org/content/m45179
• Multimedia
• Practice Tests
5.1.6.2 Multimedia
The modules in the Multimedia section are intended to illustrate OOP concepts using sample programs that
clearly represent real-world applications. In particular, most of the sample programs in this section use OOP
concepts to manipulate digital images of the sort that are produced by your digital camera. (See some
examples here 18 .)
5.1.8 Downloads
I encourage you to take advantage of all of the download options that cnx.org has to oer in order to
customize this material for use in your organized courses or for personal self study.
And if you nd the material useful, I would like to hear more about how you are using it.
5.1.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
18 http://cnx.org/content/m44148
-end-
5.2.1.2 Preface
This module is the rst in a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
Thus, this miniseries will describe and discuss the necessary and most signicant aspects of OOP using Java.
In other words, I will discuss the essence of OOP using Java. For the rst few modules, I will provide that
information in a high-level format, devoid of any requirement to understand detailed Java syntax. In those
cases where an understanding of Java syntax is required, I will provide the necessary syntax information in
the form of supplementary notes.
Therefore, if you have a general understanding of computer programming, you should be able to read
and understand the modules in this miniseries, even if you don't have a strong background in the Java
programming language.
5.2.1.2.2.1 Listings
• Listing 1 (p. 616) . Instantiating a new Radio object.
• Listing 2 (p. 618) . Calling the playStation method.
5.2.1.3 Preview
In order to understand OOP, you need to understand the following three concepts:
• Encapsulation
• Inheritance
• Polymorphism
This module will concentrate on encapsulation. Encapsulation will be used as a springboard for a discussion
of objects.
A description of an object-oriented program will be provided, along with a description of an object, and
how it relates to encapsulation.
In order to relate object-oriented programming to the real world, a car radio will be used to illustrate and
discuss several aspects of software objects. For example, you will learn that car radios, as well as software
objects, have the ability to store data, along with the ability to modify or manipulate that data.
You will learn that car radios, as well as software objects, have the ability to accept messages and to
perform an action, modify their state, return a value, or some combination of the above.
You will learn some of the jargon used in OOP, including persistence, state, messages, methods, and
behaviors.
You will learn where objects come from, and you will learn that a class is a set of plans that can be used
to construct objects. You will learn that a Java object is an instance of a class.
You will see a little bit of Java code, used to create an object, and then to send a message to that object
(invoke a method on the object).
You will learn about Java references and reference variables. You will also learn a little about memory
allocation for objects and variables in Java.
• Encapsulation
• Inheritance
• Polymorphism
When the radio beeps, I know that the new frequency value has been stored in a storage location that
corresponds to that particular button.
Please change your state
What I have done here is to send a message to the radio object asking it to change its state. The beep
that I hear could be interpreted as the radio object returning a value back to me indicating that the mission
has been accomplished. (Alternately, we might say that the radio object sent a message back to me.)
We say that an object has changed its state when one or more data values stored in the object have been
modied.
We also say that when an object responds to a message, it will usually perform an action, change its
state, return a value, or some combination of the above.
Please perform an action
Following this, when I press that button (send a message) , the radio object will be automatically tuned
to that frequency.
note: Historical note: While the ability to cause your car radio to remember your list
of favorite stations may seem like a miracle of modern digital electronics, the truth is that radios
had this capability long before they contained digital electronics. My rst car had a radio that
accomplished this feat using strings, pulleys, and levers.
As I recall, in order to set the frequency for a button, I had to manually tune the radio to a station
by turning a knob, pull one of the buttons out about a quarter of an inch, and then push it in again.
From that point until I did the same thing again, whenever I pressed that button, some kind of a
mechanical contraption caused a big rotary capacitor to turn just the right amount to tune for a
particular radio station.
Also, I remember my grandfather having a table-model radio in the early 1940's that had radio
buttons. He used them to select his favorite stations, as he surfed the airwaves.
(Interestingly, the term radio button has now become a part of programming jargon, signifying
certain visual components used in graphical user interfaces.)
note: Identical objects with identical states: It is perfectly OK for the two of us to own
identical radios and to cause the two radio objects to contain the same list of frequencies. Even
if two objects have the same state at the same time, they are still separate and distinct objects.
While this is obvious in the real world of car radios, it may not be quite as obvious in the virtual
world of computer programming.
Sending a message
A person who speaks in OOP-speak might say that pressing one of the frequency-selector buttons on the
front of the radio sends a message to the radio object, asking it to perform an action (tune to a particular
station) . That person might also say that storing a new frequency that corresponds to a particular button
entails sending a message to the radio object asking it to change its state.
Invoking or calling a method
Java-speak is a little more specic than general OOP-speak. In Java-speak, we might say that pressing
one of the selector buttons on the front of the radio invokes or calls a method on the radio object. The
behavior of the method is to cause the object to perform an action.
As a practical matter, the physical manifestation of sending a message to an object in Java is to cause
that object to execute one of its methods.
Similarly, we might say that storing a new frequency that corresponds to a particular button invokes a
setter method on the radio object.
(In an earlier paragraph, I said that I could follow a specic procedure to set the frequency value
associated with a button to correspond to one of the radio stations in Dallas. Note the use of the words set
and setter in this jargon.)
Behavior
In addition to state, objects are often also said to have behavior . The overall behavior of an object is
determined by the combined behaviors of its individual methods.
For example, one of the behaviors exhibited by our radio object is the ability to play the radio station
at a particular frequency. When a frequency is selected by pressing a selector button, the radio knows how
to translate the radio waves at that frequency into audio waves compatible with our range of hearing, and
to send those audio waves out through the speakers.
Thus, the radio object behaves in a specic way in response to a message asking it to tune to a particular
frequency.
Where do objects come from?
In order to mass-produce car radios, someone must rst create a set of plans, (drawings, or blueprints)
for the radio. Once the plans are available, the manufacturing people can produce millions of nearly identical
radios.
A class denition is a set of plans
The same is true for software objects. In order to create a software object in Java, it is necessary for
someone to rst create a plan.
In Java, we refer to that plan as a class .
(or
The class is dened by a Java programmer. Once the class denition is available, that programmer,
other programmers) , can use it to produce millions of nearly identical objects.
(While millions may sound like a lot of objects, I'm condent that since Java was released into the
programming world around 1997, Java programmers around the world have created millions of objects using
the standard Java class named Button .)
An instance of a class
If we were standing at the output end of the factory that produces car radios, we might pick up a
brand new radio and say that it is an instance of the plans used to produce the radio.(Unless they were
object-oriented programmers, the people around us might think we were a little odd when they hear us say
that.)
However, it is common jargon to refer to a software object as an instance of a class.
To instantiate an object
Furthermore, somewhere along the way, someone turned the word instance into a verb, and it is also
common jargon to say that when creating a new object, we are instantiating an object.
A little bit of code
It is time to view a little bit of Java code.
Assuming that you have access to a class denition, there are several dierent ways that you can create
an object in Java. The most common way is using syntax similar to that shown in Listing 1 (p. 616) below.
5.1
Technically, the expression on the right-hand side of the equal sign in Listing 1 (p. 616) applies the new
operator to a constructor for the class named Radio in order to cause the new object to come into being
and to occupy memory.
(Suce it at this point to say that a constructor is code that assists in the creation of an object according
to the plans contained in a class denition. The primary purpose of a constructor is to provide initial values
for the new object, but the constructor is not restricted to that behavior alone.)
A reference to the object
The right-hand expression in Listing 1 (p. 616) returns a reference to the new object.
What can you do with a reference?
The reference can later be used to send messages to the new object (call methods belonging to the new
object) .
Saving the reference
In order to use the reference later, it is necessary to save it for later use.
The expression on the left-hand side of the equal sign in Listing 1 (p. 616) declares a variable of the type
Radio named myObjRef .
(Because this type of variable will ultimately be used to store a reference to an object, we often refer to
it by the term reference variable .)
What does this mean?
Declaring a variable causes memory to be set aside for use by the variable. Values can then be stored in
that memory space and accessed later by calling up the name given to the variable when it was declared.
Assignment of values
The equal sign in Listing 1 (p. 616) causes the object's reference returned by the right-hand expression to
be assigned to, or saved as a value in, the reference variable named myObjRef (created by the left-hand
expression) .
Memory allocation
Once the code in Listing 1 (p. 616) has nished execution, two distinct and dierent chunks of memory
have been allocated and populated.
One (potentially large) chunk of memory has been allocated (by the right-hand expression) to contain
the object itself. This chunk of memory has been populated according to the plans contained in the denition
of the class named Radio .
The other chunk of memory is a relatively small chunk allocated (by the left-hand expression) for the
reference variable containing the reference to the object.
Calling a method on the object
Assume that the denition of the Radio class denes a method with the following format (also assume
that this method is intended to simulate pressing a frequency-selector button on the front of the radio) :
public void playStation(int stationNumber)
What does this mean?
Generally, in our radio-object context, this format implies that the behavior of the method named
playStation will cause the specic station identied by an integer value passed as stationNumber to
be selected for play.
Public and void
The void return type means that the method doesn't return a value.
The public modier means that the button can be pressed by anyone in the car who can reach it.
(Car radios don't have frequency-selector buttons corresponding to the private modier in Java.)
The method signature
Continuing with our exposure of jargon, some authors would say that the following constitutes the
method signature for the method identied above:
playStation(int stationNumber)
A little more Java code
Listing 2 (p. 618) shows the code from the earlier listing, expanded to cause the method named
playStation to be called.
myObjRef.playStation(3);
5.2
The rst statement in Listing 2 (p. 618) is a repeat of the statement from the earlier listing. It is repeated
here simply to maintain continuity.
Method invocation syntax
The second statement in Listing 2 (p. 618) is new.
This statement shows the syntax used to send a message to a Java object, or to call a method on that
object (depending on whether you prefer OOP-speak or Java-speak) .
Join the method name to the reference
The syntax required to call a method on a Java object joins the name of the method to the object's
reference, using a period as the joining operator.
(In this case, the object's reference is stored in the reference variable named myObjRef . However,
there are cases where an object's reference may be created and used in the same expression without storing
it in a reference variable. We often refer to such an object as an anonymous object.)
Pressing a radio button
Given the previous discussion, the numeric value 3, passed to the method when it is called, simulates
the pressing of the third button on the front of the radio (or the fourth button if you elect to number your
buttons 0, 1, 2, 3, 4, 5) .
5.2.1.5 Summary
This is the rst in a miniseries of modules that describe and discuss the necessary and most signicant
(essential) aspects of OOP using Java.
In order to understand OOP, you need to understand the following three concepts:
• Encapsulation
• Inheritance
• Polymorphism
This module has concentrated on encapsulation. Encapsulation was used as a springboard for a discussion
of objects.
A description of an object-oriented program was provided, along with a description of an object, and
how it relates to encapsulation.
In order to relate object-oriented programming to the real world, a car radio was used to illustrate and
discuss several aspects of software objects.
You learned that car radios, as well as software objects, have the ability to store data, along with the
ability to modify or manipulate that data.
You learned that car radios, as well as software objects, have the ability to accept messages and to
perform an action, modify their state, return a value, or some combination of the above.
You learned some of the jargon used in OOP, including persistence, state, messages, methods, and
behaviors.
You learned where objects come from, and you learned that a class is a set of plans that can be used to
construct objects. You learned that a Java object is an instance of a class.
You saw a little bit of Java code, used to create an object, and then to send a message to that object
(invoke a method on the object).
You learned about Java references and reference variables. You learned a little about memory allocation
for objects and variables in Java.
5.2.1.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
-end-
5.2.2.2 Preface
This module is the second in a collection of modules designed to teach you about the essence of Object-
Oriented Programming (OOP) using Java.
5.2.2.2.1.1 Images
• Image 1 (p. 623) . Screen output.
5.2.2.2.1.2 Listings
• Listing 1 (p. 621) . The class named Radio01.
• Listing 2 (p. 622) . Constructing a Radio object.
• Listing 3 (p. 622) . Programming the radio buttons.
• Listing 4 (p. 623) . Pressing a button on the radio.
• Listing 5 (p. 624) . The Radio class.
• Listing 6 (p. 625) . An instance variable.
• Listing 7 (p. 626) . The setStationNumber method.
• Listing 8 (p. 626) . The playStation method.
• Listing 9 (p. 630) . The program named Radio01.
5.2.2.3 Preview
This module will concentrate primarily on a discussion of the Java class.
A simple Java program will be discussed to illustrate the denition and use of two dierent classes. Taken
in combination, these two classes simulate the manufacture and use of the car radio object discussed in an
earlier module.
You will see how to write code to create a new Radio object by applying the new operator to the
class named Radio . You will also see how to save that object's reference in a reference variable of type
Radio .
You will see how to write code that is used to simulate the association of a radio button with a particular
radio station.
You will see how to write code that is used to simulate the pressing of a radio button to play the radio
station associated with that button.
You will see the denition of a class named Radio01 . This class consists simply of the main method.
The main method of a Java application is executed by the Java Virtual Machine when the application is
run. Thus, it is the driver for the entire application.
You will see the denition of a class named Radio . This class includes one instance variable and two
instance methods.
(The instance variable is a reference variable that refers to a special kind of object that I refer to as an
array object. I will provide a very brief discussion on array objects in this module. I will have more to say
about array objects in a subsequent module.)
I will provide a short discussion of class variables, which are not used in this program. I will explain that
the use of class variables can often lead to undesirable side eects.
Finally, I will provide a very brief discussion of the syntax of a simple class denition in Java.
5.3
The class named Radio01 consists simply of the main method. The main method of a Java
application is executed by the Java Virtual Machine when the application is run. Thus, it is the driver for
the entire application.
The driver class
The code in Listing 1 (p. 621) simulates the manufacturer of the radio and the use of the radio by the
end user. Without getting into a lot of detail regarding Java syntax, I will further subdivide and discuss this
code in the following listings.
Constructing a Radio object
As discussed in a previous module, the code in Listing 2 (p. 622) applies the new operator to the
constructor for the Radio class, causing a new object to be created according to the plans specied in the
class named Radio .
5.4
myObjRef.setStationNumber(3, 93.5);
5.5
The statement in Listing 3 (p. 622) accomplishes the association of a simulated button to a simulated
radio station by calling the method named setStationNumber on the reference to the Radio object.
(Recall that this sends a message to the object asking it to change its state.)
The parameters passed to the method cause radio button number 3 to be associated with the frequency
93.5 MHz. (The value 93.5 is stored in the variable that represents button number 3.)
Sending a message to the object
Using typical OOP jargon, the statement in Listing 3 (p. 622) sends a message to the Radio object,
asking it to change its state according to the values passed as parameters.
Pressing a button on the radio
Finally, the code in Listing 4 (p. 623) calls the method named playStation on the Radio object,
passing the integer value 3 (the button number) as a parameter.
myObjRef.playStation(3);
5.6
Another message
This code sends a message to the object asking it to perform an action. In this case, the action requested
by the message is:
5.7
class Radio{
//This class simulates the plans from
// which the radio object is created.
protected double[] stationNumber =
new double[5];
5.8
Note that the code in Listing 5 (p. 624) does not contain an explicit constructor. If you don't dene
a constructor when you dene a new class, a default version of the constructor is provided on your behalf.
That is the case for this simple program.
(Constructors will be explained in detail in subsequent modules.)
The plans for an object
The code in Listing 5 (p. 624) provides the plans from which one or more objects that simulate physical
radios can be constructed.
An object instantiated (an object is an instance of a class) from the code in Listing 5 (p. 624) simulates
a physical radio. I will subdivide this code into fragments and discuss it in the following listings.
An instance variable
In a previous module, I explained that we often say that an object is an instance of a class. (A physical
radio is one instance of the plans used to produce it.) The code in Listing 6 (p. 625) shows the declaration
and initialization of what is commonly referred to as an instance variable.
5.9
5.10
• An integer that corresponds to a button number (button numbers are assumed to begin with 0 and
extend through 4 in order to match array indexes)
• A frequency value to be associated with the indicated button.
5.11
• extracting the appropriate frequency value from the array object, and
• displaying that value on the computer screen along with some surrounding text.
When called by code in the main method of this program, this method produces the message shown in
Image 1 (p. 623) on the computer screen
That pretty-well summarizes the behavior of this simple program.
Class denition syntax
There are a number of items that can appear in a class denition, including the following:
• Instance variables
• Class variables
• Instance methods
• Class methods
• Constructors
• Static initializer blocks
• Inner classes
• Instance variables
• Instance methods
• Constructors
A constructor
A constructor is used only once in the lifetime of an object. It participates in the task of creating
(instantiating) and initializing the object. Following instantiation, the state and behavior of an object
depends entirely on instance variables, class variables, instance methods, and class methods.
Instance variables and methods
The class named Radio discussed earlier contains
5.2.2.5 Summary
This module has concentrated primarily on a discussion of the Java class.
A simple Java program was discussed to illustrate the denition and use of two dierent classes. Taken
in combination, these two classes simulate the manufacture and use of the car radio object introduced in an
earlier module.
You saw how to write code to create a new Radio object by applying the new operator to the class
named Radio .
You also saw how to save that object's reference in a reference variable of type Radio .
You saw how to write code (in an instance method named setStationNumber ) used to simulate
the association of a radio button with a particular radio station.
You saw how to write code (in an instance method named playStation ) to simulate the pressing of
a radio button to play the radio station associated with that button.
You saw the denition of the class named Radio01 , which consists simply of the main method. The
main method of a Java application is executed by the Java Virtual Machine when the application is run.
You saw the denition of the class named Radio . This class includes one instance variable and two
instance methods. (The instance variable is a reference variable that refers to a special kind of object that
I refer to as an array object. I provided a very brief discussion on array objects. I will have more to say on
this topic in a subsequent module.)
I provided a short discussion of class variables, which are not used in this program. I explained that the
use of class variables can often lead to undesirable side eects.
Finally, I provided a very brief discussion of the syntax of a simple class denition in Java.
• Encapsulation
• Inheritance
• Polymorphism
The next module will begin a discussion of inheritance. Overall, the discussion of inheritance will require
more than one module. In the next module, I will discuss how the denition of a class denes a new data
type. I will show you how to extend an existing class. I will explain what is inherited through inheritance.
I will discuss code reuse and explicit constructors.
Finally, I will illustrate all of the above in a simple program that extends the Radio class discussed in
this module into a new class named Combo that simulates an upgraded radio containing a tape player.
(Yes, at one point in history, car radios did contain tape players.)
5.2.2.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Radio01.java
Copyright 2001, R.G.Baldwin
Simulates manufacture and use of a
car radio.
class Radio{
//This class simulates the plans from
// which the radio object is created.
protected double[] stationNumber =
new double[5];
5.12
-end-
5.2.3.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.3.2.1.1 Images
• Image 1 (p. 638) . Program output.
5.2.3.2.1.2 Listings
• Listing 1 (p. 633) . Beginning of the Combo class.
• Listing 2 (p. 634) . The insertTape method.
• Listing 3 (p. 635) . The removeTape method.
• Listing 4 (p. 635) . The playTape method.
• Listing 5 (p. 636) . Modied Radio class.
• Listing 6 (p. 636) . Tape status.
• Listing 7 (p. 636) . Change to the playStation method.
• Listing 8 (p. 637) . The class named Radio02.
• Listing 9 (p. 640) . The program named Radio02.
5.2.3.3 Preview
Extending a class
This module shows you how to extend an existing class to create a new class. The new class is the
blueprint for a new type.
Inheritance and code reuse
The existing class is often called the superclass and the new class is often called the subclass . This
is the mechanism for class inheritance in Java. Inheritance provides a formal mechanism for code reuse.
The subclass inherits all of the variables and all of the methods dened in the superclass.
Car radios with tape players
A class from a previous module (whose objects represent car radios) is extended to dene a new class,
whose objects represent expanded car radios that contain tape players. (Yes, at one point in history, car
radios did contain tape players instead of CDs.)
Sending messages to the object
Objects of the new class know how to respond to messages for inserting, playing, and removing a tape,
in addition to those messages that are appropriate for objects of the original Radio class.
• Encapsulation
• Inheritance
• Polymorphism
Therefore, inheritance often makes it possible to dene a new class with a minimum requirement to write
new code by formally reusing the code that was previously written into the superclasses. Sometimes you can
get by with simply extending the existing class.
Sometimes, however, it is also necessary to make changes to the existing class to improve its ability to
be extended in a meaningful way. (That is the case with the sample program discussed in this module,
but the next module will show you how to avoid that issue.) It all depends on how the existing class was
designed in the rst place.
The Radio class
A previous program dened a class named Radio . Objects instantiated from the Radio class (see
the previous modules for a discussion of instantiating objects) were intended to simulate car radios. (Note
that the car radios simulated by objects of the Radio class didn't have built-in tape players.)
The Combo class
In this module, I will use inheritance to extend the Radio class into a new class named Combo .
Objects instantiated from the Combo class are intended to simulate car radios with a built-in tape player.
A complete listing of the new program is shown in Listing 9 (p. 640) near the end of the module.
Will discuss in fragments
As usual, I will discuss this program in fragments. I will begin my discussion with the denition of the
new class namedCombo . Then I will come back and discuss the class named Radio and the driver
class namedRadio02 .
The combo class
The code in Listing 1 (p. 633) shows the beginning of the class named Combo .
public Combo(){//constructor
System.out.println(
"Combo object constructed");
}//end constructor
5.13
The intended purpose of a constructor is to initialize the instance variables belonging to the new object.
However, constructors can do other things as well. In this case, I used an explicit constructor to display a
message when the object is instantiated from the class named Combo .
Brief discussion of constructors
I'm not going to discuss constructors in detail at this point. However, I will give you a few rules regarding
constructors.
• Constructors (like methods) can be overloaded. (I will explain what overloading means in a
subsequent module.)
• The names of constructors must match the names of the classes in which they are dened.
• A constructor signature never indicates a return type (such as void or double) .
• The code in a constructor never contains a return statement.
Instance methods
The new class named Combo denes three instance methods, each of which has to do with the handling
of tape in the tape player:
• insertTape
• removeTape
• playTape
(If you feel ambitious, you could upgrade this class even further to add features such as rewind, fast forward,
pause, etc.).
The insertTape method
insertTape
The entire method named is shown in Listing 2 (p. 634) . This is the method that is used
to simulate the insertion of a tape by the user.
5.14
The most signicant thing about the code in Listing 2 (p. 634) is the assignment of the true value to
the boolean variable named tapeIn . Other than setting the value of the tapeIn variable to true ,
the code in Listing 2 (p. 634) simply prints some messages to indicate what is going on.
What is tapeIn used for?
As you will see shortly, the value of the variable named tapeIn is used to determine if it is possible to
play the tape or to play the radio.
According to that logic:
• If tapeIn is true, it is possible to play the tape but it is not possible to play the radio.
• If tapeIn is false, it is possible to play the radio, but it is not possible to play the tape.
5.15
5.16
class Radio{
protected double[] stationNumber =
new double[5];
protected boolean tapeIn = false
5.17
Tape status
The rst signicant change that was made to the class named Radio is shown in Listing 6 (p. 636)
below.
5.18
The statement in Listing 6 (p. 636) declares and initializes a new instance variable named tapeIn . As
explained earlier, this instance variable is used to indicate whether or not a tape is inserted. (The Combo
class inherits this variable.)
Earlier in this module, I explained how the playTape method of the Combo class uses this value to
determine whether or not to attempt to play a tape.
Change to the playStation method
The signicant change that was made to the method named playStation of the Radio class is shown
in Listing 7 (p. 636) below.
if(!tapeIn){//tapeIn is false
System.out.println(
" Playing the station at "
+ stationNumber[index]
+ " Mhz");
}else{//tapeIn is true
System.out.println(
" Remove the tape first")
5.19
5.20
5.21
5.2.3.5 Summary
Extending an existing class often provides an easy way to create a new type. This is primarily true when an
existing class creates a type whose features are close to, but not identical to the features needed in the new
type.
When an existing class is extended to dene a new class, the existing class is often called the superclass
and the new class is often called the subclass.
The subclass inherits all of the variables and all of the methods dened in the superclass and its super-
classes.
Inheritance provides a formal mechanism for code reuse.
This module modies slightly, and then extends the Radio class from a previous module to dene a
new class named Combo . Objects of the Combo class simulate car radios that contain tape players.
Objects of the Combo class know how to respond to messages for inserting, playing, and removing a tape,
in addition to those messages appropriate for an object of the Radio class.
The changes that were required in the denition of the Radio class provide for the fact that it is not
possible to play a radio station and to play a tape at the same time. This change was necessary because the
original designer of the Radio class (this author) didn't design that class with the idea of extending it
to include a tape player. This points out the importance of thinking ahead when dening a new class.
5.2.3.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Radio02.java
Copyright 2002, R.G.Baldwin
Simulates the manufacture and use of a
combination car radio and tape player.
myObjRef.removeTape();
myObjRef.playStation(3);
}//end main
641
-end-
5.2.4.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.4.2.1.1 Images
• Image 1 (p. 646) . Program output.
5.2.4.2.1.2 Listings
• Listing 1 (p. 643) . The class named Radio.
• Listing 2 (p. 644) . Beginning of the Combo class.
• Listing 3 (p. 644) . The overridden playStation method.
• Listing 4 (p. 645) . The driver class.
• Listing 5 (p. 648) . The program named Radio03.
5.2.4.3 Preview
This module builds on the previous module. It is recommended that you study that module before embarking
on this module.
The program discussed in this module extends a Radio class to produce a new class that simulates an
upgraded car radio containing a tape player.
Method overriding is used to modify the behavior of a method of the Radio class named playStation
, to cause that method to behave appropriately when a tape has been inserted into the tape player.
(The behavior of the version of playStation dened in the Radio class is not appropriate for an
object of the Combo class. Therefore, the method was overridden in the Combo class to cause its
behavior to be appropriate for objects instantiated from the Combo class.)
A complete listing of the program is shown in Listing 5 near the end of this module.
The class named Radio
As usual, I will discuss the program in fragments.
Listing 1 (p. 643) shows the superclass named Radio . This code is shown here for easy referral. It
is identical to the code for the same class used in the program named Radio01 discussed in an earlier
module.
class Radio{
protected double[] stationNumber =
new double[5];
5.23
5.24
5.25
Depending on the value of the variable named tapeIn , this method will either
The code in these three methods is identical to the code in the methods having the same names in the
program named Radio02 in the previous module. I discussed that code in the previous module and won't
repeat that discussion here. You can view those methods in the complete listing of the program shown in
Listing 5 (p. 648) near the end of this module.
The driver class
Listing 4 (p. 645) shows the code for the driver class named Radio03.
5.26
The code in Listing 4 (p. 645) is also identical to the code in the program named Radio02 discussed
in the previous module. Therefore, I won't discuss it in detail here.
A new object of the Combo class
I present this code here solely to emphasize that this code instantiates a new object of the Combo
class. This assures that the overridden version of the method named playStation will be executed by the
statements in Listing 4 (p. 645) that call the playStation method.
(Although it is not the case in Listing 4 (p. 645) , even if the reference to the object of type Combo
had been stored in a reference variable of type Radio , instead of a reference variable of type Combo ,
calling the playStation method on that reference would have caused the overridden version of the method
to have been executed. That is the essence of runtime polymorphism based on overridden methods in Java.)
Program output
This program produces the output shown in Image 1 (p. 646) on the computer screen.
5.27
I will leave it as an exercise for the student to compare this output with the messages sent to the object
by the code in Listing 4 (p. 645) .
5.2.4.5 Summary
An object instantiated from a class that extends another class will contain all of the methods and all of the
variables dened in the subclass, plus all of the methods and all of the variables inherited into the subclass.
The behavior of methods inherited into the subclass may not be appropriate for an object instantiated
from the subclass. You can change that behavior by overriding the method in the denition of the subclass.
To override a method in the subclass, reproduce the name, argument list, and return type of the original
method in a new method denition in the subclass. Make sure that the overridden method is not less
accessible than the original method. Also, make sure that it doesn't throw any checked exceptions that were
not declared for the original method.
Provide a body for the overridden method, causing the behavior of the overridden method to be appro-
priate for an object of the subclass. Any method that is not declared nal can be overridden in a subclass.
The program discussed in this module extends a Radio class to produce a subclass that simulates an
upgraded car radio containing a tape player.
Method overriding is used to modify the behavior of an inherited method named playStation to cause
that method to behave appropriately when a tape has been inserted into the radio.
Method overriding is dierent from method overloading. Method overloading will be discussed in the
next module.
5.2.4.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
myObjRef.removeTape();
myObjRef.playStation(3);
}//end main
649
-end-
5.2.5.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.5.2.1.1 Listings
• Listing 1 (p. 652) . Denition of the class named A.
• Listing 2 (p. 653) . Denition of the class named B.
• Listing 3 (p. 653) . Denition of the driver class named Poly01.
• Listing 4 (p. 656) . Complete program listing.
5.2.5.3 Preview
Previous modules introduced overloading and overriding methods. This module concentrates on the use
of method overloading to achieve compile-time polymorphism .
Every class in Java is a direct or indirect subclass of the class named Object . Methods dened in the
class named Object are inherited into all other classes. Inherited methods that are not declared nal
may be overridden to make their behavior more appropriate to objects instantiated from the new class.
Overloaded methods have the same name and dierent formal argument lists. They may or may not
have the same return type.
Polymorphism manifests itself in Java in the form of multiple methods having the same name. This mod-
ule concentrates on method overloading, sometimes referred to as compile-time polymorphism . Subsequent
modules concentrate on method overriding, sometimes referred to as runtime polymorphism .
Overloaded methods may all be dened in the same class, or may be dened in dierent classes as long
as those classes have a superclass-subclass relationship.
• Encapsulation
• Inheritance
• Polymorphism
I couched those programs in a real-world scenario in an attempt to convince you that encapsulation and
inheritance really do have a place in the real world.
Programs were fairly long
However, even though those programs were simple in concept, they were relatively long. That made them
somewhat dicult to explain due simply to the amount of code involved.
Keep it short and simple
Beginning with this module, I am going to back away from real-world scenarios and begin using sample
programs that are as short and as simple as I know how to make them, while still illustrating the important
points under discussion.
My objective in this and future modules is to make the polymorphic concepts as clear as possible without
having those concepts clouded by other programming issues.
I will simply ask you to trust me when I tell you that polymorphism has enormous applicability in the
real world.
A little more on inheritance
There is another aspect of inheritance that I didn't explain in the previous modules.
Every class extends some other class
Every class in Java extends some other class. If you don't explicitly specify the class that your new class
extends, it will automatically extend the class named Object .
A class hierarchy
Thus, all classes in Java exist in a class hierarchy where the class named Object forms the root of the
hierarchy.
Some classes extend Object directly, while other classes are subclasses of Object further down the
hierarchy.
Methods in the Object class
Object denes default versions of the following methods:
The class named
• clone()
• equals(Object obj)
• nalize()
• getClass()
• hashCode()
• notify()
• notifyAll()
• toString()
• wait()
• wait(long timeout)
• wait(long timeout, int nanos)
As you can see, this list includes three overloaded versions of the method named wait . The three versions
have the same name but dierent formal argument lists. Thus, these three methods are overloaded versions
of the method name wait .
Every class inherits these eleven methods
Because every class is either a direct or indirect subclass of Object , every class in Java, (including
new classes that you dene) , inherit these eleven methods.
To be overridden ...
Some of these eleven methods are intended to be overridden for various purposes. However, some of
them, such as getClass , notify , and the three versions of wait , are intended to be used directly
without overriding. (Although not shown here, these ve methods are declared to be nal , meaning that
they may not be overridden.)
What is polymorphism?
The meaning of the word polymorphism is something like one name, many forms.
How does Java implement polymorphism?
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but dierent formal argument lists (overloaded
methods) . In other cases, multiple methods have the same name, same return type, and same formal
argument list (overridden methods) .
Three distinct forms of polymorphism
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
Method overloading
I will begin the discussion of polymorphism with method overloading, which is the simplest of the three.
I will cover method overloading in this module and will cover polymorphism based on overridden methods
and interfaces in subsequent modules.
Method overloading versus method overriding
Don't confuse method overloading with method overriding .
Java allows you to have two or more method denitions in the same scope with the same name, provided
that they have dierent formal argument lists.
More specically, here is what Roberts, Heller, and Ernest have to say about overloading methods in
their excellent book titled The Complete Java 2 Certication Study Guide :
"A valid overload diers in the number or type of its arguments. Dierences in argument names are not
signicant. A dierent return type is permitted, but is not sucient by itself to distinguish an overloading
method."
Similarly, as a preview of things to come, here is what they have to say about method overriding:
"A valid override has identical argument types and order, identical return type, and is not less accessible
than the original method. The overriding method must not throw any checked exceptions that were not
declared for the original method."
You should read these two descriptions carefully and make certain that you recognize the dierences.
Compile-time polymorphism
Some authors refer to method overloading as a form of compile-time polymorphism , as distinguished
from run-time polymorphism .
This distinction comes from the fact that, for each method call, the compiler determines which method
(from a group of overloaded methods) will be executed, and this decision is made when the program is
compiled. (In contrast, I will tell you later that the determination of which overridden method to execute
isn't made until runtime.)
Selection based on the argument list
In practice, the compiler simply examines the types, number, and order of the parameters being passed
in a method call, and selects the overloaded method having a matching formal argument list.
A sample program
I will discuss a sample program named Poly01 to illustrate method overloading. A complete listing of
the program can be viewed in Listing 4 (p. 656) near the end of the module.
Within the class and the hierarchy
Method overloading can occur both within a class denition, and vertically within the class inheritance
hierarchy. (In other words, an overloaded method can be inherited into a class that denes other overloaded
versions of the method.) The program named Poly01 illustrates both aspects of method overloading.
Class B extends class A, which extends Object
Upon examination of the program, you will see that the class named A extends the class named
Object . You will also see that the class named B extends the class named A .
The class named Poly01 is a driver class whose main method exercises the methods dened in the
classes named A and B .
Once again, this program is not intended to correspond to any particular real-world scenario. Rather, it
is a very simple program designed specically to illustrate method overloading.
Will discuss in fragments
As is my usual approach, I will discuss this program in fragments. The code in Listing 1 (p. 652) denes
the class named A , which explicitly extends Object .
5.29
Redundant code
Explicitly extending Object is not required (but it also doesn't hurt anything to do it) .
By default, the class named A would extend the class named Object automatically, unless the class
named A explicitly extends some other class.
The method named m()
The code in Listing 1 (p. 652) denes a method named m() . Note that this version of the method
has an empty argument list (it doesn't receive any parameters when it is executed) . The behavior of the
method is simply to display a message indicating that it has been called.
The class named B
Listing 2 (p. 653) contains the denition for the class named B . The class named B extends the
class named A , and inherits the method named m dened in the class named A .
class B extends A{
public void m(int x){
System.out.println("m(int x)");
}//end method m(int x)
//---------------------------------//
5.30
Overloaded methods
In addition to the inherited method named m , the class named B denes two overloaded versions of
the method named m :
• m(int x)
• m(String y)
(Note that each of these two versions of the method receives a single parameter, and the type of the
parameter is dierent in each case.)
As with the version of the method having the same name dened in the class named A , the behavior
of each of these two methods is to display a message indicating that it has been called.
The driver class
Listing 3 (p. 653) contains the denition of the driver class named Poly01 .
5.31
m()
m(int x)
m(String y)
Note that the values of the parameters passed to the methods do not appear in the output. Rather, in this
simple example, the parameters are used solely to make it possible for the compiler to select the correct
version of the overloaded method to execute.
This output conrms that each overloaded version of the method is properly selected for execution based
on the matching of method parameters to the formal argument list of each method.
5.2.5.5 Summary
Previous modules introduced overloading and overriding methods. This module concentrates on the use
of method overloading to achieve compile-time polymorphism .
All classes in Java form a hierarchy with a class named Object at the root of the hierarchy. Thus,
every class in Java is a direct or indirect subclass of the class named Object .
If a new class doesn't explicitly extend some other class, it will, by default, automatically extend the
class named Object .
The Object class denes default versions of eleven dierent methods. These methods are inherited
into all other classes, and some (those not declared nal ) may be overridden to make their behavior
more appropriate for objects instantiated from the new class.
Overloaded methods have the same name and dierent formal argument lists. They may or may not
have the same return type.
Three of the eleven methods dened in the class named Object are overloaded versions of the method
name wait . One version takes no parameters. A second version takes a single parameter of type long .
The third version takes two parameters, one of type long , and one of type int .
The word polymorphism means something like one name, many forms . Polymorphism manifests itself
in Java in the form of multiple methods having the same name.
Polymorphism manifests itself in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
5.2.5.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly01.java
Copyright 2002, R.G.Baldwin
class B extends A{
public void m(int x){
System.out.println("m(int x)");
}//end method m(int x)
//---------------------------------//
5.32
-end-
5.2.6.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.6.2.1.1 Listings
• Listing 1 (p. 660) . Denition of the class named A.
• Listing 2 (p. 660) . Denition of the class named B.
• Listing 3 (p. 661) . Denition of the class named C.
• Listing 4 (p. 661) . Beginning of the class named Poly02.
• Listing 5 (p. 662) . An illegal operation.
• Listing 6 (p. 662) . An ineective downcast.
• Listing 7 (p. 663) . A downcast to type B.
• Listing 8 (p. 663) . Declare a variable of type B.
• Listing 9 (p. 663) . Cannot be assigned to type C.
• Listing 10 (p. 664) . Another failed attempt.
• Listing 11 (p. 666) . Complete program listing.
5.2.6.3 Preview
This module discusses type conversion for both primitive and reference types.
A value of a particular type may be assignment compatible with variables of other types, in which case
the value can be assigned directly to the variable. Otherwise, it may be possible to perform a cast on the
value to change its type and assign it to the variable as the new type.
With regard to reference types, whether or not a cast can be successfully performed
A reference to any object can be assigned to a reference variable of the type Object , because the Object
class is a superclass of every other class.
When we cast a reference along the class hierarchy in a direction from the root class Object toward
the leaves, we often refer to it as a downcast .
Whether or not a method can be called on a reference to an object depends on
In order to use a reference of a class type to call a method, the method must be dened at or above that
class in the class hierarchy.
A sample program is provided that illustrates much of the detail involved in type conversion, method
calls, and casting with respect to reference types.
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
(int)
In that case, the type of the value is automatically converted to the type of the variable.
(For example, types byte and short can be assigned to a variable of type int without
the requirement for a cast because type int has a wider range than either type byte or type
short .)
Conversion to narrower range
On the other hand, a primitive value of a given type cannot be assigned to a variable of a type with a
narrower range than the type of the value,
Oftentimes, such a conversion will result in the loss of data, and that loss is the responsibility of the
programmer who performs the cast.
Assignment compatibility for references
Assignment compatibility, with respect to references, doesn't involve range issues, as is the case with
primitives. Instead, the reference to an object instantiated from a given class can be assigned to:
• Any reference variable whose type is the same as the class from which the object was instantiated.
• Any reference variable whose type is a superclass of the class from which the object was instantiated.
• Any reference variable whose type is an interface that is implemented by the class from which the
object was instantiated.
• Any reference variable whose type is an interface that is implemented by a superclass of the class from
which the object was instantiated, and
• A few other cases involving the class and interface hierarchy.
When we cast a reference along the class hierarchy in a direction from the root class Object toward
the leaves, we often refer to it as a downcast .
While it is also possible to cast in the direction from the leaves to the root, this happens automatically,
and the use of a cast operator is not required.
A sample program
Poly02
The program named , shown in Listing 11 (p. 666) near the end of the module, illustrates the
use of the cast operator with references.
When you examine that program, you will see that two classes named A and C each extend the class
named Object . Hence, we might say that they are siblings in the class hierarchy.
Another class named B extends the class named A . Thus, we might say that A is a child of
Object , and B is a child of A .
The class named A
The denition of the class named A is shown in Listing 1 (p. 660) . This class extends the class named
Object .
(Recall that it is not necessary to explicitly state that a class extends the class named Object . Any
class that does not explicitly extend some other class will automatically extend Object by default. The
class named A is shown to extend Object here simply for clarity of presentation.)
5.33
The class named A is empty. It was included in this example for the sole purpose of adding a layer of
inheritance to the class hierarchy.
The class named B
Listing 2 (p. 660) shows the denition of the class named B . This class extends the class named A .
class B extends A{
public void m(){
System.out.println("m in class B");
}//end method m()
}//end class B
5.34
5.35
The class named C is also empty. It was included in this example as a sibling class for the class named
A . Stated dierently, it was included as a class that is not in the ancestral line of the class named B .
The driver class
Listing 4 (p. 661) shows the beginning of the driver class named Poly02 .
5.36
//var.m();
5.37
An attempt to call the method named m() on the reference variable of type Object in Listing 5 (p.
662) resulted in a compiler error. It was necessary to convert the statement into a comment in order to get
the program to compile successfully.
An important rule
In order to use a reference of a class type to call a method, the method must be dened at or above that
class in the class hierarchy.
This case violates the rule
In this case, the method named m() is dened in the class named B , which is two levels down from
the class named Object .
When the reference to the object of the class B was assigned to the reference variable of type Object
, the type of the reference was automatically converted to type Object .
Therefore, because the reference is of type Object , it cannot be used directly to call the method
named m() .
The solution is a downcast
In this case, the solution to the problem is a downcast. The code in Listing 6 (p. 662) shows an attempt
to solve the problem by casting the reference down the hierarchy to type A .
//((A)var).m();
5.38
((B)var).m();
5.39
The code in Listing 7 (p. 663) casts (converts) the reference value contained in the Object variable
named var down to type B .
The method named m() is dened in the class named B . Therefore, a reference of type B can be
used to call the method.
The code in Listing 7 (p. 663) compiles and executes successfully. This causes the method named m()
to execute, producing the following output on the computer screen.
m in class B
A few odds and ends
Before leaving this topic, let's look at a couple more issues. The code in Listing 8 (p. 663) declares and
populates a new variable of type B .
B v1 = (B)var;
5.40
//C v2 = (C)var;
5.41
The code in Listing 9 (p. 663) attempts to cast the reference to type C and assign it to a reference
variable of typeC .
A runtime error
Although the program will compile, it won't execute. An attempt to execute the statement in Listing
9 (p. 663) results in a ClassCastException at runtime. As a result, it was necessary to convert the
statement into a comment in order to execute the program.
Another failed attempt
Similarly, an attempt to cast the reference to type B and assign it to a reference variable of type C ,
as shown in Listing 10 (p. 664) , won't compile.
//C v3 = (B)var;
5.42
The problem here is that the class C is not a superclass of the class named B . Therefore, a reference
of type B is not assignment compatible with a reference variable of type C .
Again, it was necessary to convert the statement into a comment in order to compile the program.
5.2.6.5 Summary
This module discusses type conversion for both primitive and reference types.
A value of a particular type may be assignment compatible with variables of other types.
If the type of a value is not assignment compatible with a variable of a given type, it may be possible to
perform a cast on the value to change its type and assign it to the variable as the new type. For primitive
types, this will often result in the loss of information.
Except for type boolean , values of primitive types can be assigned to any variable whose type represents
a range that is as wide or wider than the range of the value's type. (Values of type boolean can only
be assigned to variables of type boolean.)
With respect to reference types, the reference to an object instantiated from a given class can be assigned
to any of the following without the use of a cast:
• Any reference variable whose type is the same as the class from which the object was instantiated.
• Any reference variable whose type is a superclass of the class from which the object was instantiated.
• Any reference variable whose type is an interface that is implemented by the class from which the
object was instantiated.
• Any reference variable whose type is an interface that is implemented by a superclass of the class from
which the object was instantiated.
• A few other cases involving the class and interface hierarchy.
Assignments of references, other than those listed above, require the use of a cast to change the type of the
reference.
It is not always possible to perform a successful cast to convert the type of a reference. Whether or not a
cast can be successfully performed depends on the relationship of the classes involved in the class hierarchy.
A reference to any object can be assigned to a reference variable of the type Object , because the
Object class is a superclass of every other class.
When we cast a reference along the class hierarchy in a direction from the root class Object toward
the leaves, we often refer to it as a downcast.
Whether or not a method can be called on a reference to an object depends on the current type of the
reference and the location in the class hierarchy where the method is dened. In order to use a reference of
a class type to call a method, the method must be dened at or above that class in the class hierarchy.
A sample program is provided that illustrates much of the detail involved in type conversion, method
invocation, and casting with respect to reference types.
5.2.6.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly02.java
Copyright 2002, R.G.Baldwin
m in class B
**************************************/
class B extends A{
public void m(){
System.out.println("m in class B");
}//end method m()
}//end class B
//===================================//
5.43
-end-
5.2.7.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.7.2.1.1 Listings
• Listing 1 (p. 669) . Denition of the class named A.
• Listing 2 (p. 670) . Denition of the class named B.
• Listing 3 (p. 670) . Beginning of the driver class named Poly03.
• Listing 4 (p. 671) . Polymorphic behavior.
• Listing 5 (p. 672) . Source of a compiler error.
• Listing 6 (p. 672) . A new object of type A.
• Listing 7 (p. 675) . Complete program listing.
5.2.7.3 Preview
What is polymorphism?
The meaning of the word polymorphism is something like one name, many forms .
How does Java implement polymorphism?
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but dierent formal argument lists (overloaded
methods, which were discussed in a previous module) .
In other cases, multiple methods have the same name, same return type, and same formal argument list
(overridden methods) .
Three distinct forms of polymorphism
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
• Method overloading
Late binding
The decision as to which version of the method to call cannot be made at compile time. That decision
must be deferred and made at runtime. This is sometimes referred to as late binding .
· ref.method()
• Result: The version of the method named method that will actually be executed is the
overridden version in the class named SubClass , and is not the version that is dened in the class
named SuperClass, even though the reference to the object of type SubClass is stored in a
variable of typeSuperClass .
This is runtime polymorphism in a nutshell, which is sometimes also referred to as late-binding.
Runtime polymorphism is very powerful
As you gain more experience with Java, you will learn that much of the power of OOP using Java is
centered on runtime polymorphism using class inheritance, interfaces, and method overriding. (The use of
interfaces for polymorphism will be discussed in a future module.)
An important attribute of runtime polymorphism
The decision as to which version of the method to execute
• is based on the actual type of object whose reference is stored in the reference variable, and
• not on the type of the reference variable on which the method is called.
The reason that this type of polymorphism is often referred to as runtime polymorphism is because the
decision as to which version of the method to execute cannot be made until runtime. The decision cannot
be made at compile time.
Why defer the decision?
The decision cannot be made at compile time because the compiler has no way of knowing (when the
program is compiled) the actual type of the object whose reference will be stored in the reference variable .
In an extreme case, for example, the object might be de-serialized at runtime from a network connection
of which the compiler has no knowledge.
Could be either type
For the situation described above, that de-serialized object could just as easily be of type SuperClass
as of type SubClass . In either case, it would be valid to assign the object's reference to the same
superclass reference variable.
If the object were of the SuperClass type, then a call to the method named method on the reference
would cause the version of the method dened in SuperClass , and not the version dened in SubClass
, to be executed. (The version executed is determined by the type of the object and not by the type of the
reference variable containing the reference to the object.)
Sample Program
Let's take a look at a sample program that illustrates runtime polymorphism using class inheritance and
overridden methods. The name of the program is Poly03 . A complete listing of the program is shown in
Listing 7 (p. 675) near the end of the module.
Listing 1 (p. 669) shows the denition of a class named A , which extends the class named Object .
(Remember that any class that doesn't extend some other class automatically extends Object by
default, and it is not necessary to show that explicitly as I did in this example.)
5.44
class B extends A{
public void m(){
System.out.println("m in class B");
}//end method m()
}//end class B
5.45
The class namedB overrides (redenes) the method named m() , which it inherits from the class
named A .
Behavior of the overridden version of the method
Like the inherited version, the overridden version displays a message indicating that it has been called.
However, the message is dierent from the message displayed by the inherited version discussed above. The
overridden version tells us that it is dened in the class named B . (The behavior of the overridden version
of the method is appropriate for an object instantiated from the class named B .)
Again, this message will allow us to determine which version of the method is executed in each case
discussed later.
The driver class
Listing 3 (p. 670) shows the beginning of the driver class named Poly03 .
5.46
m in class B
By examining the output, you can conrm that the version of the method that was overridden in the class
named B is the version that was executed.
Why was this version executed?
This should also come as no surprise to you. The cast converts the type of the reference from type
Object to type B .
You can always call a public method belonging to an object using a reference to the object whose type
is the same as the class from which the object was instantiated.
Not runtime polymorphic behavior
Just for the record, the above call to the method does not constitute runtime polymorphism (in my
opinion) . I included that call to the method to serve as a backdrop for what follows.
Runtime polymorphic behavior
However, the following call to the method does constitute runtime polymorphism.
The statement in Listing 4 (p. 671) casts the reference down to type A and calls the method named
m() on that reference.
It may not come as a surprise to you that the call to the method shown in Listing 4 (p. 671) also compiles
and runs successfully.
((A)var).m();
5.47
m in class B
Same method executed in both cases
It is important to note that this output, (produced by casting the reference variable to type A instead
of type B ) , is exactly the same as that produced by the earlier call to the method when the reference
was cast to type B . This means that the same version of the method was executed in both cases.
This conrms that, even though the type of the reference was converted to type A , (rather than type
Object or type B ) , the overridden version of the method dened in class B was actually executed.
This is an example of runtime polymorphic behavior.
The version of the method that was executed was based on
var.m();
5.48
Compiler error
The code in Listing 5 (p. 672) attempts, unsuccessfully, to call the method named m() using the
reference variable named var , which is of type Object . The result is a compiler error, which, depending
on your version of the JDK, will be similar to the following:
5.49
The code in Listing 6 (p. 672) instantiates a new object of the class named A , and stores the object's
reference in the original reference variable named var of type Object .
(As a side note, this overwrites the previous contents of the reference variable with a new reference and
causes the object whose reference was previously stored there to become eligible for garbage collection.)
Downcast and call the method
Then the code in Listing 6 (p. 672) casts the reference down to type A , (the type of the object to
which the reference refers) , and calls the method named m() on the downcast reference.
The output
As you would probably predict, this produces the following output on the computer screen:
m in class A
In this case, the version of the method dened in the class named A , (not the version dened in B )
was executed.
Not polymorphic behavior
In my view, this is not polymorphic behavior (at least it isn't a very useful form of polymorphic behavior)
. This code simply converts the type of the reference from type Object to the type of the class from which
the object was instantiated, and calls one of its methods. Nothing special takes place regarding a selection
among dierent versions of the method.
Some authors may disagree
While some authors might argue that this is technically runtime polymorphic behavior, in my view at
least, it does not illustrate the real benets of runtime polymorphic behavior. The benets of runtime
polymorphic behavior generally accrue when the actual type of the object is a subclass of the type of the
reference variable containing the reference to the object.
Once again, what is runtime polymorphism?
As I have discussed in this module, runtime polymorphic behavior based on class inheritance occurs when
• The type of the reference is a superclass of the class from which the object was instantiated.
• The version of the method that is executed is the version that is either dened in, or inherited into,
the class from which the object was instantiated.
5.2.7.5 Summary
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
• Method overloading
• Method overriding through class inheritance
• Method overriding through the Java interface
The decision as to which version of the method to call cannot be made at compile time. That decision
must be deferred and made at runtime. This is sometimes referred to as late binding.
This is illustrated in the sample program discussed in this module.
5.2.7.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly03.java
Copyright 2002, R.G.Baldwin
m in class B
m in class B
m in class A
**************************************/
class B extends A{
public void m(){
System.out.println("m in class B");
}//end method m()
}//end class B
//===================================//
5.50
-end-
5.2.8.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.8.2.1.1 Listings
• Listing 1 (p. 678) . Denition of the class named A.
• Listing 2 (p. 679) . Denition of the class named B.
• Listing 3 (p. 680) . Denition of the class named C.
• Listing 4 (p. 680) . Beginning of the class named Poly04.
• Listing 5 (p. 681) . A new object of the class named B.
• Listing 6 (p. 682) . A new object of the class named C.
• Listing 7 (p. 684) . Complete program listing.
5.2.8.3 Preview
What is polymorphism?
If you have studied the earlier modules in this collection, you should already know what polymorphism
is, how it is implemented in Java, the three distinct forms of polymorphism in Java, etc.
I discussed runtime polymorphism implemented through method overriding and class inheritance in a
previous module. However, before leaving that topic, I need to discuss an important special case.
In this module, I will discuss the use of the Object class as a completely generic type for storing
references to objects of subclass types, and will explain how that results in a very useful form of runtime
polymorphism.
I will briey discuss the default versions of eleven methods dened in the Object class, and will explain
that in many cases, those default versions are meant to be overridden.
• clone()
• equals(Object obj)
• nalize()
• getClass()
• hashCode()
• notify()
• notifyAll()
• toString()
• wait()
• wait(long timeout)
• wait(long timeout, int nanos)
Given the above, you should know that you can call any of the methods dened in the Object class on
any reference to any object stored in a reference variable of type Object (including the references stored
in the concrete implementations of the Java Collections Framework) .
And the behavior will be ...
If the class from which that object is instantiated inherits or denes an overridden version of one of
the methods in the above list, calling that method on the reference will cause the overridden version to be
executed.
Otherwise, calling that method on the reference will cause the default version dened in the Object
class to be executed.
A sample program
This is illustrated in the program named Poly04 , which you can view in its entirety in Listing 7 (p.
684) near the end of this module.
For purposes of illustration, this program deals specically with the method named toString from the
above list, but it could deal just as well with other non-nal methods in the list.
The class named A
Listing 1 (p. 678) denes a class named A , which extends the class named Object (recall that it is
not necessary to explicitly show that a class extends Object ).
5.51
class B extends A{
public String toString(){
return "toString in class B";
}//end overridden toString()
}//end class B
5.52
class C extends B{
public String toString(){
return "toString in class C";
}//end overridden toString()
}//end class B
5.53
5.54
A@111f71
Pretty ugly, huh?
Nowhere does our program explicitly show the creation of any text that looks anything like this. Where
did it come from?
Default toString behavior
What you are seeing here is theString produced by the default version of the toString method, as
dened by the class named Object .
Class A does not override toString
Recall that our new class named A does not override the toString method. Therefore, when the
toString method is called on a reference to an object of the class A , the default version of the method
is executed, producing output similar to that shown above (p. 680) .
What does Sun have to say?
Here is more of what Sun has to say about the default version of the toString method
"The toString method for class Object returns a string consisting of the name of the class of which
the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash
code of the object."
You should recognize this as a description of the output produced by calling the toString method on
the reference to the object of the class A . That explains the ugliness of the screen output shown above
(p. 680) (hexadecimal representations of hashcodes are usually pretty ugly) .
A new object of the class B
Now consider the code shown in Listing 5 (p. 681) , which instantiates a new object of the class named
B , and stores the object's reference in a reference variable of type Object .
5.55
toString in class B
Do you recognize this?
You should recognize this as the text that was encapsulated in the String object by the overridden
toString method dened in the class named B
version of the .
Overridden version of toString was executed
This veries that even though the reference to the object of the class B was stored in a reference variable
of type Object , the overridden version of the toString method dened in the class named B was
executed (instead of the default version dened in the class named Object ) . This is a good example of
runtime polymorphic behavior , as described in a previous module.
As you learned in the previous module, the selection of a method for execution is based on the actual
type of object whose reference is stored in a reference variable, and not on the type of the reference
variable on which the method is called.
5.56
toString in class C
Overridden version of toString was called
This conrms what you should already have known by now. In particular, even though the reference to
the object of the class C is stored in a reference variable of type Object , the overridden version of
the toString method dened in the class named C was executed. Again, this is runtime polymorphic
behavior based on class inheritance and method overriding.
No downcasting was required
It is also very important to note that no downcasting was required in order to call the toString method
in any of the cases shown above.
Because a default version of the toString method is dened in the Object class, the toString
method can be called without a requirement for downcasting on a reference to any object stored in a variable
of type Object . This holds true for any of the eleven methods dened in the class named Object
(although some of those methods are declared nal and therefore may not be overridden) .
5.2.8.5 Summary
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
• Method overloading
• Method overriding through class inheritance
• Method overriding through the Java interface
In this module, I have continued my discussion of the implementation of polymorphism using method over-
riding through class inheritance, and have concentrated on a special case in that category.
More specically, in this module, I have discussed the use of the Object class as a completely generic
type for storing references to objects of subclass types, and have explained how that results in a very useful
form of runtime polymorphism. .
I briey mentioned the default version of the eleven methods dened in the Object class, and explained
that in some cases, those default versions are meant to be overridden.
I provided a sample program that illustrates the overriding of the toString method, which is one of
the eleven methods dened in the Object class.
5.2.8.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly04.java
Copyright 2002, R.G.Baldwin
A@111f71
toString in class B
toString in class C
**************************************/
class B extends A{
public String toString(){
return "toString in class B";
}//end overridden toString()
}//end class B
//===================================//
class C extends B{
public String toString(){
return "toString in class C";
}//end overridden toString()
}//end class B
//===================================//
}//end main
}//end class Poly04
5.57
-end-
5.2.9.2 Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented
Programming (OOP) using Java.
5.2.9.2.1.1 Listings
• Listing 1 (p. 687) . Denition of interfaces named I1 and I2.
• Listing 2 (p. 688) . Denition of the class named A.
• Listing 3 (p. 688) . Denition of the class named B.
• Listing 4 (p. 690) . Denition of the class named C.
• Listing 5 (p. 691) . The driver class named Poly05.
• Listing 6 (p. 695) . Complete program listing.
5.2.9.3 Preview
Method overloading
I covered method overloading as one form of polymorphism (compile-time polymorphism) in a previous
module. I also explained automatic type conversion and the use of the cast operator for type conversion in
a previous module.
Method overriding and class inheritance
I also discussed runtime polymorphism implemented through method overriding and class inheritance in
previous modules.
Using the Java interface
In this module and the next, I will explain runtime polymorphism as implemented using method overriding
and the Java interface.
A very important concept
29 This content is available online at <http://cnx.org/content/m44195/1.3/>.
In my opinion, this is one of the most important concepts in Java OOP, and the one that seems to give
students the greatest amount of diculty. Therefore, I will try to take it slow and easy. As usual, I will
illustrate the concept using sample programs.
I will also tie this concept back to the concept of polymorphism using method overriding through inher-
itance.
A skeleton program
In this module, I will present a simple skeleton program that illustrates many of the important aspects
of polymorphic behavior based on the Java interface.
Multiple inheritance and the cardinal rule
I will explain how the implementation of interfaces in Java is similar to multiple inheritance. I will explain
the cardinal rule of interface implementation.
A new relationship
I will explain that objects instantiated from classes that implement the same interface have a new rela-
tionship that goes beyond the relationship imposed by the standard class hierarchy.
One object, many types
I will explain that due to the combination of the class hierarchy and the fact that a class can implement
many dierent interfaces, a single object in Java can be treated as many dierent types. However, for any
given type, there are restrictions on the methods that can be called on the object.
Many classes, one type
I will explain that because dierent classes can implement the same interface, objects instantiated from
dierent classes can be treated as a common interface type.
Interfaces are critical to Java programming
I will suggest that there is little if anything useful that can be done in Java without understanding and
using interfaces.
In support of this suggestion, I will discuss several real-world examples of the use of the Java inter-
face, including the Delegation Event Model, the Model View Control paradigm, and iterators in Java data
structures.
interface I1{
public void p();
}//end interface I1
//===================================//
5.58
Each of the interfaces in Listing 1 (p. 687) declares an implicitly abstract method (an abstract method does
not have a body) .
Neither of the interfaces in Listing 1 (p. 687) declares any variables (they aren't needed for the purpose
of this module) .
A new data type
I told you earlier that when you dene a new class, you cause a new data type to become available to
your program. The same is true of an interface denition. Each interface denition constitutes a new type.
The class named A
Listing 2 (p. 688) denes a very simple class named A , which in turn denes two methods named
toString and x .
5.59
Overridden toString
The method named toString in Listing 2 (p. 688) is actually an overridden version of the method
having the same name that is dened in the class named Object . (Recall that a previous module made
heavy use of overridden versions of the toString method.)
New method
The method named x is newly dened in the class named A . (The method named x is not
inherited into the class named A , because the class named Object does not dene a method named
x .)
The class named B
Listing 3 (p. 688) contains material that is new to this module.
5.60
Implementing an interface
Listing 3 (p. 688) denes a class named B , which extends the class named A , and implements
the interface named I2 .
As you already know, a class in Java can extend only one other class. However, a Java class can implement
any number of interfaces. (Multiple inheritance is allowed with interfaces.)
Similar to an abstract class
An interface is similar, but not identical, to an abstract class. (An abstract class may contain abstract
methods or concrete methods, or a combination of the two while all of the methods in an interface are
implicitly abstract.)
Restrictions
An abstract class cannot be instantiated. Thus, an abstract class is only useful when it is extended by
another class.
An interface also cannot be instantiated.
Implicitly abstract methods
As mentioned above, all methods declared in an interface are implicitly abstract, but that is not true
for an abstract class. An abstract class can also contain fully-dened (concrete) methods. Regardless, an
abstract class cannot be instantiated.
A totally abstract class
At the risk of oending the purists, I will coin a new term here and say that an interface is similar to a
totally abstract class (one which contains only abstract method declarations and nal variables) .
To a rst degree of approximation then, we might say that the class named B is not only a subclass of
the class named A , it is also a subclass of the totally abstract class named I2 . (This is pretty far
out with respect to terminology, so to avoid being embarrassed, you probably shouldn't repeat it to anyone
else.)
Since I2 extends I1 , we might also say that the class named B is a subclass of the totally abstract
class named I1 .
A dierent kind of thinking
With this kind of thinking, we have suddenly make it possible for Java classes to support multiple
inheritance , with the stipulation that all but one of the inherited classes must be totally abstract classes .
Be very careful with this way of thinking
However, we need to be very careful with this kind of thinking. While it may help some students to
understand the role of interfaces in Java, there are probably some hidden dangers lurking here.
Back to the safety zone
The safest course of action is to simply say that the class named B :
Java does not support multiple inheritance, but it does allow you to extend one class and implement any
number of interfaces.
The cardinal rule regarding interface implementation
The cardinal rule in implementing interfaces is:
If a class implements an interface, it must provide a concrete denition for all the methods declared
by that interface, and all the methods inherited by that interface. Otherwise, the class must be declared
abstract and the denitions must be provided by a class that extends the abstract class.
The cardinal rule regarding class inheritance
A similar rule exists for dening classes that inherit abstract methods from other classes:
If a class inherits one or more abstract methods from its superclasses, it must provide concrete denitions
for all the inherited abstract methods. Otherwise, the class must be declared abstract and the concrete
denitions must be provided by a class that extends the abstract class.
What does that mean in this case?
In this case, this means that the class named B must provide concrete denitions for the methods
named p and q , because:
As in method overriding, the signature of the concrete method in the dening class must match the signature
of the method as it is declared in the interface.
Class B satises the cardinal rule
As you can see from Listing 3 (p. 688) , the class named B does provide concrete (but empty)
denitions of the methods named p and q .
(As mentioned earlier, I made the methods empty in this program for simplicity. However, it is not
uncommon to dene empty methods in classes that implement interfaces that declare a large number of
methods, such as the MouseListener interface. See my tutorials on event-driven programming at
http://www.dickbaldwin.com/toc.htm 30 for examples.)
The class named C
Listing 4 (p. 690) denes a class named C , which extends Object , and also implements I2 . As
in the case of the class named B , this class must, and does, provide concrete (but empty) denitions for
the methods named p and q .
5.61
A driver class
Finally, the driver class named Poly05 shown in Listing 5 (p. 691) denes an empty main method.
30 http://www.dickbaldwin.com/toc.htm
5.62
Doesn't do anything
As mentioned earlier, the purpose of this program is solely to illustrate an inheritance and interface
structure. This program can be compiled and executed, but it doesn't do anything useful.
A new relationship
At this point, it might be useful for you to sketch out the structure in a simple hierarchy diagram.
If you do, you will see that implementation of the interface named I2 by the classes named B and
C , has created a relationship between those two classes that is totally independent of the normal class
hierarchical relationship.
What is the new relationship?
By declaring that both of these classes implement the same interface named I2 , we are guaranteeing
that an object of either class will contain concrete denitions of the two methods declared in the interfaces
named I2 and I1 .
Furthermore, we are guaranteeing that objects instantiated from the two classes can be treated as the
common type I2 .
( Important : references to any objects instantiated from classes that implement I2 , can
be stored in reference variables of the type I2 , and any of the interface methods can be called on those
references.)
We know the user interface
The signatures of the interface methods in the two classes must match the signatures declared in the
interfaces.
This means that if we have access to the documentation for the interfaces, we also know the signatures
of the interface methods for objects instantiated from any class that implements the interfaces.
Dierent behavior
However, and this is extremely important, the behavior of the interface methods as dened in the class
named B may be (and often will be) entirely dierent from the behavior of the interface methods having
C .
the same signatures as dened in the class named
Possibly the most powerful concept in Java
This is possibly the most powerful (and most dicult) concept embodied in the Java programming
language.
If you don't understand interfaces ...
I usually tell my students several times each semester that if they don't understand interfaces, they don't
really understand Java.
It is unlikely that you will ever be successful as a Java programmer without an understanding of interfaces.
There are very few worthwhile programs that can be written in Java without an understanding of inter-
faces.
The core aspect
So, what is the core aspect of this concept that is so powerful?
I told you earlier that each interface denition constitutes a new type. As a result, a reference to any
object instantiated from any class that implements a given interface can be treated as the type of the
interface.
So what!
When a reference to an object is treated as an interface type, any method declared in, or inherited into
that interface can be called on the reference to the object.
However, the behavior of the method when called on references to dierent objects of the same interface
type may be very dierent. In the current jargon, the behavior is appropriate for the object on which it is
called .
One object, many types
Furthermore, because a single class can implement any number of dierent interfaces, a single object
instantiated from a given class can be treated as any of the interface types implemented by the class from
which it is instantiated. Therefore, a single object in Java can be treated as many dierent types.
(However, when an object is treated as an interface type, only those methods declared in that interface
can be called on the object. To call other methods on the object, it necessary to cast the object's reference
to a dierent type.)
Treating dierent types of objects as a common type
All of this also makes it possible to treat objects instantiated from widely diering classes as the same
type, provided that all of those classes implement the same interface.
Important : When an interface method is called on one of the objects using the reference of the interface
type, the behavior of the method will be as dened by the author of the specic class that implemented the
interface. The behavior of the method will often be dierent for dierent objects instantiated from dierent
classes that implement the same interface.
Receiving parameters as interface types
Methods can receive parameters that are references of interface types. In this case, the author of the
code that calls interface methods on the incoming reference doesn't need to know, and often doesn't care,
about the name of the class from which the object was instantiated. (For a discussion of this capability,
see my tutorials on Java Data Structures on my web site at http://www.dickbaldwin.com/toc.htm 31 .)
A common example
A very common example is to store references to objects instantiated from dierent classes, (which
implement the same interface) in some sort of data structure ( such as list or a set) and then to call the
same methods on each of the references in the collection.
Heart of the Delegation Event Model
For example, this methodology is at the heart of the Delegation Event Model , which forms the basis
of Graphical User Interfaces and event-driven programming in Java.
This often entails dening classes that implement standard interfaces such as MouseListener ,
WindowListener , TextListener , etc. In this case, the programmer denes the interface methods to
be appropriate for a listener object instantiated from a specic class. Then a reference to the listener object
is registered on an event source as the interface type .
Later when an event of that type occurs, the source object calls one or more interface methods on the
listener object using the reference of the interface type. The event source object doesn't know or care about
the class from which the object was instantiated. In fact, it doesn't even care how the interface method
behaves when it is called. The responsibility of the source object ends when it calls the appropriate interface
method on the listener object.
Model View Control
This same methodology is also critical to the use of the Model View Control paradigm in Java using
the Observer interface and the Observable class. In this case, view objects instantiated from dierent
classes that implement the Observer interface can register themselves on a model object that extends the
Observable class. Then each time the data being maintained in the model changes, each of the views will
be notied so that they can update themselves.
31 http://www.dickbaldwin.com/toc.htm
JavaBeans Components
This concept is also critical to the use of bound and constrained properties in JavaBeans Components.
One bean can register itself on other beans to be notied each time the value of a bound or constrained
property changes. In the case of constrained properties, the bean that is notied has the option of vetoing
the change.
Java Collections Framework
The Java Collections Framework is also totally dependent on the use of interfaces. As I mentioned earlier,
you can read all about this in my modules on Java Data Structures.
Iterators and Enumerators
If you appreciate data structures, you will also appreciate iterators. In Java, Iterator is an interface,
and an object that knows how to iterate across a data structure is an object of a class that implements the
Iterator interface.
As a result, the users of the concrete implementations in the Java Collections Framework don't need
to know any of the implementation details of the collection to create and use an iterator. All of the work
necessary to properly create an iterator is done by the author of the class that implements the appropriate
Collection interfaces. All the user needs to understand is the behavior of the three methods declared in the
Iterator interface.
5.2.9.5 Summary
Polymorphic behavior, based on the Java interface, is one of the most important concepts in Java OOP
In this module, I began my discussion of runtime polymorphism as implemented using method overriding
and the Java interface.
I presented a simple skeleton program that illustrated many of the important aspects of polymorphic
behavior based on the Java interface.
By using a nonstandard notation of my own design, (a totally abstract class) , I explained how the
implementation of interfaces in Java is similar to multiple inheritance.
I explained the cardinal rule, which is:
If a class implements an interface, it must provide a concrete denition for all the methods declared
by that interface, and all the methods inherited by that interface. Otherwise, the class must be declared
abstract and the denitions must be provided by a class that extends the abstract class.
I explained that objects instantiated from classes that implement the same interface have a new relation-
ship that goes beyond the relationship imposed by the standard class hierarchy.
I explained that due to the combination of the class hierarchy and the fact that a class can implement
many dierent interfaces, a single object in Java can be treated as many dierent types. However, for any
given type, there are restrictions on the methods that can be called on the object.
I also explained that because dierent classes can implement the same interface, objects instantiated
from dierent classes can be treated as a common interface type.
I suggested that there is little if anything useful that can be done in Java without understanding and
using interfaces.
Finally I discussed some real-world examples of the use of the Java interface:
5.2.9.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly05.java
Copyright 2002, R.G.Baldwin
**************************************/
interface I1{
public void p();
}//end interface I1
//===================================//
}//end main
}//end class Poly05
5.63
696 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
-end-
5.2.10.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.10.2.1.1 Listings
• Listing 1 (p. 698) . Denition of the interfaces named I1 and I2.
• Listing 2 (p. 698) . Denition of the class named A.
• Listing 3 (p. 699) . Denition of the class named B.
• Listing 4 (p. 700) . Denition of the class named C.
• Listing 5 (p. 700) . Beginning of the class named Poly06.
• Listing 6 (p. 701) . Try unsuccessfully to call the method named q.
• Listing 7 (p. 701) . Successfully call the method named q.
• Listing 8 (p. 702) . Instantiate a new object of the class B.
• Listing 9 (p. 702) . Try unsuccessfully to call the method named x.
• Listing 10 (p. 703) . Successfully call the method named x.
• Listing 11 (p. 703) . Call the toString method.
• Listing 12 (p. 704) . Try unsuccessfully to call the method named p.
• Listing 13 (p. 704) . Successfully call the method named p.
• Listing 14 (p. 705) . A walk in the park.
• Listing 15 (p. 708) . Complete program listing.
5.2.10.3 Preview
Method overloading
I covered method overloading as one form of polymorphism (compile-time polymorphism) in a previous
module.
32 This content is available online at <http://cnx.org/content/m44196/1.3/>.
Listing 1 (p. 698) shows the denition of the two interfaces named I1 and I2 .
interface I1{
public void p();
}//end interface I1
//===================================//
5.64
Since the methods declared in an interface are not allowed to have a body, these interface denitions are
identical to those shown in the program from the previous module.
The class named A
Similarly, Listing 2 (p. 698) shows the denition of the class named A along with the denition of the
method named x , and the overridden method named toString .
5.65
These two methods were also fully dened in the program from the previous module, so there is no change
here either.
The method named B
Listing 3 (p. 699) denes the class named B , which extends A , and implements I2 .
5.66
5.67
In this upgraded version, the methods named p and q each display a message indicating that they
have been executed. Again, this will be useful later to let us know exactly which version of the methods
named p and q get executed when we exercise the objects.
The driver class
Listing 5 (p. 700) shows the beginning of the class named Poly06 . The main method in this class
instantiates objects of the classes named B and C , and exercises them to illustrate what can, and what
cannot be done with them.
5.68
Following this, the code in Listing 5 (p. 700) successfully calls the method named p on the reference,
producing the following output on the computer screen:
p in B
Why is this allowed?
p is declared in the interface named I1
This is allowable because the method named .
Which version of the method was executed?
It is also important to note, (by observing the output) , that the version of the method dened in the
class named B (and not the version dened in the class named C ) was actually executed.
Attempt unsuccessfully to call q
Next, the code in Listing 6 (p. 701) attempts, unsuccessfully, to call the method named q on the same
reference variable of type I1 .
var1.q();//won't compile
5.69
((I2)var1).q();//OK
5.70
As in the case of polymorphism involving class inheritance, the solution is to change the type of the
reference to a type that either declares or inherits the method named q .
In this case, this takes the form of using a cast operator to convert the type of the reference from type
I1 , to type I2 , and then calling the method named q on that reference of a new type.
This produces the following output:
q in B
Using type I2 directly
Listing 8 (p. 702) instantiates a new object of the class B and stores the object's reference in a reference
variable of the interface type I2 .
5.71
p in B
q in B
Why does this work?
This works because:
5.72
The required type conversion is accomplished in Listing 10 (p. 703) where the reference is temporarily
converted to type A using a cast operator. (It would also work to cast it to type B .)
5.73
The String produced by the rst statement in Listing 10 (p. 703) is passed to the println method
causing the following text to be displayed on the computer screen:
x in A
Get ready for a surprise
If you have now caught onto the general scheme of things, the next thing that I am going to show you
may result in a little surprise.
Successfully call the toString method on var2
The rst statement in Listing 11 (p. 703) successfully calls the toString method on the object of the
class B whose reference is stored as type I2 .
var3 = var2.toString();//OK
System.out.println(var3);
5.74
toString in A
Polymorphism applies
Note that the object whose reference is held in var2 was instantiated from the class named B , which
extends the class named A .
Due to polymorphism, the toString method that was actually executed in Listing 11 (p. 703) was
the overridden version dened in class A , and not the default version dened in the Object class. The
overridden version in classA was inherited into class B .
The reverse is not true
While a reference of an interface type also acts like type Object , a reference of type Object does
not act like an interface type.
Store a reference as type Object
The code in Listing 12 (p. 704) instantiates a new object of type B and stores it in a reference of type
Object .
Attempt unsuccessfully to call p
Then it attempts, unsuccessfully, to call the method named p on the reference.
5.75
((I1)var4).p();//OK
5.76
The output
The code in Listing 13 (p. 704) compiles and executes successfully, producing the following text on the
computer screen:
p in B
A walk in the park
If you understand all of the above, understanding the code in Listing 14 (p. 705) should be like a walk
in the park on a sunny day.
5.77
Class C implements I2
Recall that the class named C also implements the interface named I2 .
The code in Listing 14 (p. 705) instantiates a new object of the class named C , and stores the object's
reference in the existing reference variable named var2 of type I2 .
Then it calls the methods named p and q on that reference, causing the following text to be displayed
on the computer screen:
p in C
q in C
Which methods were executed?
This conrms that the methods that were actually executed were the versions dened in the class named
C ( and not the versions dened in the class named B ) .
Same method name, dierent behavior
It is important to note that the behavior of the methods named p and q , as dened in the class
named C , is dierent from the behavior of the methods having the same signatures dened in the class
named B . Therein lies much of the power of the Java interface.
The power of the Java interface
Using interface types, it is possible to collect many objects instantiated from many dierent classes
(provided all the classes implement a common interface) , and store each of the references in some kind of
collection as the interface type.
Appropriate behavior
Then it is possible to call any of the interface methods on any of the objects whose references are stored
in the collection.
To use the current jargon, when a given interface method is called on a given reference, the behavior that
results will be appropriate to the class from which that particular object was instantiated.
This is runtime polymorphism based on interfaces and overridden methods.
5.2.10.5 Summary
If you don't understand interfaces ...
If you don't understand interfaces, you don't understand Java, and it is highly unlikely that you will be
successful as a Java programmer.
Interfaces are indispensable in Java
Beyond writing "Hello World" programs, there is little if anything that can be accomplished using Java
without understanding and using interfaces.
What can you do with interfaces?
The sample program that I discussed in this module has illustrated (in a very basic form) some of the
things that you can do with interfaces, along with some of the things that you cannot do with interfaces.
In order to write programs that do something worthwhile, you will need to extend the concepts illustrated
by this sample program into real-world requirements.
5.2.10.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
/*File Poly06.java
Copyright 2002, R.G.Baldwin
p in B
q in B
x in A
toString in A
p in B
p in C
q in C
**************************************/
interface I1{
public void p();
}//end interface I1
//===================================//
-end-
5.2.11.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.11.2.1.1 Images
• Image 1 (p. 715) . Output date and time.
• Image 2 (p. 717) . Five seconds later.
• Image 3 (p. 718) . Same date and time as before.
• Image 4 (p. 719) . A new date and time.
• Image 5 (p. 720) . Same date and time as before.
• Image 6 (p. 722) . Output from overridden toString method in Date class.
5.2.11.2.1.2 Listings
• Listing 1 (p. 713) . Beginning of the class named MyClass01.
• Listing 2 (p. 714) . Signature of the main method.
• Listing 3 (p. 715) . Display some text.
• Listing 4 (p. 715) . Display date information.
• Listing 5 (p. 716) . A ve-second delay.
• Listing 6 (p. 716) . Instantiate a new object.
• Listing 7 (p. 716) . Display the new Date object.
• Listing 8 (p. 718) . Accessing class variable via an object.
• Listing 9 (p. 718) . Another new object.
• Listing 10 (p. 719) . Display the date and time.
• Listing 11 (p. 720) . Display date information.
5.2.11.3 Preview
Static members
There is another aspect of OOP in Java that I have avoided up to this point in the discussion: static
variables and static methods.
Tends to complicate ...
I have avoided this topic because, while not particularly dicult, the existence of static members tends
to break up the simple structures that I have discussed in previous modules in this collection.
While static members can be useful in some situations, the existence of static members tends to
complicate the overall object-oriented structure of Java.
Avoid overuse of static members
static members
Furthermore, the overuse of can lead to problems similar to those experienced in
languages like C and C++ that support global variables and global functions.
When to use static members
I will discuss the use of static members in this module, and will provide some guidelines for their use.
The class named Class
I will also introduce the class named Class and discuss how it enters into the use of static variables
and methods.
Instance members versus class members
I will describe the dierences between instance members and class members with particular emphasis
being placed on their accessibility.
Three kinds of objects
From a conceptual viewpoint, there are at least three kinds of objects involved in a Java program:
• Ordinary objects
• Array objects
• Class objects
Ordinary objects
All (or at least most) of the discussion up to this point in the collection deals with what I have referred
to in the above list as ordinary objects .
These are the objects that you instantiate in you code by applying the new operator to a constructor
for a class in order to create a new instance(object) of that class. (There are also a couple of other ways
to create ordinary objects, but I'm not going to get into that at this time.)
Array objects
I haven't discussed array objects thus far in this collection. (I will discuss them in a future module.)
Suce it for now to say that array objects are objects whose purpose is to encapsulate a one-dimensional
array structure that can contain either primitive values, or references to other objects (including other array
objects).
I will discuss Class objects in this module.
There is a class whose name is Class . The purpose of this class is to encapsulate information about
some other class (actually, it can also be used to encapsulate information about primitive types as well as
class types).
Here is part of what Sun has to say about this class:
"Instances of the class Class represent classes and interfaces in a running Java application. ...
Class has no public constructor. Instead Class objects are constructed automatically by the Java
Virtual Machine as classes are loaded ..."
What does this mean?
As a practical matter, when one or more objects are instantiated from a given class, an extra object of
the Class class is also instantiated automatically. This object contains information about the class from
which the objects were instantiated. (Note that it is also possible to cause a Class object that describes
a specic class to be created in the absence of objects of that class, but that is a topic that will be reserved
for more advanced modules.)
A real-world analogy
Here is an attempt to describe a real-world analogy. Remember that a class denition contains the
blueprint for objects instantiated from that class.
A certain large construction company is in the business of building condominium projects. This contractor
builds condos of many dierent sizes, types, and price ranges. However, each dierent condo project contains
condos of only two or three dierent types or price ranges.
A library of blueprints
There is a large library of blueprints at the contractor's central oce. This library contains blueprints
for all of the dierent types of condos that the contractor has built or is building. (This library is analogous
to the class libraries available to the Java programmer.)
A subset from the blueprint library
When a condo project begins, the contractor delivers copies of several sets of blueprints to the construction
site. The blueprints delivered to that site describe only the types of condos being constructed on that site.
Condo is analogous to an object
Each condo unit is analogous to an ordinary Java object .
Each set of blueprints delivered to the construction site is roughly analogous to an object of the class
named Class . In other words, each set of blueprints describes one or more condo units constructed from
that set of blueprints.
When construction is complete
When the construction project is complete, the contractor delivers a set of blueprints for each type of
condo unit to the management rm that has been hired to manage the condo complex. Each set of blueprints
continues to be analogous to an object of the class named Class . The blueprints remain at the site of the
condo units.
RTTI
Thus, information regarding the construction, wiring, plumbing, air conditioning, etc., for each condo
unit (object) continues to be available at the site even after the construction has been completed. (This is
somewhat analogous to something called runtime type information and often abbreviated as RTTI. A Class
object contains RTTI for objects instantiated from that class.)
What are those analogies again?
In the above scenario, each condo unit is (roughly) analogous to an object instantiated from a specic
class (set of blueprints).
Each set of blueprints remaining onsite after construction is complete is roughly analogous to a Class
object that describes the characteristics of one or more condo units.
What do you care?
Until you get involved in such advanced topics as reection and introspection , you don't usually have
much involvement or much interest in Class objects. They are created automatically, and are primarily
used by the Java virtual machine during runtime to help it do the things that it needs to do.
An exception to that rule
However, there is one area where you will be interested in the use of these Class objects from early on.
You will be interested whenever variables or methods in the class denition are declared to be static .
Class variables and class methods
According to the current jargon, declaring a member variable to be static causes it to be a class
variable . (Note that local variables cannot be declared static . Only member variables can be declared
static .) Similarly, declaring a method to be static causes it to be a class method.
Instance variables and methods
On the other hand, according to the current jargon, not declaring a variable to be static causes it to
be an instance variable , and not declaring a method to be static causes it to be an instance method .
In general, we can refer to them as class members and instance members .
What is the dierence?
Here are some of the dierences between class and instance members insofar as this discussion is
concerned.
How many copies of member variables exist?
instance variable dened in the
Every object instantiated from a given class has its own copy of each
class. (Instance variables are not shared among objects.) However, every object instantiated from a given
class shares the same copy of each class variable dened in the class. (It is as though the class variable
belongs to the single Class object and not to the individual objects instantiated from that class.)
Access to an instance variable
Every object has its own copy of each instance variable (the object owns the instance variable). There-
fore, the only way that you can access an instance variable is to use that object's reference to send a message
to the object requesting access to the variable (even then, you may not be given access, depending on access
modiers).
Why call it an instance variable?
According to the current jargon, an object is an instance of a class . (I probably told you that
somewhere before in this collection.) Each object has its own copy of each non-static variable. Hence, they
are often called instance variables. (Every instance of the class owns one and they are not implicitly shared
among instances.)
Access to a class variable
You can also send a message to an object requesting access to a class variable that the object shares with
other objects instantiated from the same class. (Again, you may or may not gain access, depending the
access modiers).
Access using the Class object
More importantly, you can also access a class variable without a requirement to go through an object
instantiated from the class. (In fact, a class variable can be accessed in the total absence of objects
of that class.) (Remember, this discussion is conceptual in nature, and may not represent an actual
implementation.)
Assuming that a class variable is otherwise accessible, you can access the class variable by sending an
Class
access request message to the object to which the variable belongs.
One way to think of this
To help you keep track of things in a message-passing sense, you can pretend that there is a global
reference variable whose name is the same as the name of a class.
This (hypothetical) reference variable contains a reference to the Class object that owns the class
variable. Using standard Java message-passing syntax, you can access the class variable by joining the name
of the reference variable to the name of the class variable with a period. Example syntax is shown below:
ReferenceVariableName.ClassVariableName
As a result of the hypothetical substitution process that I described above, this is equivalent to the following:
ClassName.ClassVariableName
We will see an example of this in the sample program that I will discuss later.
Be careful with this thought process
While this thought process may be useful when thinking about static variables and methods, I want
to point out, that the thought process breaks down very quickly when dealing with Class objects in a
deeper sense.
For example, when calling the getName method on a Class object, an actual reference of type
Class is required to access the members of the Class object. The name of the class will not suce.
If this discussion of a global reference variable whose name matches the name of the class is confusing
to you, just forget it. Simply remember that you can access class variables by joining the name of the class
to the name of the class variable using a period as the joining operator.
Characteristics of class methods
I'm not going to talk very much about instance methods and class methods in this module. However,
there are a couple of characteristics of class methods that deserve a brief discussion in this context.
Cannot access instance members
First, the code in a class method has direct access only to other static members of the class. (A class
method does not have direct access to instance variables or instance methods of the class.) This is sort of
like saying that a class method has access to the methods and variables belonging to the Class object, but
does not have access to the methods and variables belonging to the ordinary objects instantiated from the
class described by the Class object.
Once again, be careful
Once again, this thinking breaks down very quickly once you get beyond static members. A Class
object also has instance methods, such as getName , which can only be accessed using an actual reference
to the Class object.
Now you are probably beginning to understand why I deferred this discussion until after I nished
discussing the easy stu.
No object required
Another important characteristic is that a class method can be accessed without a requirement for an
object of the class to exist.
As with class variables, class methods can be accessed by joining the name of the class to the name of
the method with a period.
I will illustrate much of this with a sample program named MyClass01 .
Discuss in fragments
I will discuss the program in fragments. You will nd a complete listing of the program in Listing 13 (p.
726) near the end of the module.
Listing 1 (p. 713) shows the beginning of the class denition.
class MyClass01{
static Date v1 = new Date();
Date v2 = new Date();
5.79
the constructor with no arguments, the new Date object encapsulates the current date and time from the
system clock.)
Note the static keyword
The important thing to note here is the use of the static keyword when declaring the variable named
v1 . This causes v1 to be a class variable , exhibiting the characteristics of class variables described
earlier.
An instance variable
On the other hand, the variable named v2 is not declared static . This causes it to be an instance
variable , as described above.
The main method is a class method
Listing 2 (p. 714) shows the signature for the main method.
5.80
The important thing to note here is that the main method is declared static . That causes it to be
a class method .
As a result, the main method can be called without a requirement for an object of the class to exist.
(Also, the main method has direct access only to other static members.)
How a Java application starts running
In fact, that is how the Java Virtual Machine starts an application running.
First the JVM nds the specied le having an extension of .class. Then it examines that le to see
if it has a main method with the correct signature. If not, an error occurs.
If the JVM nds a main method with the correct signature, it calls that method without instantiating
an object of the class. That is how the Java Virtual Machine causes a Java application to start running.
A side note regarding applets
For those of you who are familiar with Java applets, you should know that this is not the case for an
applet. An applet does not use a main method. When an applet is started, an object of the controlling
class is instantiated by the browser, by the appletviewer program, or by whatever program is being used
to control the execution of the applet.
A poor programming technique
Basically, this entire sample program is coded inside the main method. As a practical manner, this is
a very poor programming technique, but it works well for this example.
Display some text
The code in Listing 3 (p. 715) , which is the rst executable statement in the main method, causes
the words Static variable to appear on the computer screen. I will come back and discuss the details of
this and similar statements later in the module.
System.out.println("Static variable");
5.81
System.out.println(MyClass01.v1);
5.82
No object required
For the moment, concentrate on the text inside the parentheses in the statement in Listing 4 (p. 715) .
Because the variable named v1 is a class variable, it's value is accessed by joining the name of the class
to the name of the variable with a period.
What was the output?
I will discuss the remaining portion of statements of this sort later. For now, just be aware that the code
in Listing 4 (p. 715) caused the output shown in Image 1 (p. 715) to be displayed on my computer screen
when I ran the program.
5.83
try{
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){}
5.84
5.85
System.out.println(ref1.v2);
5.86
5.87
The date and time shown in Image 2 (p. 717) is ve seconds later than the time reected in the Date
object referred to by the class variable named v1 (see Image 1 (p. 715) ) . That time was displayed by
the code in Listing 4 (p. 715) earlier.
So, what does this mean?
It means that the Date object referred to by the static reference variable named v1 was created
ve seconds earlier than the Date object referred to by the instance variable named v2 .
When is a class variable created?
I can't tell you precisely when a class variable comes into existence. All I can say is that the virtual
machine brings it into existence as soon as it is needed.
My guess is that it comes into existence at the rst mention (in the program) of the class to which it
belongs.
When is an instance variable created?
An instance variable doesn't come into existence until the object to which it belongs is created. (An
instance variable cannot exist until the object to which it belongs exists.)
If the instance variable is initialized with a reference to a new object (such as a new Date object in
this sample program), that new object comes into existence when the object to which it belongs comes into
existence.
A ve-second delay
In this program, I purposely inserted a ve-second delay between the rst mention of the class named
MyClass01 in Listing 4 (p. 715) , and the instantiation of the object of the class named MyClass01 in
Listing 6 (p. 716) .
As a result, the Date object referred to by the instance variable named v2 was created about ve
seconds later than the Date object referred to by the class variable named v1 .
This is reected in the date and time values displayed and discussed above.
Accessing class variable via an object
While it is possible to access a class variable using the name of the class joined to the name of the variable,
it is also possible to access a class variable using a reference to any object instantiated from the class.
(As mentioned earlier, if two or more objects are instantiated from the same class, they share the same
class variable.)
The code in parentheses in Listing 8 (p. 718) uses the reference variable named ref1 to access the class
variable named v1 , and to cause the contents of the Date object referred to by the class variable to be
displayed.
System.out.println(ref1.v1);
5.88
The output
This caused the date and time shown in Image 3 (p. 718) to be displayed on my computer screen.
5.89
5.90
System.out.println(ref2.v2);
5.91
This caused the output shown in Image 4 (p. 719) to be displayed on my computer screen when I ran
the program.
(Once again, you will get dierent results if you compile and run the program because the date and time
shown is the date and time that you run the program.)
5.92
Also remember that if a variable is a class variable, only one copy of the variable exists, and all objects
instantiated from the class share that one copy.
This is illustrated by the code in Listing 11 (p. 720) , which uses the reference to the second object
instantiated from the class named MyClass01 , to cause the contents of the class variable named v1 to
be displayed.
System.out.println(ref2.v1);
}//end main
5.93
The output produced by the code in Listing 11 (p. 720) is shown in Image 5 (p. 720) .
5.94
System.out.println(ref1.v1);
5.95
• Create a textual representation of the object referred to by the incoming parameter of type Object
(because Object is a totally generic type, this version of the println method can accept an
incoming parameter that is a reference to any type of object)
• Send that textual representation to the output device
In general...
A new PrintStream object can be connected to a variety of output devices when it is instantiated.
However, in the special case of the PrintStream object instantiated by the virtual machine when the
program starts, whose reference is stored in the class variable named out of the System class, the
purpose of the object is to provide a display path to the standard output device.
Our old friend, the toString method
To accomplish this, the code in the version of the println method shown above (p. 721) calls the
toString method on the incoming reference. (I discussed the toString method in detail in earlier
modules in this collection.) The toString method may, or may not, have been overridden in the denition
of the class from which the object was instantiated, or in some superclass of the class from which the object
was instantiated.
Default version of toString
If not overridden, the default version of the toString method dened in the Object class is used to
produce a textual representation of the object. As we learned in an earlier module, that textual representation
looks something like the following:
ClassName@HexHashCode
Overridden version of toString method
If the class from which the object was instantiated (or some superclass of that class) contains an
overridden version of the toString method, runtime polymorphism kicks in and the overridden version of
the method is executed to produce the textual representation of the object.
The Date class overrides toString
In the case of this sample program, the object was instantiated from the Date class. The Date class
does override the toString method.
When the overridden toString method is called on a Date object's reference, the String returned
by the method looks something like that shown in Image 6 (p. 722) .
5.96
You will recall that this is the output that was produced by the code shown in Listing 8 (p. 718) and
Listing 12 (p. 721) .
More than you ever wanted to know ...
And that is probably more than you ever wanted to know about the expression System.out.println...
.
It is also probably more than you ever wanted to know about class variables, class methods, instance
variables, and instance methods.
Some cautions
Before leaving this topic, I do want to express some cautions. Basically, I want to suggest that you use
static members very sparingly, if at all.
Static variables
To begin with, don't ever use static variables without declaring them nal unless you understand
exactly why you are declaring them static .
( static nal variables, or constants, are often very appropriate. See the elds in the Color class
for example.)
I can only think of only a very a few situations in which the use of a non-nal static variable might be
appropriate.
(One appropriate use might be to count the number of objects instantiated from a specic class.)
Static methods
Don't declare methods static if there is any requirement for the method to remember anything from
one call to the next.
There are many appropriate uses for static methods, but in most cases, the purpose of the method
will be to completely perform some action with no requirement to remember anything from that call to the
next.
The method should probably also be self-contained. By this I mean that all information that the method
needs to do its job should either come from incoming parameters or from nal static member variables
(constants). The method probably should not depend on the values stored in non-nal static member
variables, which are subject to change over time.
(A static method only has access to other static members of the class, so it cannot depend on
instance variables dened in the class.)
An appropriate example of a static method is the sqrt method of the Math class. This method
computes and "Returns the correctly rounded positive square root of a double" where the double value is
provided as a parameter to the method. Each time the method is called, it completes its task and doesn't
attempt to save any values from that call to the next. Furthermore, it gets all the information that it needs
to do its job from an incoming parameter.
5.2.11.5 Summary
Added complexity
The existence of static members tends to break up the simple OOP structures that I have discussed
in previous modules in this collection.
While static members can be useful in some situations, the existence of static members tends to
complicate the overall object-oriented structure of Java.
Furthermore, the overuse of static members can lead to problems similar to those experienced in
languages like C and C++ that support global variables and global functions.
The class named Class
I discussed the class named Class and how a conceptual object of type Class exists in memory
following a reference to a specic class in the program code.
The Class object represents the referenced class in memory, and contains the static variables and
static methods belonging to that class. (It contains some other information as well, such as the name of
the superclass.)
Class members and instance members
Class variables and class methods are declared static (declaring a member static in the class
denition causes to be called a class member) .
Instance variables and instance methods are not declared static .
Each object has its own copy ...
Every object instantiated from a given class has its own copy of each instance variable declared in the
class denition. (Instance variables are not shared among objects.)
Every object instantiated from a given class acts like it has its own copy of every instance method declared
(Although instance methods are actually shared among objects in order to reduce
in the class denition.
the amount of memory required, they are shared in such a way that they don't appear to be shared.)
Every object shares ...
Every object instantiated from a given class shares the same single copy of each class variable declared
in the class denition. Similarly, every object instantiated from a given class shares the same copy of each
class method.
Accessing an instance member
An instance variable or an instance method can only be accessed by using a reference to the object that
owns it. Even then, it may or may not be accessible depending on the access modier assigned by the
programmer.
Accessing a class member
The single shared copy of a class variable or a class method can be accessed in either of two ways:
Again, the variable or method may or may not be accessible, depending on the access modiers assigned by
the programmer.
When to use class variables
It is very often appropriate to use nal static variables, as constants in your programs. It is rarely, if
ever, appropriate to use non-nal static variables in your programs. The use of non-nal static variables
should denitely be minimized.
When to use static methods
static
It is often appropriate to use methods in your programs, provided there is no requirement for
the method to remember anything from one call to the next. Static methods should be self-contained.
5.2.11.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
/*File MyClass01.java
Copyright 2002, R.G.Baldwin
Static variable
Mon Sep 17 09:52:27 CDT 2001
Instance variable
Mon Sep 17 09:52:32 CDT 2001
Static variable
Mon Sep 17 09:52:27 CDT 2001
Instance variable
Mon Sep 17 09:52:37 CDT 2001
Static variable
Mon Sep 17 09:52:27 CDT 2001
**************************************/
import java.util.Date;
class MyClass01{
static Date v1 = new Date();
Date v2 = new Date();
System.out.println();//blank line
-end-
5.2.12.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.12.2.1.1 Listings
• Listing 1 (p. 729) . Sample variable declarations for array objects.
• Listing 2 (p. 729) . The special case of type Object.
• Listing 3 (p. 730) . Creating array objects.
• Listing 4 (p. 733) . The beginning of the class named Array05.
• Listing 5 (p. 733) . A new ordinary object of class Array05.
• Listing 6 (p. 734) . Populate the second element.
• Listing 7 (p. 734) . Print some data.
• Listing 8 (p. 735) . Produce some more output.
• Listing 9 (p. 738) . Complete program listing.
5.2.12.3 Preview
This module explains how array objects t into the grand scheme of things in Object-Oriented Programming
(OOP) using Java.
A dierent syntax is required to create array objects than the syntax normally used to create ordinary
objects.
Array objects are accessed via references. Any of the methods of the Object class can be called on a
reference to an array object.
Array objects encapsulate a group of variables. The variables don't have individual names. They are
accessed using positive integer index values. The integer indices of a Java array object always extend from
0 to (n-1) where n is the length of the array encapsulated in the object.
All array objects in Java encapsulate one-dimensional arrays. The component type of an array may itself
be an array type. This makes it possible to create array objects whose individual components refer to other
array objects. This is the mechanism for creating multi-dimensional or ragged arrays in Java.
• Ordinary objects
• Class objects
• Array objects
Ordinary objects
Most of the discussion up to that point in the collection dealt with what I have referred to in the above
list as ordinary objects .
These are the objects that you instantiate in you code by applying the new operator to a constructor
for a class in order to create a new instance (object) of that class.
Class objects
In that module, I emphasized that my discussion of Class objects was conceptual in nature and did
not necessarily represent an actual implementation. I went on to discuss the class named Class , and
discussed how the use of that class ts into the grand scheme of OOP in Java. I explained how the existence
of class variables and class methods tends to complicate the rather simple OOP structure consisting only
of ordinary objects.
Array objects
I haven't discussed array objects up to this point in this collection. That is the purpose of this module.
Also tends to complicate
The existence of array objects also tends to complicate the OOP structure of a Java program consisting
only of ordinary objects. Even if you don't consider array objects to be a dierent kind of object, you must
at least consider them to be a special kind of object. A completely dierent syntax is required to create
array objects than the syntax normally used to instantiate ordinary objects.
References to array objects
Arrays are objects in Java (at least, arrays are always encapsulated in objects). Array objects are
dynamically created. Like ordinary objects, array objects are accessed via references. The reference to an
array object may be assigned to a reference variable whose type is specied as:
TypeName[]
For example, Listing 1 (p. 729) shows some unrelated declarations for variables that are capable of storing
references to array objects.
int[] x1;
Button[] x2;
Object[] x3;
5.98
Note the empty square brackets that are required in the variable declarations in Listing 1 (p. 729) .
The special case of type Object
In addition, a reference to an array object may be assigned to a reference variable of type Object as
shown in Listing 2 (p. 729) .
Object x4;
5.99
[I@73d6a5
Pretty ugly, huh?
You may recognize this as being similar to the default String returned by calling the toString method
on an ordinary object with the name of the class for the ordinary object being replaced by [I .
For example, the String returned by calling the toString method on an object of the class named
Array04 , (with no overridden toString method), looks something like the following.
Array04@73d6a5
(Note that the hexadecimal numeric values following the @ in both of the above examples will change from
one case to the next.)
Calling the getClass method
Similarly, calling the getClass method on references to arrays containing data of the types Array04 ,
Button , and int , respectively, and then calling the toString method on the Class objects returned
by the getClass method, produces the following:
class [LArray04;
class [Ljava.awt.Button;
class [I
Complicating the OOP structure
I made the following statement in an earlier paragraph:
"The existence of array objects also tends to complicate the OOP structure of a Java program consisting
only of ordinary objects."
Array object is not a subclass of class Object
Object for
An array object can be treated as type purposes of calling the methods of the Object
class on the reference to the array object. However, it would probably be misleading to say that an array
object is instantiated from a subclass of the Object class.
The new operator and the constructor name
Ordinary objects are created by applying the new operator to the constructor for a class, where the
name of the constructor is always the same as the name of the class. That is not the case with array objects.
Array objects are created by applying the new operator to the name of the type of data to be encapsulated
in the array object.
Passing parameters versus square-bracket notation
In addition, whereas the instantiation of ordinary objects involves parameters passed in parentheses, a
square-bracket notation is used instead of parentheses to create an array object. The value in the square
brackets species thelength of the array.
Creating an array object
Array objects (with default initialization values) are created by applying the new operator to the
name of the data type to be stored in the array, using a square-bracket notation. An example is shown by
the right-hand portion of the rst statement in Listing 3 (p. 730) .
int[] x2 = {1,2,3,4,5};
5.100
The second statement in Listing 3 (p. 730) also creates an array object capable of storing ve values of
type int , but in this case, the values in the elements are explicitly initialized to the values shown.
(Note that the new operator is not used in the second statement in Listing 3. This is also a signicant
departure from the syntax used to instantiate ordinary objects.)
This array object's reference is assigned to the reference variable named x2 .
Note the empty square brackets in the variable declarations
The syntax of the type specication for the reference variable in each statement in Listing 3 (p. 730) is
dierent from the syntax used in the type specication for either a primitive variable or an ordinary class
type reference variable (note the square brackets on the left in Listing 3) . In Listing 3 (p. 730) , the type
specications indicate that each variable is capable of holding a reference to an array object.
The size of the array
Furthermore, the empty square brackets (in the declaration of the reference variable) indicate that the
reference variable doesn't know (and doesn't care) about the size of the array to which it may refer. Each of
the reference variables declared in Listing 3 (p. 730) can refer to a one-dimensional array object of any size.
Also, each of the reference variables can refer to dierent array objects at dierent points in time during the
execution of the program.
note: The Array class As an aside, let me mention that there is a class named Array
, which provides static methods to dynamically create and access Java arrays. The use of the
methods of this class makes it possible to handle arrays with a programming style similar to the
programming style typically used with ordinary objects. However, the use of the methods of the
Array class tends to require more programming eort than the square-bracket notation discussed
in this module. I will discuss a sample program that illustrates the methods of the Array class
in a future module.
Here is another quotation from the Java specication that explains the type specications for the variable
declarations in Listing 1 (p. 729) and Listing 3 (p. 730) .
"All the components of an array have the same type, called the component type of the array. If the
component type of an array is T, then the type of the array itself is written T[]."
Components may be of an array type
As of the time that this object was originally written, all array objects in Java encapsulate one-dimensional
arrays (I have read that this may change in the future).
The component type of an array may itself be an array type. This makes it possible to create array
objects whose individual components refer to other array objects.
Multi-dimensional or ragged arrays
One way to think of this is to think of the second level of array objects as being sub-arrays of the original
array object. This construct can be used to create multi-dimensional array structures.
(The geometry of such multi-dimensional array structures is not constrained to be rectangles, cubes,
etc., as is the requirement in many other languages. Some authors may refer to this as ragged arrays.)
Tree structures
This process of having the components of an array contain references to sub-arrays can be continued
indenitely (well, maybe not indenitely, but further than I care to contemplate).
(This can be thought of as a tree structure where each array object containing references to other array
objects is a node in the tree.)
The leaves of the tree
Eventually, the components (the leaves of the tree structure) must refer to a component type that is
not an array type. According to Sun:
"... this is called the element type of the original array, and the components at this level of the data
structure are called the elements of the original array."
Component versus element
Hopefully, the above quotation provides a somewhat clearer distinction between the use of the words
component and element than was presented earlier.
Generic references
The reference to any array object can also be assigned to reference variables of the types Object ,
Cloneable , or Serializable .
( Object is the class at the top of the inheritance hierarchy. Cloneable and Serializable are
interfaces, which are implemented by all array objects. Thus, a reference to an array object can be treated
as any of these three types.)
Generic array objects
Therefore, if the element type of an array object is one of these types, the elements in the array can refer
to:
This is illustrated in the sample program named Array05 shown in Listing 9 (p. 738) near the end of the
module.
Will explain in fragments
I will explain this program in fragments. Listing 4 (p. 733) shows the beginning of the controlling class
and the beginning of the main method for the program named Array05 ..
5.101
5.102
This is allowable because the reference to an object of any class can be assigned to a reference variable
of type Object .
(The array object referred to by v2 contains two elements, each of which is a reference variable of type
Object .)
Populate the second element
The code in Listing 6 (p. 734) assigns the reference to the existing array object of the element type int
to the second element in the array object of element type Object .
v2[1] = v1;
5.103
This is allowable because a reference to any array object can be assigned to a reference variable of type
Object .
Array contains two references
At this point, the array object of element type Object contains two references.
(Each of the elements in an array of the declared type Object[] is a reference of type Object .)
The rst element refers to an ordinary object of the class Array05 .
The second element refers to an array object of type int , having ve elements, populated with the
integer values of 1 through 5 inclusive.
(Note that this is not a multi-dimensional array in the traditional sense. I will discuss the Java approach
to such multi-dimensional arrays in the next module. This is simply a generic array of element type Object
, one element of which happens to contain a reference to an array object of type int .)
Print some data
The code in Listing 7 (p. 734) passes each of the references to the println method of the PrintStream
class.
System.out.println(v2[0]);
System.out.println(v2[1]);
5.104
The println method causes the toString method to be called on each reference. The String
returned by the toString method is displayed on the computer screen in each case.
This is allowable because any method dened in the Object class (including the toString method)
can be called on any reference stored in a reference variable of type Object .
This is true regardless of whether that reference is a reference to an ordinary object or a reference to an
array object.
The output
Listing 7 (p. 734) causes the following two lines of text to be displayed:
Array05@73d6a5
[I@111f71
Pretty ugly, huh?
In both cases, this is the value of the String returned by the default version of the toString method
dened in the Object class. Here is what Sun has to say about that default behavior:
"Returns a string representation of the object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but informative representation that is easy
for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which
the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash
code of the object."
Doesn't address array objects
Obviously, this description of behavior doesn't address the case where the object is an array object, unless
the characters [I are considered to be the name of a class. (I will have a little more to say about this
later.)
Produce some more output
Finally, Listing 8 (p. 735) shows the last statement in this simple program.
5.105
v2[1]
Get the value at index 1 as type Object
This code begins by accessing the component at index value 1 of the array object referred to by the
reference variable named v2 .
The value retrieved is a reference, and is retrieved as type Object , (because the variable named v2
was declared to be of type Object[] ).
A cast is required
A cast is used to convert from type Object[] to type int[] using the following code:
(int[])
This produces a reference to an array object capable of containing values of type int .
Apply index to the int array
After the type of the reference has been converted, the accessor [4] is applied to the reference. This
causes the int value stored in the array object of type int (at index value 4) to be returned.
(If you refer back to Listing 4 (p. 733) , you will see that the integer value 5 was stored in the element
at index value 4 of this array object.)
You should try to remember this syntax and compare it with the syntax used in the Java approach to
traditional multi-dimensional arrays, which I will discuss in the next module.
The output
Thus, the code in Listing 8 (p. 735) causes the number 5 to be displayed on the computer screen.
Let's recap
To recap, the program namedArray05 creates a two-element array object capable of storing references
of type Object .
Object is generic
Because Object is a completely generic type, each of the elements in the array is capable of storing a
reference to any ordinary object, or storing a reference to any array object.
Store reference to ordinary object in generic array
The rst element in the array is populated with a reference to an ordinary object instantiated from the
class named Array05 .
(Important: The actual object does not occupy the array element. Rather, the actual object exists
someplace else in memory, and a reference to the object occupies the array element.)
Store a reference to an array object in the generic array
Object is populated with a reference to another array
The second element in the array of element type
object capable of containing elements of type int .
As above, the actual array object of type int does not occupy the second element. Rather, that array
object exists someplace else in memory, and a reference to the array object occupies the second element in
the array of element type Object .
Display some data
After the array object of element type Object is created and populated, three print statements are
executed to display information about the array object and its contents (those print statements are shown
in Listing 7 (p. 734) and Listing 8 (p. 735) ).
The print statements produce the following output on the computer screen:
Array05@73d6a5
[I@111f71
5
Default textual representation of ordinary object
The rst line of output is the default textual representation of the ordinary object, achieved by calling
the default toString method on the reference to the ordinary object.
Default textual representation of array object
The second line of output is the textual representation of the array object of type int[] , achieved by
calling the default toString method on the reference to the array object.
Primitive value stored in array object
The third line of text is the value stored in element index 4 of the int[] array object whose reference is
stored in element index 1 of the array object of element type Object .
Primitive versus non-primitive array element contents
References to objects are stored in the elements of non-primitive array objects. The objects themselves
exist somewhere else in memory.
Actual primitive values are stored in the elements of a primitive array object.
Thus, the elements of an array object contain actual primitive values, null references, or actual references
to ordinary or array objects, depending on the type of the elements of the array object.
5.2.12.5 Summary
This module begins the discussion of array objects in Java.
The existence of array objects tends to complicate the OOP structure of a Java program otherwise
consisting only of ordinary objects.
A completely dierent syntax is required to create array objects than the syntax normally used to
instantiate ordinary objects. Ordinary objects are normally instantiated by applying the new operator to
the constructor for the target class passing parameters between a pair of matching parentheses.
Array objects (with default initialization) are created using the new operator, the type of data to be
encapsulated in the array, and a square-bracket notation to specify the length of the array encapsulated
in the object.
Array objects with explicit initialization are created using a comma-separated list of expressions enclosed
in curly brackets.
Arrays in Java are objects, which are dynamically created and allocated to dynamic memory.
Like ordinary objects, array objects are accessed via references. The type of such a reference is considered
to be TypeName[] (note the empty square brackets in the type specication).
A reference to an array object can also be assigned to a reference variable of type Object (note the
absence of square brackets). Thus, any of the methods of the Object class can be called on a reference
to an array object.
As is the case with other languages that support arrays, array objects in Java encapsulate a group of
zero or more variables. The variables encapsulated in an array object don't have individual names. Rather,
they are accessed using positive integer index values.
The integer indices of a Java array object always extend from 0 to (n-1) where n is the length
of the array object.
As of the time of this writing, all array objects in Java encapsulate one-dimensional arrays. However, the
component type of an array may itself be an array type. This makes it possible to create array objects whose
individual components refer to other array objects. This is the mechanism for creating multi-dimensional
or ragged arrays in Java.
The reference to any array object can be assigned to reference variables of the types Object ,
Cloneable , or Serializable . If the element type of an array object is one of these types, the elements
in the array can refer to:
5.2.12.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
/*File Array05.java
Copyright 2002, R.G.Baldwin
Array05@73d6a5
[I@111f71
5
**************************************/
int[] v1 = {1,2,3,4,5};
Object[] v2 = new Object[2];
v2[0] = new Array05();
v2[1] = v1;
System.out.println(v2[0]);
System.out.println(v2[1]);
System.out.println(
((int[])v2[1])[4]);
}//end main
}//end class Array05
5.106
-end-
5.2.13.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.13.2.1.1 Listings
• Listing 1 (p. 740) . Reference variable declaration..
• Listing 2 (p. 741) . A three-dimensional array object of element type Button.
• Listing 3 (p. 741) . The generic class Object.
• Listing 4 (p. 742) . Primitive type conversions.
• Listing 5 (p. 743) . Initialization.
• Listing 6 (p. 743) . Placement of square brackets.
• Listing 7 (p. 744) . Creating the actual array object.
• Listing 8 (p. 745) . An array access expression.
• Listing 9 (p. 746) . Explicit initialization of array elements.
• Listing 10 (p. 747) . Create a two-dimensional rectangular array structure.
• Listing 11 (p. 748) . Using length to populate the leaves of the tree structure.
• Listing 12 (p. 749) . Display leaf object contents.
• Listing 13 (p. 750) . Beginning of a ragged array with two rows and three columns.
• Listing 14 (p. 750) . Create the leaf array objects.
• Listing 15 (p. 751) . Create the array object.
• Listing 16 (p. 752) . Populate the root object.
• Listing 17 (p. 753) . Populate the leaf array objects.
• Listing 18 (p. 754) . Display data in leaf array objects.
• Listing 19 (p. 754) . A triangular array.
• Listing 20 (p. 755) . Populate the leaf array objects.
• Listing 21 (p. 756) . A more general approach.
• Listing 22 (p. 756) . Populate the leaf objects.
5.2.13.3 Preview
This module explains various details regarding the use of array objects in Java, and illustrates many of those
details through the use of sample code.
A sample program shows you three ways to emulate traditional two-dimensional rectangular arrays, and
also shows you how to create and use ragged arrays.
int[][] v1;
5.107
(Note that Listing 1 doesn't really declare a two-dimensional array in the traditional sense of other
programming languages. Rather, it declares a reference variable capable of storing a reference to a one-
dimensional array object, which in turn is capable of storing references to one-dimensional array objects of
type int .)
Multiple pairs of square brackets are allowed
The components in an array object may refer to other array objects. The number of bracket pairs used
in the declaration of the reference variable indicates the depth of array nesting (in the sense that array
elements can refer to other array objects). This is one of the ways that Java implements the concept of
traditional multi-dimensional arrays (I will show you some other ways later in this module).
The code in Listing 1 shows two levels of nesting for the reference variable of type
int[][]
Length not part of variable declaration
Note that an array's length is not part of its type or reference variable declaration.
Ragged arrays
Note also that multi-dimensional arrays, when implemented in this fashion, are not required to represent
rectangles, cubes, etc. For example, the number of elements in each row of a Java two-dimensional array
can be dierent. Some authors refer to this as a ragged array .
Allowable types
The specied element type of an array may be any primitive or reference type. Note, however, that all
elements of the array must be of the same type (consistent with the type-conversion rules discussed below)
.
Listing 2 (p. 741) shows the declaration of a reference variable capable of referring to a three -dimensional
array object of element type Button ( Button is one of the classes in the standard class library).
Button[][][] v2;
5.108
Object[] v3;
5.109
int[] v1;
v1 = new int[3];
byte x1 = 127;
short x2 = 16384;
int x3 = 32000;
v1[0] = x1;
v1[1] = x2;
v1[2] = x3;
5.110
Assignment-compatible assignments
byte , short , and int
Values of the types , are stored in the elements of the array object in Listing
4 (p. 742) .
Actual type is lost in the process
byte and short
It should be noted that the values are converted to type int as they are stored.
When retrieved later, they will be retrieved as type int . Any indication that these values were ever of any
type other thanint is lost in the process of storing and retrieving the values.
What about class types?
If the declared element type is the name of a class, (which may or may not be abstract), a null reference
or a reference to any object instantiated from the class or any subclass of the class may be stored in the
array element.
(Obviously you can't store a reference to an object instantiated from an abstract class, because you can't
instantiate an abstract class.)
What about an interface type?
If the declared element type is an interface type, a null reference or a reference to any object instantiated
from any class that implements the interface can be stored in the array element.
(This is an extremely powerful concept, allowing references to objects instantiated from many dierent
classes to be collected into an array as the interface type.)
Array reference variables
All array objects are accessed via references. A reference variable whose declared type is an array type
does not contain an array. Rather, it contains either null, or a reference to an array object.
Allocation of memory
Declaring the reference variable does not create an array, nor does it allocate any space for the array
components. It simply causes memory to be allocated for the reference variable itself, which may later
contain a reference to an array object.
Initialization
In the same sense that it is possible to declare a reference variable for an ordinary object, and initialize it
with a reference to an object when it is declared, it is also possible to declare a reference to an array object
and initialize it with a reference to an array object when it is declared. This is illustrated in Listing 5 (p.
743) , which shows the following operations combined into a single statement:
Listing 5: Initialization.
5.111
int[][] v1;
int[] v2[];
int v3[][];
5.112
Two valid array creation expressions are illustrated by the statements in Listing 7 (p. 744) .
int[][] v1;
int[] v2[];
v1 = new int[2][3];
v2 = new int[10][];
5.113
5.114
First-level access
This array access expression rst accesses the contents of the element at index 0 in the array object
referred to by the reference variable named v1 . This element contains a reference to a second array object
(note the double matching square brackets, [][] in the declaration of the variable named v1 ).
Second-level access
The array access expression in Listing 8 (p. 745) uses that reference to access the value stored in the
element at index value 1 in the second array object. That value is then passed to the println method for
display on the standard output device.
(In this case, the value 0 is displayed, because array elements are automatically initialized to default
values when the array object is created. The default value for all primitive numeric values is zero.)
Zero-based indexing
All array indexes in Java begin with 0 . An array with length n can be indexed by the integers 0 to
(n-1) . Array accesses are checked at runtime. If an attempt is made to access the array with any other
index value, an ArrayIndexOutOfBoundsException will be thrown.
Index value types
Arrays must be indexed by integer values of the following types: int , short , byte , or char .
For any of these types other than int , the value will be promoted to an int and used as the index.
An array cannot be accessed using an index of type long . Attempting to do so results in a compiler
error.
Default initialization
If the elements in an array are not purposely initialized when the array is created, the array elements
will be automatically initialized with default values. The default values are:
int[] v1 = {1,2,3,4,5};
5.115
No new operator
Note that this format does not use the new operator. Also note that the expressions in the list may
be much more complex than the simple literal values shown in Listing 9 (p. 746) .
Length and order
When this format is used, the length of the constructed array will equal the number of expressions in the
list.
The expressions in an array initializer are executed from left to right in the order that they occur in the
source code. The rst expression species the value at index value zero, and the last expression species the
value at index value n-1 (where n is the length of the array).
Each expression must be assignment-compatible with the array's component type, or a compiler error
will occur.
A sample program
The previous paragraphs in this module have explained some of the rules and characteristics regarding
array objects. They have also illustrated some of the syntax involved in the use of array objects in Java.
More powerful and complex
Many aspiring Java programmers nd the use of array objects to be something less than straightforward,
and that is understandable. In fact, Java array objects are somewhat more powerful than array structures
in many other programming languages, and this power often manifests itself in additional complexity.
A traditional two-dimensional rectangular array
Some of that complexity is illustrated by the program named Array07 , shown in Listing 26 (p. 761)
near the end of this module. This program illustrates three dierent ways to accomplish essentially the same
task using array objects in Java. That task is to emulate a traditional two-dimensional rectangular array as
found in other programming languages. Two of the ways that are illustrated are essentially ragged arrays
with sub-arrays having equal length.
Ragged arrays
The program also illustrates two dierent ways to work with array objects and ragged arrays.
Will discuss in fragments
As is my practice, I will discuss and explain the program in fragments.
main
All of the interesting code in this program is contained in the method, so I will begin my discussion
with the rst statement in themain method.
Create a two-dimensional rectangular array structure
Listing 10 (p. 747) creates an array structure that emulates a traditional rectangular array with two rows
and three columns.
5.116
(Note that unlike the ragged array structures to be discussed later, this approach requires all rows to be
the same length and all columns to be the same length.)
Reference variable declaration
The code to the left of the equal sign (=) in Listing 10 (p. 747) declares a reference variable named
v1 . This reference variable is capable of holding a reference to an array object whose elements are of the
type Object[] ..
In other words, this reference variable is capable of
Each of the sub-array objects has three elements. Each element is capable of storing a reference to an
object as type Object .
The leaves of the tree
These two sub-array objects might be viewed as the leaves of the tree structure.
Initialize elements to null
However, the objects of type Object don't exist yet. Therefore, each element in each of the sub-array
objects is automatically initialized to null .
Arrays versus sub-arrays
Note that there is no essential dierence between an array object and a sub-array object in the above
discussion. The use of the sub prex is used to indicate that an ordinary array object belongs to another
array object, because the reference to the sub-array object is stored in an element of the owner object.
Many dimensions are possible
Multi-dimensional arrays of any (reasonable) depth can be emulated in this manner. An array object
may contain references to other array objects, which may contain references to other array objects, and so
on.
The leaves of the tree structure
Eventually, however, the elements of the leaves in the tree structure must be specied to contain either
primitive values or references to ordinary objects. This is where the data is actually stored.
(Note however, that if the leaves are specied to contain references of type Object , they may contain
references to other array objects of any type, and the actual data could be stored in those array objects.)
The length of an array
Every array object contains a public nal instance variable named length , which contains an integer
value specifying the number of elements in the array.
Once created, the length of the array encapsulated in an array object cannot change. Therefore, the
value of length species the length of the array throughout the lifetime of the array object.
Using length to populate the leaves of the tree structure
The value of length is very handy when processing array objects. This is illustrated in Listing 11 (p.
748) , which uses a nested for loop to populate the elements in the leaves of the tree structure referred to
by v1 . (The elements in the leaf objects are populated with references to objects of type Integer .)
Listing 11: Using length to populate the leaves of the tree structure.
for(int i=0;i<v1.length;i++){
for(int j=0;j<v1[i].length;j++){
v1[i][j] =
new Integer((i+1)*(j+1));
}//end inner loop
}//end outer loop
5.117
I will also point out that the value returned by v1[i].length (in the conditional expression for the
inner loop) is the number of elements in each leaf array object (each leaf object in this tree structure has
three elements).
Finally, I will point out that the expression v1[i][j] accesses the jth element in the ith leaf, or
sub-array. In the traditional sense of a rectangular array, this could be thought of as the jth column of
the ith row. This mechanism is used to store object references in each element of each of the leaf array
objects.
Populate with references to Integer objects
Thus, each element in each leaf array object is populated with a reference to an object of the type
Integer . Each object of the type Integer encapsulates an int value calculated from the current values
of the two loop counters.
Display leaf object contents
In a similar manner, the code in Listing 12 (p. 749) uses the length values in the conditional expressions
of nested for loops to access the references stored in the elements of the leaf array objects, and to use
those references to access and display the values encapsulated in the Integer objects whose references are
stored in those elements.
for(int i=0;i<v1.length;i++){
for(int j=0;j<v1[i].length;j++){
System.out.print(
v1[i][j] + " ");
}//end inner loop
System.out.println();//new line
}//end outer loop
5.118
1 2 3
2 4 6
As you can see, this emulates a traditional two-dimensional array having two rows and three columns.
A ragged array with two rows and three columns
The second approach to emulating a traditional two-dimensional rectangular array will create a ragged
array where each row is the same length.
(It is very important to note that, unlike this case, with a ragged array, the number of elements in each
row or the number of elements in each column can be dierent.)
The most signicant thing about this approach is the manner in which the tree of array objects is created
(see Listing 13 (p. 750) ).
Listing 13: Beginning of a ragged array with two rows and three columns.
5.119
5.120
1 2 3
2 4 6
Now for something really dierent
The next approach that I am going to show you for emulating a two-dimensional rectangular array is
signicantly dierent from either of the previous two approaches.
Not element type Object[]
In this approach, I will create a one-dimensional array object of element type Object (not element
type Object[] ) . I will populate the elements of that array object with references to other array objects
Object . In doing so, I will create a tree structure similar to those discussed above.
of element type
The length of the leaf objects
As with the second approach above, the array objects that make up the leaves of the tree can be any
length, but I will make them the same length in order to emulate a traditional rectangular two-dimensional
array.
Create the array object
First consider the statement shown in Listing 15 (p. 751) . Compare this statement with the statements
shown earlier in Listing 10 (p. 747) and Listing 13 (p. 750) .
5.121
In the previous two cases, the elements of the root object were required to store references of type
Object[] (note the square brackets). In other words, an array object whose elements are of type
Object[] can only store references to other array objects whose elements are of type Object .
A more general approach
However, an array object whose elements are of type Object (as is the case here), can store:
Therefore, this is a much more general, and much more powerful approach.
A price to pay
However, there is a price to pay for the increased generality and power. In particular, the programmer who
uses this approach must have a much better understanding of Java object-oriented programming concepts
than the programmer who uses the two approaches discussed earlier in this module.
Particularly true relative to rst approach
This is particularly true relative to the rst approach discussed earlier. That approach is suciently
similar to the use of multi-dimensional arrays in other languages that a programmer with little understanding
of Java object-oriented programming concepts can probably muddle through the syntax based on prior
knowledge. However, it is unlikely that a programmer could muddle through this approach without really
understanding what she is doing.
Won't illustrate true power
Although this approach is very general and very powerful, this sample program won't attempt to illustrate
that power and generality. Rather, this sample program will use this approach to emulate a traditional two-
dimensional rectangular array just like the rst two approaches discussed earlier. (Later, I will also use this
approach for a couple of ragged arrays.)
Populate the root object
The two statements in Listing 16 (p. 752) create two array objects, each having three elements. Each
element is capable of storing a reference to any object that is assignment compatible with the Object
type.
(Assignment compatibility includes a reference to any object instantiated from any class, or a reference
to any array object of any type (including primitive types), or a mixture of the two.)
5.122
References to the two new array objects are stored in the elements of the array object that forms the
root of the tree structure. The two new array objects form the leaves of the tree structure.
Populate the leaf array objects
As in the previous two cases, the code in Listing 17 (p. 753) uses nested for loops to populate the array
elements in the leaf objects with references to new Integer (The
objects. Integer objects encapsulate
int values based on the loop counter values for the outer and inner loops.)
for(int i=0;i<v3.length;i++){
for(int j=0;j<((Object[])v3[i]).length;j++){
((Object[])v3[i])[j] = new Integer((i+1)*(j+1));
}//end inner loop
}//end outer loop
5.123
Added complexity
The added complexity of this approach manifests itself in
((Object[])v3[i]).length
Assign a value to an element in the leaf array object
Similarly, the following expression converts the reference stored in v3[i] from type Object to type
Object[] . Having made the conversion, it then accesses the jth element of the array object whose
reference is stored there (in order to assign a value to that element).
((Object[])v3[i])[j]=
Display data in leaf array objects
Listing 18 (p. 754) uses similar casts to get and display the values encapsulated in the Integer objects
whose references are stored in the elements of the leaf array objects.
for(int i=0;i<v3.length;i++){
for(int j=0;j<((Object[])v3[i]).length;j++){
System.out.print(((Object[])v3[i])[j] + " ");
}//end inner loop
System.out.println();//new line
}//end outer loop
5.124
5.125
for(int i=0;i<v4.length;i++){
for(int j=0;j<v4[i].length;j++){
v4[i][j] =
new Integer((i+1)*(j+1));
}//end inner loop
}//end outer loop
5.126
1 2
2 4 6
Note that this is not the same as before, and this output does not describe a rectangular array. Rather, it
describes a ragged array where the rows are of dierent lengths.
(As I indicated earlier, it is sort of triangular. However, it could be any shape that you might want it
to be.)
A more general approach
The next case, shown in Listing 21 (p. 756) , is the same as the third case discussed earlier, except that
the lengths of the leaf array objects are not the same.
As before, this case creates a one-dimensional array object of type Object (having two elements) that
forms the root of a tree. Each element in the root object contains a reference to another array object of type
Object .
One of those leaf objects has two elements and the other has three elements, thus producing a ragged
array (you could make the lengths of those objects anything that you want them to be).
5.127
for(int i=0;i<v5.length;i++){
for(int j=0;
j<((Object[])v5[i]).length;
j++){
((Object[])v5[i])[j] =
new Integer((i+1)*(j+1));
}//end inner loop
}//end outer loop
5.128
1 2
2 4 6
Note that this is the same as the case immediately prior to this one. Again, it does not describe a rectangular
array. Rather, it describes a ragged array where the rows are of dierent lengths.
A more general case
I'm going to show you one more general case for a ragged array. This case illustrates a more general
approach. In this case, I will create a one-dimensional array object of element type Object . I will populate
the elements of that array object with references to other array objects. These array objects will be the
leaves of the tree.
Leaf array objects are type int
In this case, the leaves won't be of element type Object . Rather, the elements in the leaf objects will
be designed to store primitive int values.
(An even more general case would be to populate the elements of the root object with references to
a mixture of objects of class types, interface types, and array objects where the elements of the array
objects are designed to store primitives of dierent types, and references of dierent types. Note, however,
each leaf array object must be designed to store a single type, but will accept for storage any type that is
assignment-compatible with the specied type for the array object.)
This case begins in Listing 23 (p. 757) , which creates the root array object, and populates its elements
with references to leaf array objects of type int .
5.129
for(int i=0;i<v6.length;i++){
for(int j=0;j<((int[])v6[i]).length;j++){
((int[])v6[i])[j] = (i+2)*(j+2);
}//end inner loop
}//end outer loop
5.130
for(int i=0;i<v6.length;i++){
for(int j=0;j<((int[])v6[i]).length;j++){
System.out.print(((int[]
5.131
The code in Listing 25 (p. 758) is very similar to what you have seen before, and there should be no
requirement for an explanation of this code.
The code in Listing 25 (p. 758) produces the following output:
4 6 8 10 12 14 16
6 9 12
I will leave it as an exercise for the student to correlate the output with the code.
5.2.13.5 Summary
When declaring a reference variable capable of referring to an array object, the array type is declared by
writing the name of an element type followed by some number of empty pairs of square brackets [].
The components in an array object may refer to other array objects. The number of bracket pairs used
in the declaration of the reference variable indicates the depth of array nesting (in the sense that array
elements can refer to other array objects).
An array's length is not part of its type or reference variable declaration.
Multi-dimensional arrays are not required to represent rectangles, cubes, etc. They can be ragged.
The normal rules of type conversion and assignment compatibility apply when creating and populating
array objects.
Object is the superclass of all other classes. Therefore, an array of element type Object is capable
of storing references to objects instantiated from any other class. The type declaration for such an array
object would be Object[] .
An array of element type Object is also capable of storing references to any other array object.
If the declared element type for the array object is one of the primitive types, the elements of the array
can be used to store values of any primitive type that is assignment compatible with the declared type
(without the requirement for a cast).
If the declared element type is the name of a class, (which may or may not be abstract), a null reference
or a reference to any object instantiated from the class or any subclass of the class may be stored in the
array element.
If the declared element type is an interface type, a null reference or a reference to any object instantiated
from any class that implements the interface can be stored in the array element.
A reference variable whose declared type is an array type does not contain an array. Rather, it contains
either null, or a reference to an array object. Declaring the reference variable does not create an array, nor
does it allocate any space for the array components.
It is possible to declare a reference to an array object and initialize it with a reference to an array object
when it is declared.
A reference to an array object can refer to dierent array objects (of the same element type and dierent
lengths) at dierent points in the execution of a program.
When declaring an array reference variable, the square brackets [] may appear as part of the type, or
following the variable name, or both.
Once an array object is created, its type and length never changes.
An array object is created by an array creation expression or an array initializer.
An array creation expression (or an array initializer) species:
The length of the array is always available as a nal instance variable named length .
An array element is accessed by an expression whose value is an array reference followed by an indexing
expression enclosed by matching square brackets.
If an attempt is made to access the array with an invalid index value, an ArrayIndexOutOfBound-
sException will be thrown.
Arrays must be indexed by integer values of the types int , short , byte , or char . An array
cannot be accessed using an index of type long .
If the elements in an array are not purposely initialized when the array is created, the array elements
will be automatically initialized with default values.
The values in the array elements may be purposely initialized when the array object is created using a
comma-separated list of expressions enclosed by matching curly brackets.
The program in this module illustrated three dierent ways to emulate traditional rectangular two-
dimensional arrays.
The program also illustrated two dierent ways to create and work with ragged arrays.
5.2.13.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
/*File Array07.java
Copyright 2002, R.G.Baldwin
-end-
5.2.14.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.14.2.1.1 Listings
• Listing 1 (p. 764) . Using the newInstance method.
• Listing 2 (p. 766) . Populate the array object.
• Listing 3 (p. 766) . Display the data.
• Listing 4 (p. 767) . An array object of type int.
• Listing 5 (p. 768) . The two-dimensional array object tree.
• Listing 6 (p. 768) . Populate the leaf elements.
• Listing 7 (p. 769) . Display the data.
• Listing 8 (p. 770) . Create, populate, and display an array object.
• Listing 9 (p. 770) . Sort and display the data.
• Listing 10 (p. 771) . Search for an existing string.
• Listing 11 (p. 771) . Search for a non-existing string.
• Listing 12 (p. 774) . Complete program listing.
5.2.14.3 Preview
This module discusses various details regarding the use of array objects in Java, including:
• A public nal variable named length , which contains the number of components of the array (length
may be positive or zero)
• A public method named clone . This method overrides the method of the same name in Object
class.
• Default versions of all the methods inherited from the class named Object , (other than clone ,
which is overridden as described above).
For the benet of the C/C++ programmers in the audience, an array of char is not a String .
(In Java, a string is an object of the String class or the StringBuer class).
Not terminated by null
String object nor an array of type char
Also, neither a is terminated by '\u0000' (the NUL character)
.
(This information is provided for the benet of C programmers who are accustomed to working with
so-called null-terminated strings. If you're not a C programmer, don't worry about this.)
A String object in Java is immutable
String object never change.
Once initialized, the contents of a Java
On the other hand, an array of type char has mutable elements. The String class provides a method
named toCharArray , which returns an array of characters containing the same character sequence as a
String .
StringBuer objects
The class named StringBuer also provides a variety of methods that work with arrays of characters.
The contents of a StringBuer object are mutable.
The Array and Arrays classes
The classes named Array and Arrays provide methods that you can use to work with array objects.
The Array class provides static methods to dynamically create and access Java arrays.
The Arrays class contains various methods for manipulating arrays (such as sorting and searching).
It also contains a static factory method that allows arrays to be viewed as lists.
A sample program named Array08
Array08 (shown in Listing 12 (p. 774) near the end of the module)
The sample program named
illustrates the use of some of these methods.
Will discuss in fragments
As usual, I will discuss this program in fragments. Essentially all of the interesting code is in the method
named main , so I will begin my discussion there. The rst few fragments will illustrate the creation,
population, and display of a one-dimensional array object whose elements contain references to objects of
type String .
The newInstance method of the Array class
The code in Listing 1 (p. 764) calls the static method of the Array class named newInstance to
create the array object and to store the object's reference in a reference variable of type Object named
v1 .
(Note that there are two overloaded versions of the newInstance method in the Array class. I will
discuss the other one later.)
Object v1 = Array.newInstance(Class.forName("java.lang.String"),
3);
5.133
• boolean.class,
• int.class,
• oat.class, etc.
5.134
5.135
No square brackets
Once again, note that no casts, and no square brackets were required in Listing 3 (p. 766) . In fact,
this approach makes it possible to deal with one-dimensional array objects using a syntax that is completely
devoid of square brackets.
Rather than using square brackets to access array elements, this is a method-oriented approach to the
use of array objects. This makes it possible to treat array objects much the same as we treat ordinary objects
in Java.
A two-dimensional rectangular array object tree
Array class to create,
Next, I will use the methods of the populate, and display a rectangular two-
dimensional array object tree, whose elements contain references to objects of the class String .
Another overloaded version of newInstance
To accomplish this, I will use the other overloaded version of the newInstance method. This version
requires a reference to an array object of type int as the second parameter.
(Note that the Sun documentation describes two dierent behaviors for this method, depending on the
whether the rst parameter represents a non-array class or interface, or represents an array type. This
sample program illustrates the rst possibility.)
The second parameter
As mentioned above, the version of the newInstance method that I am going to use requires a reference
to an array object of type int as the second parameter.
(The length of the array object of type int species the number of dimensions of the multi-dimensional
array object. The contents of the elements of the array object of type int specify the sizes of those
dimensions.)
Thus, my rst task is to create and populate an array object of type int .
An array object of type int
Listing 4 (p. 767) shows the code required to create and populate the array object of type int . This is
a one-dimensional array object having two elements (length equals 2). The rst element is populated with
the int value 2 and the second element is populated with the int value 3.
Object v2 = Array.newInstance(int.class,2);
Array.setInt(v2, 0, 2);
Array.setInt(v2, 1, 3);
5.136
Object v3 = Array.newInstance(Class.forName("java.lang.String"),
(int[])v2);
5.137
A reference to the array object at the root of the tree is stored in the reference variable of type Object
named v3 . Note that the tree is designed to store references to objects of type String .
(The number of dimensions and the size of each dimension are specied by the reference to the array
object of type int passed as the second parameter.)
Square-bracket cast is required here
The required type of the second parameter for this version of the newInstance method is int[] .
Therefore, there was no way for me to avoid the use of square brackets. I could either store the reference to
the array object as type Object and cast it before passing it to the method, (which I did), or save it
originally as type int[] , (which I didn't). Either way, I would have to know about the type int[] .
Populate the leaf elements
The nested for loop in Listing 6 (p. 768) uses the various methods of the Array class to populate
the elements in the leaf array objects with references to objects of the class String .
5.138
Admittedly, the code in Listing 6 (p. 768) is a little complex. However, there is really nothing new there,
so I won't discuss it further.
Display the data
Similarly, the code in Listing 7 (p. 769) uses the methods of the Array class in a nested for loop to
get and display the contents of the String objects whose references are stored in the elements of the leaf
array objects. Again, there is nothing new here, so I won't discuss this code further.
5.139
Object v4 = Array.newInstance(Class.forName("java.lang.String"),
8);
//Populate the array object.
// Create a gap in the data.
for(int i = 0; i < Array.getLength(v4); i++){
if(i < 4){
Array.set(v4,i,"c"+(8-i));}
else{
Array.set(v4,i,"c"+(18-i));}
}//end for loop
5.140
The output
The code in Listing 8 (p. 770) produces the following output on the screen:
Arrays.sort((Object[])v4);
5.141
The output
The code in Listing 9 (p. 770) displays the sorted contents of the array object, producing the following
output on the computer screen :
System.out.println(Arrays.binarySearch((Object[])v4,"c5"));
5.142
System.out.println(Arrays.binarySearch((Object[])v4,"c4"));
5.143
element greater than the key, or list.size(), if all elements in the list are less than the specied key. Note
that this guarantees that the return value will be >= 0 if and only if the key is found."
Thus, the negative return value indicates that the method didn't nd a match. The absolute value of
the return value can be used to determine the index of the reference to the target object if it did exist in the
sorted list. I will leave it as an exercise for the student to interpret Sun's explanation beyond this simple
explanation.
Other capabilities
In addition to sorting and searching, the Arrays class provides several other methods that can be used
to manipulate the contents of array objects in Java.
5.2.14.5 Summary
An array object has the following members (in addition to the data stored in the object):
The methods of the Array class make it possible to deal with one-dimensional array objects using a syntax
that is completely devoid of square brackets. This is a method-oriented approach to the use of array
objects. This makes it possible to treat array objects much the same as we treat ordinary objects in Java.
The required syntax for multi-dimensional array objects is mostly devoid of square brackets.
The Arrays class provides methods for sorting and searching array objects as well as performing other
operations on array objects as well.
Through a combination of the Arrays class and the Java Collections Framework, most of the sort-
ing, searching, data structures, and collection needs that you might have are readily available without a
requirement for you to reinvent them.
One of the most important concepts in OOP is reuse, don't reinvent.
5.2.14.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
/*File Array08.java
Copyright 2002, R.G.Baldwin
Rev 2/10/02
try{
//Create, populate, and display a
// one-dimensional array object
// whose elements contain
// references to objects of type
// String.
-end-
5.2.15.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.15.2.1.1 Images
• Image 1 (p. 777) . The extends keyword.
5.2.15.2.1.2 Listings
• Listing 1 (p. 779) . The program named This01.
• Listing 2 (p. 781) . The program named This02.
• Listing 3 (p. 783) . The program named This03.
• Listing 4 (p. 786) . The program named Super3.
• Listing 5 (p. 788) . The program named Super4.
5.2.15.3 Preview
This module explains the use of the keywords this and super . Short sample programs illustrate
how you can use these keywords for several purposes.
I will discuss and illustrate the use of the this keyword in the following situations:
• To bypass local variables or parameters that hide member variables having the same name, in order to
access the member variable.
• To make it possible for one overloaded constructor to call another overloaded constructor in the same
class.
37 This content is available online at <http://cnx.org/content/m44201/1.4/>.
• To pass a reference to the current object to a method belonging to a dierent object (as in implementing
callbacks, for example).
I will also discuss and illustrate the use of the super keyword in the following situations:
• To bypass the overridden version of a method in a subclass and execute the version in the superclass.
• To bypass a member variable in a subclass in order to access a member variable having the same name
in a superclass.
• To cause a constructor in a subclass to call a parameterized constructor in the immediate superclass.
• encapsulation
• inheritance
• polymorphism .
If you have been studying this series of modules on the Essence of OOP in Java, you already know quite a
lot about OOP in general, and the implementation of OOP in Java in particular.
A few more important OOP/Java concepts
However, there are a few more important concepts that I haven't previously discussed in this series of
modules. In this module, I will explain the use of the keywords this and super .
Data and methods
The class provides the plan from which objects are built. This plan denes the data that is to be
stored in an object, and the methods for manipulating that data. The data is variously referred to as data
members, elds , and variables , depending on which book you are reading.
Non-static and static
The data can be further sub-divided into non-static and static , often referred to as i nstance variables
and class variables respectively.
The methods are also often referred to as member methods , and they can also be static or non-static
. Static methods are often referred to as class methods while non-static methods are often referred to as
instance methods .
Instance variables and instance methods
The class body contains the declarations for, and possibly the initialization of all data members (both
class variables and instance variables) as well as the full denition of all methods .
In this module, we will be particularly interested in instance variables and instance methods.
Every class is a subclass of Object
By default, every class in Java extends (either directly or indirectly) the class named Object . A new
class may either extend Object , or extend another class that extends Object , or extend another class
further down the inheritance hierarchy.
The immediate parent class of a new class is known as its superclass , and the new class is known as
the subclass .
(Sometimes we use the word superclass to indicate the collection of classes in the inheritance hierarchy
from which a specic class is derived.)
If you do not specify the superclass for a new class, it will extend Object by default.
The extends keyword
extends is used in the class declaration to specify the immediate superclass
The keyword of the new
class using the syntax shown in Image 1 (p. 777) .
5.145
Inheritance
A class inherits the variables and methods of its superclass, and of the superclass of that class, etc., all
the way back up the family tree to the single class Object , which is the root of all inheritance.
Thus, an object that is instantiated from a class contains all the instance variables and all the instance
methods dened by that that class and dened by all its ancestors.
However, the methods may have been overridden one or more times along the way. Also, access to
those variables and methods may have been restricted through the use of the public , private , and
protected keywords.
(There is another access level, often referred to as package private , which is what you get when you
don't use an access keyword.)
The this keyword
Every instance method in every object in Java receives a reference named this when the method is
called. The reference named this is a reference to the object on which the method was called. It can be
used for any purpose for which such a reference is needed.
Three common situations
There are at least three common situations where such a reference is needed:
• To bypass local variables or parameters that hide member variables having the same name, in order to
access the member variable.
• To make it possible for one overloaded constructor to call another overloaded constructor in the same
class.
• To pass a reference to the current object to a method belonging to a dierent object (as in implementing
callbacks, for example).
Normally, instance methods belonging to an object have direct access to the instance variables belonging to
that object, and to the class variables belonging to the class from which that object was instantiated.
(Class methods never have access to instance variables or instance methods.)
Name can be duplicated
However, the name of a method parameter or constructor parameter can be the same as the name of an
instance variable belonging to the object or a class variable belonging to the class. It is also allowable for
the name of a local variable to be the same as the name of an instance variable or a class variable. In this
case, the local variable or the parameter is said to hide the member variable having the same name.
Reference named this is passed to instance methods
As mentioned above, whenever an instance method is called on an object, a hidden reference named this
is always passed to the method. The this reference always refers to the object on which the method was
called. This makes it possible for the code in the method to refer back to the object on which the method
was called.
The reference named this can be used to access the member variables hidden by the local variables or
parameters having of the same name.
The sample program named This01
The sample program shown in Listing 1 (p. 779) illustrates the use of the this reference to access a
hidden instance variable named myVar and a hidden class variable named yourVar .
/*File This01.java
Copyright 2002, R.G.Baldwin
Illustrates use of this keyword to
access hidden member variables.
myVar parameter = 20
local yourVar variable = 1
Instance variable myVar = 5
Class variable yourVar = 10
**************************************/
class This01 {
int myVar = 0;
static int yourVar = 0;
5.146
780 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
• When the code refers to myVar or yourVar , the reference resolves to either an incoming parameter
or to a local variable having that name.
• When the code refers to this.myVar or this.yourVar , the reference resolves to the corresponding
instance variable and class variable having that name.
To summarize this situation, every time an instance method is called, it receives a hidden reference named
this . That is a reference to the object on which the method was called.
The code in the method can use that reference to access any instance member of the object on which it
was called, or any class member of the class from which the object was instantiated.
However, when class methods are called, they do not receive such a hidden reference, and therefore, they
cannot refer to any instance members of any object instantiated from the class. They can only access class
members of the same class.
Calling other constructors of the same class
Now I am going to discuss and illustrate the second common situation listed earlier.
A class can dene two or more overloaded constructors having the same name and dierent argument
lists. Sometimes it is useful for one overloaded constructor to call another overloaded constructor in the
same class. When this is done, the constructor being called is referred to as though it were a method whose
name is this , and whose argument list matches the argument list of the constructor being called.
The sample program named This02
This situation is illustrated in the program named This02 shown in Listing 2 (p. 781) .
/*File This02.java
Copyright 2002, R.G.Baldwin
Illustrates use of this keyword for one
overloaded constructor to access
another overloaded constructor of the
same class.
class This02 {
int myVar = 0;
5.147
this(15);
This is the statement used by one overloaded constructor to call another overloaded constructor.
Callbacks
An extremely important concept in programming is the third situation mentioned in the earlier list (p.
777) . This is a situation where a method in one object calls a method in another object and passes a
reference to itself as a parameter.
(This is sometimes referred to as registration. That is to say, one object registers itself on another
object.)
The method in the second object saves the reference that it receives as an incoming parameter. This
makes it possible for a method in the second object to make a callback to the rst object sometime later.
This is illustrated in the program named This03 , shown in Listing 3 (p. 783) .
/*File This03.java
Copyright 2002, R.G.Baldwin
Illustrates using the this keyword in
a callback scenario.
class This03 {
public static void main(
String[] args){
ClassA objA = new ClassA();
ClassB objB = new ClassB();
objA.goRegister(objB);
objB.callHimBack();
objA.showData();
}//end main method
}//End This03 class definition.
//===================================//
class ClassA{
int myVar;
}//end goRegister
//---------------------------------//
void showData(){
System.out.println(
"Instance variable myVar = "
+ myVar);
}//end showData
}//end ClassA
//===================================//
class ClassB{
ClassA ref;
}//end registerMe
//---------------------------------//
784 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
• If your class overrides a method in a superclass, you can use the super keyword to bypass the
overridden version in the class and execute the version in the superclass.
• If a local variable in your method or a member variable in your class hides a member variable in the
superclass (having the same name), you can use the super keyword to access the member variable
in the superclass.
• You can also use super in a constructor of your class to call a parameterized constructor in the
superclass.
The program also uses this and super to disambiguate a local variable, an instance variable of the
subclass, and an instance variable of the superclass. All three variables have the same name.
/*File Super3.java
Copyright 2002, R.G.Baldwin
Illustrates use of super reference to
access constructor in superclass. Also
illustrates use of super to
disambiguate instance variable in
subclass from instance variable in
superclass. Illustrates use of this
to disambiguate local variable from
instance variable in subclass.
In SuperClass constructor.
Setting superclass instance var to 500
In subclass constructor.
Setting subclass instance var to 400
In main
Subclass instance var = 400
In method myMeth
Local var = 300
Subclass instance var = 400
SuperClass instance var = 500
**************************************/
class SuperClass{
int data;
//Parameterized superclass
// constructor
public SuperClass(int val){
System.out.println(
"In SuperClass constructor. ");
System.out.println(
"Setting superclass instance "
+ "var to " + val);
data = val;
System.out.println();//blank line
}//end SuperClass constructor
}//end SuperClass class definition
//===================================//
//Subclass constructor
public Super3(){
//Call parameterized SuperClass
787
The keyword super is used twice in the program in Listing 4 (p. 786) .
Call a parameterized constructor
The rst usage of the keyword super appears as the rst executable statement in the noarg constructor
for the class named Super3 . This statement reads as follows:
super(500);
This statement causes the parameterized constructor for the immediate superclass (the class named Su-
perClass ) of the class named Super3 , to be executed before the remaining code in the constructor for
Super3 is executed.
This is the mechanism by which you can cause a parameterized constructor in the immediate superclass
to be executed.
What if you don't do this?
If you don't do this, an attempt will always be made to call a noarg constructor on the superclass before
executing the remaining code in the constructor for your class.
(That is why you should almost always make certain that the classes that you dene have a noarg
constructor in addition to any parameterized constructors that you may dene.)
First executable statement in constructor
When super(parameters) is used to call the superclass constructor, it must always be the rst
executable statement in the constructor.
Whenever you call the constructor of a class to instantiate an object, if your constructor doesn't have a
call to super as the rst executable statement in the constructor, the call to the noarg constructor in
the superclass is made automatically.
In other words, in order to construct an object of a class, it is necessary to rst construct that part of the
object attributable to the superclass. That normally happens automatically, making use of the superclass
constructor that doesn't take any parameters.
Calling a parameterized constructor
If you want to use a version of the superclass constructor that takes parameters, you can make your own
call to super(parameters) as the rst executable statement in your constructor (as was done in this
program).
Accessing a superclass member variable
The second use of the super keyword in the program shown in Listing 4 (p. 786) uses the keyword to
bypass an instance variable named data in the class named Super3 , to access and display the value of
an instance variable named data in the superclass named SuperClass .
Note that in that same section of code, the this keyword is used to bypass a local variable named
data in order to display the value of an instance variable named data in the class named Super3 .
Similarly, a statement without the use of either this or super is used to display the value of a local
variable named data .
To disambiguate
Therefore, as stated earlier, the program uses this and super to disambiguate a local variable, an
instance variable of the subclass, and an instance variable of the superclass, where all three variables have
the same name.
Accessing overridden superclass method
As mentioned earlier (p. 784) , if your method overrides a method in its superclass, you can use
the keyword super to call the overridden version in the superclass, possibly completely bypassing the
overridden version in the subclass.
The program named Super4
This is illustrated by the program in Listing 5 (p. 788) . This program contains an overridden version
of a superclass method named meth . The subclass version uses the value of an incoming parameter to
decide whether to call the superclass version and then to call some of its own code, or to execute its own
code exclusively.
/*File Super4.java
Copyright 2002, R.G.Baldwin
Illustrates calling the superclass
version of an overridden method from
code in the subclass version.
In main
Entering overridden method in subclass
Incoming parameter is false
Subclass version only is called
Back in or still in subclass version
Goodbye from subclass version
Back in main
**************************************/
class SuperClass{
//Following method is overridden in
// the subclass.
void meth(boolean par){
System.out.println(
"Incoming parameter is " + par);
System.out.println(
"SuperClass method called");
}//end meth
}//end SuperClass class definition
//===================================//
System.out.println(
"Incoming parameter is " + par);
System.out.println(
789
super.meth(par);
This statement is inside the body of an if statement. If the value of par is true, then this statement is
executed, causing the superclass version of the method named meth to be executed (passing the value
of par as a parameter to the superclass method). When the method returns, the remaining code in the
subclass version of the method is executed.
If the value of par is false, the above statement is bypassed, and the superclass version of the method
doesn't get executed. In this case, only the code in the subclass version is executed.
5.2.15.5 Summary
I have discussed and illustrated the use of the this keyword in the following common situations:
• To bypass local variables or parameters that hide member variables having the same name, in order to
access the member variable.
• To make it possible for one overloaded constructor to call another overloaded constructor in the same
class.
• To pass a reference to the current object to a method belonging to a dierent object (as in implementing
callbacks, for example).
I have also discussed and illustrated the use of the super keyword in the following situations:
• To bypass the overridden version of a method in a subclass and execute the version in the superclass.
• To bypass a member variable in a subclass in order to access a member variable having the same name
in a superclass.
• To cause a constructor in a subclass to call a parameterized constructor in the immediate superclass.
5.2.15.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.2.16.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.2.16.2.1.1 Images
• Image 1 (p. 793) . Throwable constructors.
• Image 2 (p. 794) . Methods of the Throwable class.
• Image 3 (p. 798) . Compiler error from an unhandled checked exception.
• Image 4 (p. 799) . Another compiler error.
• Image 5 (p. 803) . Output from program that throws ArithmeticException.
• Image 6 (p. 804) . Syntax of a try block.
• Image 7 (p. 805) . Syntax of a catch block.
• Image 8 (p. 808) . Output produced by the nally block.
• Image 9 (p. 808) . Syntax for declaring that a method throws exceptions.
• Image 10 (p. 809) . Example of a throw statement.
• Image 11 (p. 811) . Output from the for loop.
• Image 12 (p. 812) . Output from the exception handler.
• Image 13 (p. 813) . Output from code following the catch block.
5.2.16.2.1.2 Listings
• Listing 1 (p. 797) . Sample program with no exception handling code.
• Listing 2 (p. 798) . Sample program that xes one compiler error.
• Listing 3 (p. 800) . Sample program that xes the remaining compiler error.
• Listing 4 (p. 802) . A sample program that throws an exception.
• Listing 5 (p. 807) . The power of the nally block.
• Listing 6 (p. 810) . The class named MyException.
• Listing 7 (p. 811) . The try block.
• Listing 8 (p. 812) . A matching catch block.
• Listing 9 (p. 812) . Code following the catch block.
• Listing 10 (p. 814) . Complete program listing for Excep16.
5.2.16.3 Preview
This module explains Exception Handling in Java. The discussion includes the following topics:
• What is an exception?
• How do you throw and catch exceptions?
• What do you do with an exception once you have caught it?
• How do you make use of the exception class hierarchy provided by the Java development environment?
This module will cover many of the details having to do with exception handling in Java. By the end of the
module, you should know that the use of exception handling is not optional in Java, and you should have a
pretty good idea how to use exception handling in a benecial way.
• You try to execute the statements contained within a block of code. (A block of code is a group of
one or more statements surrounded by curly brackets.)
• If you detect an exceptional condition within that block, you throw an exception object of a specic
type.
• You catch and process the exception object using code that you have designed.
• You optionally execute a block of code, designated by nally , which needs to be executed whether
or not an exception occurs. (Code in the nally block is normally used to perform some type of
cleanup.)
For example, the read method of the InputStream class throws an exception of type IOException
if an exception occurs while the read method is executing. In this case, you are responsible only for the
code in the catch block and optionally for the code in the nally block.
(This is the reason that you must surround the call to System.in.read() with a try block followed
by a catch block, or optionally declare that your method throws an exception of type IOException
.)
Exception hierarchy, an overview
When an exceptional condition causes an exception to be thrown , that exception is represented by an
object instantiated from the class named Throwable or one of its subclasses.
Here is part of what Sun has to say about the Throwable class:
"The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects
that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be
thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument
type in a catch clause."
Sun goes on to say:
"Instances of two subclasses, Error and Exception , are conventionally used to indicate that
exceptional situations have occurred. Typically, these instances are freshly created in the context of the
exceptional situation so as to include relevant information (such as stack trace data)."
The Error and Exception classes
The virtual machine and many dierent methods in many dierent classes throw exceptions and errors
. I will have quite a lot more to say about the classes named Error and Exception later in this module.
Dening your own exception types
You may have concluded from the Sun quotation given above that you can dene and throw exception
objects of your own design, and if you did, that is a correct conclusion. (Your new class must extend
Throwable or one of its subclasses.)
The dierence between Error and Exception
As mentioned above, the Throwable class has two subclasses:
• Error
• Exception
What is an error?
What is the dierence between an Error and an Exception ? Paraphrasing David Flanagan and
his excellent series of books entitled Java in a Nutshell , an Error indicates that a non-recoverable error
has occurred that should not be caught. Errors usually cause the Java virtual machine to display a message
and exit.
Sun says the same thing in a slightly dierent way:
"An Error is a subclass of Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions."
For example, one of the subclasses of Error is named VirtualMachineError . This error is "Thrown
to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue
operating. "
What is an exception?
Paraphrasing Flanagan again, an Exception indicates an abnormal condition that must be properly
handled to prevent program termination.
Sun explains it this way:
"The class Exception and its subclasses are a form of Throwable that indicates conditions that a
reasonable application might want to catch."
As of JDK 1.4.0, there are more than fty known subclasses of the Exception class. Many of these
subclasses themselves have numerous subclasses, so there is quite a lot of material that you need to become
familiar with.
The RuntimeException class
One subclass of Exception is the class named RuntimeException As of JDK 1.4.0, this class has
about 30 subclasses, many which are further subclassed. The class named RuntimeException is a very
important class.
Unchecked exceptions
The RuntimeException class, and its subclasses, are important not so much for what they do, but
for what they don't do. I will refer to exceptions instantiated from RuntimeException and its subclasses
as unchecked exceptions.
Basically, an unchecked exception is a type of exception that you can optionally handle, or ignore. If you
elect to ignore the possibility of an unchecked exception, and one occurs, your program will terminate as a
result. If you elect to handle an unchecked exception and one occurs, the result will depend on the code that
you have written to handle the exception.
Checked exceptions
All exceptions instantiated from the Exception class, or from subclasses of Exception other than
RuntimeException and its subclasses must either be:
Throwable()
Throwable(String message)
Throwable(String message,Throwable cause)
Throwable(Throwable cause)
5.151
The rst two constructors have been in Java for a very long time. Basically, these two constructors allow
you to construct an exception object with, or without a String message encapsulated in the object.
New to JDK 1.4
The last two constructors are new in JDK 1.4.0. These two constructors are provided to support the
cause facility. The cause facility is new in release 1.4. It is also known as the chained exception 39
facility. (I won't cover this facility in this module. Rather, I plan to cover it in a series of future modules.)
Methods of the Throwable class
39 http://softwaredev.earthweb.com/java/article/012082_1431531_1,00.html
Image 2 (p. 794) shows some of the methods of the Throwable class. (I omitted some of the methods
introduced in JDK 1.4 for the reasons given above.)
fillInStackTrace()
getStackTrace()
printStackTrace().
setStackTrace(StackTraceElement[] stackTrace)
getLocalizedMessage()
getMessage()
toString()
5.152
The StackTrace
The rst four methods in Image 2 (p. 794) deal with theStackTrace . In case you are unfamiliar with
the term StackTrace, this is a list of the methods executed in sequence that led to the exception. (This
is what you typically see on the screen when your program aborts with a runtime error that hasn't been
handled.)
Messages
The two methods dealing with messages provide access to a String message that may be encapsulated
in the exception object. The getMessage class simply returns the message that was encapsulated when
the object was instantiated. (If no message was encapsulated, this method returns null.)
The getLocalizedMessage method is a little more complicated to use. According to Sun, "Subclasses
may override this method in order to produce a locale-specic message."
The toString method
The toString method is inherited from the Object class and overridden in the exception subclass
to "return a short description of the Throwable ".
Inherited methods
All exception objects inherit the methods of the Throwable class, which are listed in Image 2 (p. 794)
. Thus, any of these methods may be called by the code in the catch block in its attempt to successfully
handle the exception.
For example, exceptions may have a message encapsulated in the exception object, which can be accessed
using the getMessage method. You can use this to display a message describing the error or exception.
You can also use other methods of the Throwable class to:
When an exceptional condition occurs within a method, the method may instantiate an exception object
and hand it o to the runtime system to deal with it. This is accomplished using the throw keyword.
(This is called throwing an exception.)
To be useful, the exception object should probably contain information about the exception, including
its type and the state of the program when the exception occurred.
Handling the exception
At that point, the runtime system becomes responsible for nding a block of code designed to handle the
exception.
The runtime system begins its search with the method in which the exception occurred and searches
backwards through the call stack until it nds a method that contains an appropriate exception handler
(catch block).
An exception handler is appropriate if the type of the exception thrown is the same as the type of
exception handled by the handler, or is a subclass of the type of exception handled by the handler.
Thus, the requirement to handle an exception that has been thrown progresses up through the call stack
until an appropriate handler is found to handle the exception. If no appropriate handler is found, the runtime
system and the program terminate.
(If you have ever had a program terminate with a NullPointerException , then you know how
program termination works).
According to the jargon, the exception handler that is chosen is said to catch the exception.
Advantages of using exception handling
According to Campione and Walrath, exception handling provides the following advantages over "tradi-
tional" error management techniques:
When an exception is thrown, an object of one of the exception classes is passed as a parameter. Objects
are instances of classes, and classes fall into an inheritance hierarchy in Java. Therefore, a natural hierarchy
can be created, which causes exceptions to be grouped in logical ways.
For example, going back to the stack example, you might create an exception class that applies to all
exceptional conditions associated with an object of your stack class. Then you might extend that class into
other classes that pertain to specic exceptional conditions, such as push exceptions, pop exceptions, and
initialization exceptions.
When your code throws an exception object of a specic type, that object can be caught by an exception
handler designed either to:
In other words, an exception handler can catch exceptions of the class specied by the type of its parameter,
or can catch exceptions of any subclass of the class specied by the type of its parameter.
More detailed information on exception handling
Throwable objects of type Error and for Throwable.Exception
As explained earlier, except for
objects of type RuntimeException , Java programs must either handle or declare all Exception
objects that are thrown. Otherwise, the compiler will refuse to compile the program.
In other words, all exceptions other than those specied above are checked by the compiler, and the
compiler will refuse to compile the program if the exceptions aren't handled or declared. As a result,
exceptions other than those specied above are often referred to as checked exceptions.
Catching an exception
Just to make certain that we are using the same terminology, a method catches an exception by providing
an exception handler whose parameter type is appropriate for that type of exception object. (I will more
or less use the terms catch block and exception handler interchangeably.)
The type of the parameter in the catch block must be the class from which the exception was instan-
tiated, or a superclass of that class that resides somewhere between that class and the Throwable class
in the inheritance hierarchy.
Declaring an exception
If the code in a method can throw a checked exception, and the method does not provide an exception
handler for the type of exception object thrown, the method must declare that it can throw that exception.
The throws keyword is used in the method declaration to declare that it throws an exception of a
particular type.
Any checked exception that can be thrown by a method is part of the method's programming interface
(see the read method of the InputStream class, which throws IOException , for example). Users
of a method must know about the exceptions that a method can throw in order to be able to handle them.
Thus, you must declare the exceptions that the method can throw in the method signature.
Checked exceptions
Checked exceptions are all exception objects instantiated from subclasses of the Exception class other
than those of the RuntimeException class.
Exceptions of all Exception subclasses other than RuntimeException are checked by the compiler
and will result in compiler errors if they are neither caught nor declared .
You will learn how you can create your own exception classes later. Whether your exception objects
become checked or not depends on the class that you extend when you dene your exception class.
(If you extend a checked exception class, your new exception type will be a checked exception. Otherwise,
it will not be a checked exception.)
Exceptions that can be thrown within the scope of a method
The exceptions that can be thrown within the scope of a method include not only exceptions which are
thrown by code written into the method, but also includes exceptions thrown by methods called by that
method, or methods called by those methods, etc.
/*File Excep11.java
Copyright 2002, R.G.Baldwin
Tested using JDK 1.4.0 under Win2000
**************************************/
import java.lang.Thread;
class Excep11{
public static void main(
String[] args){
Excep11 obj = new Excep11();
obj.myMethod();
}//end main
//---------------------------------//
void myMethod(){
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep11
5.153
A possible InterruptedException
The code in the main method of Listing 1 (p. 797) calls the method named myMethod . The
method named myMethod calls the method named sleep of the Thread class. The method named
sleep declares that it throws InterruptedException .
InterruptedException is a checked exception. The program illustrates the failure to either catch or
declare InterruptedException in the method named myMethod .
As a result, this program won't compile. The compiler error is similar to that shown in Image 3 (p. 798)
. Note the caret in the last line that points to the point where the compiler detected the problem.
unreported exception
java.lang.InterruptedException;
must be caught or declared to be thrown
Thread.currentThread().sleep(1000);
^
5.154
As you can see, the compiler detected a problem where the sleep method was called, because the
method named myMethod failed to deal properly with an exception that can be thrown by the sleep
method.
Sample program that xes one compiler error
The next version of the program, shown in Listing 2 (p. 798) , xes the problem identied with the call
to the sleep method, by declaring the exception in the signature for the method named myMethod .
/*File Excep12.java
Copyright 2002, R.G.Baldwin
Tested using JDK 1.4.0 under Win2000
**************************************/
import java.lang.Thread;
class Excep12{
public static void main(
String[] args){
Excep12 obj = new Excep12();
obj.myMethod();
}//end main
//---------------------------------//
void myMethod()
throws InterruptedException{
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep12
5.155
InterruptedException . However, in this case, the problem has moved up one level in the call stack
relative to the problem with the program in Listing 1 (p. 797) .
This program also fails to compile, producing a compiler error similar to that shown in Image 4 (p. 799)
. Note that the caret indicates that the problem is associated with the call to myMethod .
unreported exception
java.lang.InterruptedException;
must be caught or declared to be thrown
obj.myMethod();
^
5.156
/*File Excep13.java
Copyright 2002, R.G.Baldwin
class Excep13{
public static void main(
String[] args){
Excep13 obj = new Excep13();
try{//begin try block
obj.myMethod();
}catch(InterruptedException e){
System.out.println(
"Handle exception here");
}//end catch block
}//end main
//---------------------------------//
void myMethod()
throws InterruptedException{
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep13
5.157
• If such a catch block can be found, immediately transfer control to the catch block without executing
any of the remaining code in the try block.
(For simplicity, this program didn't have any remaining code. Some later sample programs will illustrate
code being skipped due to the occurrence of an exception.)
Not a method call
Note that this transfer of control is not a method call. It is an unconditional transfer of control. There
is no return from a catch block.
Matching catch block was found
In this case, there was a matching catch block to receive control. In the event that an Interrupt-
edException is thrown, the program would execute the statement within the body of the catch block,
and then transfer control to the code following the nal catch block in the group of catch blocks (in
this case, there was only one catch block).
No output is produced
It is unlikely that you will see any output when you run this program, because it is unlikely that an
InterruptedException will be thrown. (I didn't provide any code that will cause such an exception to
occur.)
A sample program that throws an exception
Now let's look at the sample program in Listing 4 (p. 802) , which throws an exception and deals with
it. This program illustrates the implementation of exception handling using the try/catch block structure.
/*File Excep14.java
Copyright 2002, R. G. Baldwin
class Excep14{
public static void main(
String[] args){
try{
for(int cnt = 2; cnt >-1; cnt--){
System.out.println(
"Running. Quotient is: "
+ 6/cnt);
}//end for-loop
}//end try block
catch(ArithmeticException e){
System.out.println(
"Exception message is: "
+ e.getMessage()
+ "\nStacktrace shows:");
e.printStackTrace();
System.out.println(
"String representation is\n " +
e.toString());
System.out.println(
"Put corrective action here");
}//end catch block
System.out.println(
"Out of catch block");
}//end main
5.158
Keeping it simple
I try to keep my sample programs as simple as possible, introducing the minimum amount of complexity
necessary to illustrate the main point of the program. It is easy to write a really simple program that
throws an unchecked ArithmeticException . Therefore, the program in Listing 4 (p. 802) was written
to throw an ArithmeticException . This was accomplished by trying to perform an integer divide by
zero.
The try/catch structure is the same ...
It is important to note that the try/catch structure illustrated in Listing 4 (p. 802) would be the same
whether the exception is checked or unchecked. The main dierence is that you are not required by the
compiler to handle unchecked exceptions and you are required by the compiler to either handle or declare
checked exceptions.
Throwing an ArithmeticException
The code in Listing 4 (p. 802) executes a simple counting loop inside a try block. During each iteration,
the counting loop divides the integer 6 by the value of the counter. When the value of the counter goes to
zero, the runtime system tries to perform an integer divide by zero operation, which causes it to throw an
ArithmeticException .
Transfer control immediately
At that point, control is transferred directly to the catch block that follows the try block. This is
an appropriate catch block because the type of parameter declared for the catch block is Arith-
meticException . It matches the type of the object that is thrown.
(It would also be appropriate if the declared type of the parameter were a superclass of ArithmeticEx-
ception , up to and including the class named Throwable . Throwable is a direct subclass of Object
. If you were to declare the parameter type for the catch block as Object , the compiler would produce
an incompatible type error.)
Calling methods inside the catch block
Once control enters the catch block, three of the methods of the Throwable class are called to
cause information about the situation to be displayed on the screen. The output produced by the program
is similar to that shown in Image 5 (p. 803) .
5.159
try{
//java statements
}//end try block
5.160
Thus a try block consisting of a single statement might require many dierent exception handlers or
catch blocks following it.
Multiple statements and multiple exceptions
You could put all or several of the statements that might throw exceptions within a single try block
and associate multiple exception handlers with it. There are a number of practical issues involved here, and
only you can decide in any particular instance which approach would be best.
The catch blocks must follow the try block
However you decide to do it, the exception handlers associated with a try block must be placed
immediately following their associated try block. If an exception occurs within the try block, that
exception is handled by the appropriate exception handler associated with the try block. If there is no
appropriate exception handler associated with the try block, the system attempts to nd an appropriate
exception handler in the next method up the call stack.
A try block must be accompanied by at least one catch block (or one nally block). Otherwise,
a compiler error that reads something like 'try' without 'catch' or 'nally' will occur.
The catch block(s)
Continuing with what Campione and Walrath have to say:
"Next, you associate exception handlers with a try block by providing one or more catch blocks directly
after the try block."
There can be no intervening code between the end of the try block and the beginning of the rst
catch block, and no intervening code between catch blocks.
Syntax of a catch block
The general form of a catch block is shown in Image 7 (p. 805) .
catch(ThrowableObjectType paramName){
//Java statements to handle the
// exception
}//end catch block
5.161
The declaration for the catch block requires a single argument as shown. The syntax for the argument
declaration is the same as an argument declaration for a method.
Argument type species type of matching exception object
The argument type declares the type of exception object that a particular catch block can handle. The
Throwable , or a subclass of the Throwable
type must be class discussed earlier.
A parameter provides the local name
Also, as in a method declaration, there is a parameter, which is the name by which the handler can refer
to the exception object. For example, in an earlier program, I used statements such as e.getMessage() to
access an instance method of an exception object caught by the exception handler. In that case, the name
of the parameter was e .
You access the instance variables and methods of exception objects the same way that you access the
instance variables and methods of other objects.
Proper order of catch blocks
According to Campione and Walrath:
"The catch block contains a series of legal Java statements. These statements are executed if and when
the exception handler is called. The runtime system calls the exception handler when the handler is the rst
one in the call stack whose type matches that of the exception thrown."
Therefore, the order of your exception handlers is very important, particularly if you have some handlers,
which are further up the exception hierarchy than others.
Those handlers that are designed to handle exception types furthermost from the root of the hierarchy
tree ( Throwable ) should be placed rst in the list of exception handlers.
Otherwise, an exception handler designed to handle a specic type of object may be preempted by another
handler whose exception type is a superclass of that type, if the superclass exception handler appears earlier
in the list of exception handlers.
Catching multiple exception types with one handler
Exception handlers that you write may be more or less specialized. In addition to writing handlers for
very specialized exception objects, the Java language allows you to write general exception handlers that
handle multiple types of exceptions.
A hierarchy of Throwable classes
Throwable objects (instances of the Throwable class or a subclass of the
Java exceptions are
Throwable class).
The Java standard library contains numerous classes that are subclasses of Throwable and thus build
a hierarchy of Throwable classes.
According to Campione and Walrath:
"Your exception handler can be written to handle any class that inherits from Throwable . If you
write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only
handle exceptions of that specic type. If you write a handler for a "node" class (a class with subclasses),
you've written a general handler: it will handle any exception whose type is the node class or any of its
subclasses."
You have a choice
Therefore, when writing exception handlers, you have a choice. You can write a handler whose exception
type corresponds to a node in the inheritance hierarchy, and it will be appropriate to catch exceptions of
that type, or any subclass of that type.
Alternately, you can write a handler whose exception type corresponds to a leaf, in which case, it will
be appropriate to catch exceptions of that type only.
And nally, you can mix and match, writing some exception handlers whose type corresponds to a node,
and other exception handlers whose type corresponds to a leaf. In all cases, however, be sure to position
your exception handlers in reverse subclass order, with the furthermost subclass from the root appearing
rst, and the root class appearing last.
The nally block
(no pun intended), Campione and Walrath tell us:
And nally
"Java's nally block provides a mechanism that allows your method to clean up after itself regardless of
what happens within the try block. Use the nally block to close les or release other system resources."
To elaborate, the nally block can be used to provide a mechanism for cleaning up open les, etc.,
before allowing control to be passed to a dierent part of the program. You accomplish this by writing the
cleanup code within a nally block.
Code in nally block is always executed
It is important to remember that the runtime system always executes the code within the nally block
regardless of what happens within the try block.
If no exceptions are thrown, none of the code in catch blocks is executed, but the code in the nally
block is executed.
If an exception is thrown and the code in an exception handler is executed, once the execution of that
code is complete, control is passed to the nally block and the code in the nally block is executed.
(There is one important exception to the above. If the code in the catch block terminates the program
by executing System.exit(0) , the code in the nally block will not be executed.)
/*File Excep15.java
Copyright 2002, R. G. Baldwin
class Excep15{
public static void main(
String[] args){
new Excep15().aMethod();
}//end main
//---------------------------------//
void aMethod(){
try{
int x = 5/0;
}//end try block
catch(ArithmeticException e){
System.out.println(
"In catch, terminating aMethod");
return;
}//end catch block
finally{
System.out.println(
"Executing finally block");
}//end finally block
System.out.println(
"Out of catch block");
}//end aMethod
5.162
executed. Then control is transferred to the main method, which called this method in the rst place.
Image 8 (p. 808) shows the output produced by this program.
5.163
5.164
Assuming that these are checked exceptions, any method calling this method would be required to either
handle these exception types, or continue passing them up the call stack. Eventually, some method must
handle them or the program won't compile.
(Note however that while it might not represent good programming practice, it is allowable to declare
that the main method throws exceptions. This is a way to avoid handling checked exceptions and still
get your program to compile.)
The throw keyword
catch
Before your code can an exception, some Java code must throw one. The exception can be
thrown by code that you write, or by code that you are using that was written by someone else.
Regardless of who wrote the code that throws the exception, it's always thrown with the Java throw
keyword. At least that is true for exceptions that are thrown by code written in the Java language.
(Exceptions such as ArithmeticException are also thrown by the runtime system, which is probably
not written using Java source code.)
A single argument is required
When formed into a statement, the throw keyword requires a single argument, which must be a
reference to an object instantiated from the Throwable class, or any subclass of the Throwable class.
Image 10 (p. 809) shows an example of such a statement.
5.165
If you attempt to throw an object that is not instantiated from Throwable or one of its subclasses,
the compiler will refuse to compile your program.
Dening your own exception classes
Now you know how to write exception handlers for those exception objects that are thrown by the runtime
system, and thrown by methods in the standard class library.
It is also possible for you to dene your own exception classes, and to cause objects of those classes to be
thrown whenever an exception occurs. In this case, you get to decide just what constitutes an exceptional
condition.
For example, you could write a data-processing application that processes integer data obtained via a
TCP/IP link from another computer. If the specication for the program indicates that the integer value 10
should never be received, you could use an occurrence of the integer value 10 to cause an exception object
of your own design to be thrown.
Choosing the exception type to throw
Before throwing an exception, you must decide on its type. Basically, you have two choices in this regard:
• Use an exception class written by someone else, such as the myriad of exception classes dened in the
Java standard library.
• Dene an exception class of your own.
An important question
So, an important question is, when should you dene your own exception classes and when should you
use classes that are already available. Because this is only one of many design issues, I'm not going to try
to give you a ready answer to the question. However, I will refer you to The Java Tutorial
42 by Campione
and Walrath where you will nd a checklist to help you make this decision.
Choosing a superclass to extend
If you decide to dene your own exception class, it must be a subclass of Throwable . You must decide
which class you will extend.
The two existing subclasses of Throwable are Exception and Error . Given the earlier description
of Error and its subclasses, it is not likely that your exceptions would t the Error category. (In
concept, errors are reserved for serious hard errors that occur deep within the system.)
Checked or unchecked exception
42 http://java.sun.com/docs/books/tutorial/
Therefore, your new class should probably be a subclass of Exception . If you make it a subclass of
RuntimeException , it won't be a checked exception. If you make it a subclass of Exception , but not
a subclass of RuntimeException , it will be a checked exception.
Only you can decide how far down the Exception hierarchy you want to go before creating a new
branch of exception classes that are unique to your application.
Naming conventions
Many Java programmers append the word Exception to the end of all class names that are subclasses
of Exception , and append the word Error to the end of all class names that are subclasses of Error .
One more sample program
Let's wrap up this module with one more sample program named Excep16 . We will dene our own
exception class in this program. Then we will throw , catch and process an exception object instantiated
from that class.
Discuss in fragments
This program is a little longer than the previous programs, so I will break it down and discuss it in
fragments. A complete listing of the program is shown in Listing 10 (p. 814) .
The class denition shown in Listing 6 (p. 810) is used to construct a custom exception object that
encapsulates a message. Note that this class extends Exception . (Therefore, it is a checked exception.)
5.166
The constructor for this class receives an incoming String message parameter and passes it to the
constructor for the superclass. This makes the message available for access by the getMessage method
called in the catch block.
The try block
Listing 7 (p. 811) shows the beginning of the main method, including the entire try block
5.167
The main method executes a for loop (inside the try block) that guarantees that the variable
named cnt will reach a value of 3 after a couple of iterations.
Once during each iteration, (until the value of cnt reaches 3) a print statement inside the for loop
displays the value of cnt . This results in the output shown in Image 11 (p. 811) .
5.168
catch(MyException e){
System.out.println(
"In exception handler, "
+ "get the message\n"
+ e.getMessage());
}//end catch block
5.169
When the throw statement is executed in Listing 7 (p. 811) , control is transferred immediately to the
catch block in Listing 8 (p. 812) . No further code is executed within the try block.
A reference to the object instantiated as the argument to the throw keyword in Listing 7 (p. 811) is
passed as a parameter to thecatch block. That reference is known locally by the name e inside the
catch block.
Using the incoming parameter
The code in the catch block calls the method named getMessage (inherited from the Throwable
class) on the incoming parameter and displays that message on the screen. This produces the output shown
in Image 12 (p. 812) .
5.170
System.out.println(
"Out of catch block");
}//end main
}//end class Excep16
5.171
That executable statement is a print statement that produces the output shown in Image 13 (p. 813) .
5.172
/*File Excep16.java
Copyright 2002, R. G. Baldwin
Illustrates defining, throwing,
catching, and processing a custom
exception object that contains a
message.
5.2.16.5 Summary
This module has covered many of the details having to do with exception handling in Java. By now, you
should know that the use of exception handling is not optional in Java, and you should have a pretty good
idea how to use exception handling in a benecial way.
Along the way, the discussion has included the following topics:
• What is an exception?
• How do you throw and catch exceptions?
• What do you do with an exception once you have caught it?
• How do you make use of the exception class hierarchy provided by the Java development environment?
5.2.16.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3 Multimedia
5.3.1 Java3000: The Guzdial-Ericson Multimedia Class Library43
5.3.1.1 Table of Contents
• Preface (p. 816)
5.3.1.2 Preface
In the weeks and months to come, I will publish several modules that use a multimedia class library developed
and made available by Mark Guzdial
44 and Barbara Ericson 45 of the Georgia Institute of Technology. The
purpose of this module is to provide the information that you will need to obtain and use a copy of that
library.
5.3.1.3.2 Listings
• Listing 1 (p. 821) . A text version of Hello World.
• Listing 2 (p. 822) . A graphic version of Hello World.
5.3.1.4 Preview
Among other things, the Guzdial-Ericson multimedia class library makes it practical to write object-oriented
programs for the manipulation of images in an interesting and educational way. For example, the image in
Image 1 (p. 817) was produced by manipulating and merging the images shown in Image 2 (p. 818) and
Image 3 (p. 819) .
44 http://www.cc.gatech.edu/∼guzdial/
45 http://coweb.cc.gatech.edu/ice-gt/8
5.174
5.175
5.176
5.3.1.5 Discussion
The Guzdial-Ericson library was originally published by Guzdial and Ericson in conjunction with their book
Introduction to Computing and Programming with Java: A Multimedia Approach
46 . While the book isn't
free, the library is freely available and is published under a Creative Commons Attribution 3.0 United States
License
47 .
As of July, 2012, the latest version of the library can be downloaded in a zip le named bookClasses-
3-9-10-with-doc.zip at http://home.cc.gatech.edu/TeaParty/47.
48 Additional information is available
at http://coweb.cc.gatech.edu/mediaComp-plan/101
49 .
Download the library
In order to work with the programs in the modules that use the library, you will need to download a
copy of the latest version of the library from the site listed above. To guard against the possibility of that
46 http://www.pearsonhighered.com/educator/academic/product/0,3110,0131496980,00.html
47 http://creativecommons.org/licenses/by/3.0/us/
48 http://home.cc.gatech.edu/TeaParty/47.
49 http://coweb.cc.gatech.edu/mediaComp-plan/101
link becoming broken at some point in the future, I am depositing a backup copy of the zip le containing
the library on the cnx.org site and you can download it here
50 .
Prepare the library for use
Once you have downloaded the zip le, you will need to extract the folder named bookClasses from
the zip le and store it somewhere on your computer's disk.
Library documentation
When you examine the contents of the bookClasses folder, you will see that in addition to source code
and compiled class les for the library, the folder also contains javadoc documentation for the library in
a folder named doc and some other material as well. Go to the doc folder and open the le named
index.html in your browser to view the documentation.
Put the library on the classpath
You will need to put the path to the bookClasses folder on your classpath in order to incorporate
classes from the library into your programs.
del *.class
javac -cp .;M:\bookClasses *.java
java -cp .;M:\bookClasses Prob01
5.177
For example, Image 4 (p. 820) shows three commands that you can execute at a Windows command
prompt to
(The commands shown in Image 4 (p. 820) assume that the bookClasses folder is in the root
directory on the M-drive. The bookClasses folder will likely be in a dierent location on your computer.
They also assume that you are compiling and running a program having its main method in a class named
Prob01 in a le named Prob01.java .)
Be sure to include the period and the semicolon shown before the M in Image 4 (p. 820) . This tells the
Java compiler and the Java Virtual Machine to search rst in the current folder before searching elsewhere
on the disk for the required les.
You can also put the three commands in a batch le and run the batch le to avoid having to type the
three commands each time you need to compile and run the program. In that case, you should add a pause
command following the other three commands.
If you are using an IDE such as DrJava, JCreator, or JGrasp, see the instructions for the IDE to learn
how to set the classpath in the IDE.
50 http://cnx.org/content/m44148/latest/bookClasses-3-9-10-with-doc.zip
Ericson's library. This version can be used to conrm that the Java Development Kit (JDK) is properly
installed on your computer.
The second version is a graphic version that does require Ericson's library. This version can be used to
conrm proper installation and use of the library.
class TextHelloWorld{
public static void main(String[] args){
System.out.println("Text Hello World");
}//end main
}//end class
5.178
As mentioned above, this program does not require the use of Ericson's library. It can be compiled and
executed using a batch le containing the commands shown in Image 5 (p. 821) . You should make certain
that you can compile and execute this program before progressing to the graphic version.
echo off
del *.class
javac TextHelloWorld.java
java TextHelloWorld
pause
5.179
import java.awt.Color;
class GraphicHelloWorld{
public static void main(String[] args){
Picture pix = new Picture(200,100);
pix.setAllPixelsToAColor(Color.RED);
pix.addMessage("Graphic Hello World",15,50);
pix.show();
}// end main
}//end class
5.180
The program shown in Listing 2 (p. 822) causes the image shown in Image 6 (p. 822) to be displayed
when the program is compiled and executed.
5.181
As mentioned above, this program does require the use of Ericson's library. It can be compiled and
executed using a batch le containing the commands shown in Image 7 (p. 823) . You should make certain
that you can compile and execute this program before progressing to more complex programs involving
Ericson's library.
echo off
del *.class
javac -cp .;M:\bookClasses GraphicHelloWorld.java
java -cp .;M:\bookClasses GraphicHelloWorld
pause
5.182
(Once again, the commands shown in Image 7 (p. 823) assume that the bookClasses folder is
in the root directory on the M-drive. The bookClasses folder will likely be in a dierent location on
your computer.)
5.3.1.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
-end-
· 1 (p. 824) , 2 (p. 824) , 3 (p. 824) , 4 (p. 824) , 5 (p. 824) , 6 (p. 825) , 7 (p. 825) , 8 (p. 825) ,
9 (p. 825) , 10 (p. 826) , 11 (p. 826) , 12 (p. 827)
5.3.2.2 Preface
This module contains review questions and answers keyed to the module titled Java3000: The Guzdial-
Ericson Multimedia Class Library
52 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.2.3 Questions
5.3.2.3.1 Question 1 .
True or false? The multimedia library used in this course originated at MIT.
Answer 1 (p. 830)
5.3.2.3.2 Question 2
True or false? Among other things, the Guzdial-Ericson multimedia class library makes it practical to write
object-oriented programs for the manipulation of images in an interesting and educational way.
Answer 2 (p. 830)
5.3.2.3.3 Question 3
True or false? The textbook for the course is available at no cost.
Answer 3 (p. 830)
5.3.2.3.4 Question 4
True or false? Once you have downloaded the zip le containing the library, you will need to extract the
folder named MediaComp from the zip le and store it somewhere on your computer's disk.
Answer 4 (p. 830)
5.3.2.3.5 Question 5
True or false? The bookClasses folder contains javadoc documentation for the library in a folder
named doc . You can view the documentation by going to the doc folder and opening the le named
index.html in your browser.
Answer 5 (p. 830)
5.3.2.3.6 Question 6
True or false? You will need to put the path to the bookClasses folder on your path in order to
incorporate classes from the library into your programs.
Answer 6 (p. 830)
5.3.2.3.7 Question 7
True or false? Commands similar to those shown in Listing 1 (p. 825) can be used to put the bookClasses
library on the classpath :
Listing 1, Question 7.
5.183
5.3.2.3.8 Question 8
True or false? Commands similar to those shown in Listing 2 (p. 825) can be used to:
Listing 2, Question 8.
del *.class
javac -cp .;M:\bookClasses *.java
java -cp .;M:\bookClasses Prob01
5.184
5.3.2.3.9 Question 9
True or false? You can put commands in a batch le and run the batch le to avoid having to type the
commands each time you need to perform a specic operation from the command line. In that case, you
should add a pause command as the last command in the sequence.
Answer 9 (p. 829)
5.3.2.3.10 Question 10
True or false? The program shown in Listing 3 (p. 826) causes the words Text Hello World to be
displayed on the standard output device when the program is compiled and executed.
class TextHelloWorld{
public static void main(String[] args){
System.out.println("Text Hello World");
}//end main
}//end class
5.185
5.3.2.3.11 Question 11
True or false? The code shown in Listing 4 (p. 826) can be compiled and run to produce the graphic output
shown in Image 1 (p. 827) .
import java.awt.Color;
class GraphicHelloWorld{
public static void main(String[] args){
PictureExplorer pix = new PictureExplorer(200,100);
pix.setAllPixelsToAColor(Color.RED);
pix.addMessage("Graphic Hello World",15,50);
pix.show();
}// end main
}//end class
5.186
5.187
5.3.2.3.12 Question 12
True or false? The program shown (incorrectly) in Listing 4 (p. 826) and correctly in Listing 5 (p. 829)
requires the use of Ericson's multimedia library plus a jpg image le.
Answer 12 (p. 829)
5.3.2.4 Images
• Image 1 (p. 827) . Question 11.
5.3.2.5 Listings
• Listing 1 (p. 825) . Question 7.
• Listing 2 (p. 825) . Question 8.
• Listing 3 (p. 826) . Question 10.
• Listing 4 (p. 826) . Question 11.
• Listing 5 (p. 829) . Answer 11.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.2.6 Answers
5.3.2.6.1 Answer 12
False. The program does require the use of Ericson's multimedia library but it does not require a jpg image
le.
Back to Question 12 (p. 827)
5.3.2.6.2 Answer 11
False. The correct code is shown in Listing 5 (p. 829) .
import java.awt.Color;
class GraphicHelloWorld{
public static void main(String[] args){
Picture pix = new Picture(200,100);
pix.setAllPixelsToAColor(Color.RED);
pix.addMessage("Graphic Hello World",15,50);
pix.show();
}// end main
}//end class
5.188
5.3.2.6.3 Answer 10
True
Back to Question 10 (p. 826)
5.3.2.6.4 Answer 9
True.
Back to Question 9 (p. 825)
5.3.2.6.5 Answer 8
True.
Back to Question 8 (p. 825)
5.3.2.6.6 Answer 7
True.
Back to Question 7 (p. 825)
5.3.2.6.7 Answer 6
False. You will need to put the path to the bookClasses folder on your classpath in order to incorporate
classes from the library into your programs.
Back to Question 6 (p. 825)
5.3.2.6.8 Answer 5
True
Back to Question 5 (p. 824)
5.3.2.6.9 Answer 4
False. Once you have downloaded the zip le containing the library, you will need to extract the folder
named bookClasses from the zip le and store it somewhere on your computer's disk.
Back to Question 4 (p. 824)
5.3.2.6.10 Answer 3
False. The Guzdial-Ericson library was originally published by Guzdial and Ericson in conjunction with
their book Introduction to Computing and Programming with Java: A Multimedia Approach
53 . While the
book isn't free, the library is freely available and is published under a Creative Commons Attribution 3.0
United States License
54 .
Back to Question 3 (p. 824)
5.3.2.6.11 Answer 2
True.
Back to Question 2 (p. 824)
5.3.2.6.12 Answer 1
False. The multimedia class library was developed and made available by Mark Guzdial
55 and Barbara
Ericson
56 of the Georgia Institute of Technology.
Back to Question 1 (p. 824)
5.3.2.7 Miscellaneous
This section contains a variety of miscellaneous information.
53 http://www.pearsonhighered.com/educator/academic/product/0,3110,0131496980,00.html
54 http://creativecommons.org/licenses/by/3.0/us/
55 http://www.cc.gatech.edu/∼guzdial/
56 http://coweb.cc.gatech.edu/ice-gt/8
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.3.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.4.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
61 .
5.3.4.2.1.1 Images
• Image 1 (p. 834) . Graphic screen output.
• Image 2 (p. 835) . Command-line output.
• Image 3 (p. 837) . Commands to compile and execute the application.
• Image 4 (p. 841) . Constructors for the World class.
• Image 5 (p. 842) . Constructors for the Turtle class.
• Image 6 (p. 846) . Constructors for the Picture class.
5.3.4.2.1.2 Listings
• Listing 1 (p. 836) . The driver class.
• Listing 2 (p. 839) . Beginning of the class named Prob01Runner.
• Listing 3 (p. 843) . The constructor for the Prob01Runner class.
• Listing 4 (p. 844) . Three accessor methods.
• Listing 5 (p. 845) . The beginning of the run method.
• Listing 6 (p. 847) . Add text to the image.
• Listing 7 (p. 848) . Manipulate the turtle named joe.
• Listing 8 (p. 849) . Manipulate the turtle named sue.
• Listing 9 (p. 852) . Source code for Prob01.
5.3.4.3 Preview
In this module, I will explain a program that uses Java and Ericson's media library to (see Image 1 (p. 834)
) :
• Create a Picture object from an image le and replace the default white Picture in a World
object with the new Picture object.
• Place two Turtle objects in a World object.
• Apply a series of operations to manipulate the two turtle objects so as to produce a specic graphic
output.
• Provide accessor methods to get references to two Turtle objects and the World object.
• Use the references to get information from the World and Turtle objects and display that
information on the command-line screen.
• Display text on a Picture in a World object.
Program output
Image 1 (p. 834) shows the graphic screen output produced by this program.
5.189
Image 2 (p. 835) shows the text output produced by the program on the command line screen.
javac 1.6.0_14
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode,
sharing)
Dick Baldwin.
A 300 by 274 world with 2 turtles in it.
joe turtle at 44, 143 heading -135.0.
sue turtle at 250, 237 heading 0.0.
5.190
javac -version
java -version
import java.awt.Color;
5.191
javac Prob01.java
Note however that it is often necessary to specify the path to various library les on the command line when
compiling the application. In that case, the simplest form given above is not sucient.
Compiler output le names
When the application is successfully compiled, it will produce one or more output les with an extension
of .class . In this case, one of those les will be named Prob01.class .
Execution of the application
The execution of C and C++ programs begins and ends in the main function. The execution of Java
applications begin and end in the method named main .
Once again, in its simplest form, this application can be executed by entering the following command at
the command prompt:
java Prob01
Again, it is often necessary to specify the path to various library les on the command line when executing
the application. In that case, the simplest form is not sucient.
Compilation and execution on my machine
This application can be compiled and executed on my machine by entering the two commands shown in
Image 3 (p. 837) at the command prompt. (Note that articial line breaks were inserted into Image 3
(p. 837) to force the long commands to t this narrow format.)
5.192
The rst statement in the body of the main method in Listing 1 (p. 836) instantiates a new object of
the class named Prob01Runner .
The statement saves a reference to that object in a reference variable named obj . Note that the type
of the variable is the same as the name of the class in this case. In general, the type of the variable must be:
• getMars
• getJoe
• getSue
Accessor methods
These three methods are of a type that is commonly referred to as accessor methods . They access and
return values encapsulated inside an object. In most cases, (using good programming practice) they return
copies of the values. This protects the encapsulated values from being corrupted by code outside the object.
The method named println
In each case in Listing 1 (p. 836) , the value returned by the method is passed to a method named
println . This is a method belonging to a standard system object that represents the standard output
device (usually the command-line screen) . The purpose of the println method is to display material on
the command-line screen.
System.out.println...
Without going into detail about how this works, you should simply memorize the syntax of the last three
statements in the body of the main method in Listing 1 (p. 836) . I explain the concepts involved in great
detail on my website. Go to Google and search for the following keywords:
• The fourth line of text from the bottom in Image 2 (p. 835) (Dick Baldwin) was produced before the
last three lines of text discussed above. Therefore, that line of text must have been produced before
control reached the call to the getMars method in Listing 1 (p. 836) .
• public
• private
• protected
• package-private
Rather than trying to explain all four at this time, I will explain public here and explain the other three
when we encounter them in code.
The public modier is the easiest of the four to explain. As the name implies, it is analogous to a
public telephone. Any code that can nd a class or class member with a public modier can access and use
it. In this case, any code that can nd the class denition for the class named Prob01 can instantiate an
object of that class.
The class named Prob01Runner
There's not a lot more that we can say about the driver class named Prob01 , so it's time to analyze
the class named Prob01Runner . We need to gure out what it is about that class that causes the
program output to match the material shown in Image 1 (p. 834) and Image 2 (p. 835) .
Beginning of the class named Prob01Runner
Prob01Runner
The denition of the class named begins in Listing 2 (p. 839) .
class Prob01Runner{
//Instantiate the World and Turtle objects.
private World mars = new World(300,274);
private Turtle joe = new Turtle(mars);
private Turtle sue = new Turtle(mars);
5.193
No access modier
Note that this class denition does not have an access modier. This puts it in package-private access
category. A class with package-private access can be accessed by code that is stored in the same package
and cannot be accessed by code stored in other packages.
Three private variables
The last three statements in Listing 2 (p. 839) declare three private variables. Because these variables
are declared private, they can only be accessed by code contained in methods dened inside the class.
(They are also accessible by code contained in methods dened in classes dened inside the class, but
that is beyond the scope of this module.)
Three private instance variables
These variables are also instance variables as opposed to class variables . (We will discuss class
variables in a future module.)
Because they are instance variables, they belong to an object instantiated from the class. (An object
is an instance of a class.) Even if the variables were public, they could only be accessed by rst gaining
access to the object to which they belong.
Multiple instances of the class
If you instantiate multiple objects of this same class (create multiple instances which you often do) ,
each object will encapsulate the same set of the three private instance variables shown in Listing 2 (p. 839)
. Instance variables have the same name but may have dierent values in the dierent objects.
Three private instance reference variables
The three variables declared in Listing 2 (p. 839) are also reference variables (as opposed to primitive
variables) . This means that they are capable of storing references to objects as opposed to simply being
able to store primitive values of the following eight types:
• char
• byte
• short
• int
• long
• oat
• double
• boolean
Primitive variables can only store primitive values of the types in the above list.
Classes, classes, and more classes
A Java application consists almost exclusively of objects. Objects are instances of classes. Therefore,
class denitions must exist before objects can exist.
The true power of Java
The Java programming language is small and compact. The true power of Java lies in its libraries of
predened classes.
The Java standard edition development kit and runtime engine available from Sun contains a library con-
sisting of thousands of predened classes. Other class libraries containing thousands of classes are available
from sun in the enterprise edition and the micro edition.
Non-standard class libraries
In some cases, you or your company may create your own class libraries and/or obtain class libraries
from other sources such as the Ericson class library that we are using in this module.
Custom class denitions
In almost all cases, you will need to dene a few new classes for new applications that you write. We will
dene two new classes for this application. The remainder of the classes that we use will come either from
Sun's standard library or Ericson's library.
Objects of the World class and the Turtle class
World and another class named Turtle . The code in
Ericson's class library contains a class named
Listing 2 (p. 839) instantiates one object of the World class and populates that world with two objects of
the Turtle class.
Every class has a constructor
Every class denition has one or more method-like members called constructors. (If you don't dene a
constructor when you dene a class, a default constructor will be automatically dened for your class.)
The name of the constructor must always be the same as the name of the class. Like a method, a
constructor may or may not take arguments. If there are two or more (overloaded) constructors, they must
have dierent argument lists.
Instantiating an object of a class
To instantiate an object of a class, you apply the new operator (see Listing 2 (p. 839) ) to the
class' constructor, passing parameters that satisfy the required arguments for the constructor.
Return a reference to the object
Once the object has been instantiated, the constructor returns a reference to the new object.
A new World object
For example, the rst statement in Listing 2 (p. 839) applies the new operator to Ericson's World class
constructor passing two integer values as parameters. This causes a new World object to be instantiated.
A reference is returned
A reference to the newWorld object is returned and stored in the reference variable named mars .
Once the reference is stored in the reference variable, it can be used to access the World object later.
Constructors for the World class
Image 4 (p. 841) s shows the constructors that are available for Ericson's World class. (See javadocs
for the Ericson library.)
5.194
5.195
note: ModelDisplay interface The World class implements the ModelDisplay interface.
Therefore, an object of the World class can be treated as it is type ModelDisplay. I explain the
relationship between classes and interfaces in detail on my website.
public Prob01Runner(){//constructor
System.out.println("Dick Baldwin.");
}//end constructor
5.196
5.197
5.198
Recall that the code in the main method in Listing 1 (p. 836) calls the run method on the object
immediately after it is instantiated.
A turtle on a white background
I told you earlier that if you were to eliminate the call to the run method, you would see a turtle at
the center of the world with a white background.
The background is a Picture object
World object consists of an object of Ericson's Picture
The background of a class. (A Picture
object is encapsulated in the World object.)
By default, the Picture object encapsulated in a World object is all white and is exactly the right
size and shape to completely ll the area inside the world's border (see Image 1 (p. 834) ).
Can be replaced
As you will see shortly, we can replace the default Picture object with a new Picture object of our
own choosing.
What if it doesn't t?
If the new Picture object isn't large enough to completely ll the area inside the borders of the World
object, it will be placed in the upper-left corner of the World object and the remainder of the World
object will be a light gray color.
If the Picture object is too large, an upper-left rectangular portion of the Picture object, sucient
to ll theWorld object, will be displayed. The remainder of the Picture object will not be visible even
if you manually resize the World object to make it larger.
Constructors for the Picture class
Image 6 (p. 846) shows the javadocs for the constructors for Ericson's Picture class.
5.199
62 http://cnx.org/content/m44149/latest/Prob01.jpg
• a string and
• two coordinate values of type int .
The method will draw the string as text characters onto the image at the location specied by the two
coordinate values.
(The origin of the coordinate system is the upper-left corner of the image with positive horizontal values
going to the right and positive vertical values going down.)
Add text to the image
The code in Listing 6 (p. 847) uses two levels of indirection to add my name as a message to the picture
that forms the background of the world as shown in Image 1 (p. 834) .
mars.getPicture().addMessage(
"Dick Baldwin",10,20);
5.200
joe.setName("joe");
joe.setBodyColor(Color.RED);
joe.setShellColor(Color.BLUE);
joe.setPenColor(Color.YELLOW);
joe.setPenWidth(3);
joe.forward();
joe.turn(-135);
joe.setPenColor(Color.BLUE);
joe.forward(150);
5.201
sue.setName("sue");
sue.setPenWidth(2);
sue.setPenColor(Color.RED);
sue.moveTo(183,170);
sue.setPenDown(false);
sue.moveTo(216,203);
sue.setPenDown(true);
sue.moveTo(250,237);
}//end run method
}//end class Prob01Runner
5.202
Pen control
Listing 8 (p. 849) also calls the setPenDown method twice passing false and then true as the parameter
to rst raise and then lower the pen. This produced the gap in the red line shown in Image 1 (p. 834) .
The end of the program
Listing 8 (p. 849) also signals the end of the method named run and the end of the class named
Prob01Runner . As such, Listing 8 (p. 849) signals the end of the program.
5.3.4.6 Summary
II explained a program that uses Java and Ericson's media library to:
· Part01
64
· Part02
65
· Part03
66
· Part04
67
· Part05
68
63 http://www.youtube.com/playlist?list=PL26BF7154F10D3854
64 http://www.youtube.com/watch?v=7KjSLqTgMec
65 http://www.youtube.com/watch?v=Jnra7RfPKOI
66 http://www.youtube.com/watch?v=mJDGp1HPCuE
67 http://www.youtube.com/watch?v=mYrGKI16j_4
68 http://www.youtube.com/watch?v=UUTlMh3J5Ow
· Part06
69
· Part07
70
· Part08
71
· Part09
72
· Part10
73
5.3.4.9 Miscellaneous
This section contains a variety of miscellaneous information.
• File: Java3002.htm
• Published: 07/26/12
• Revised: 02/12/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have misappropriated copies of my modules from cnx.org, con-
verted them to Kindle books, and placed them for sale on Amazon.com showing me as the author.
I receive no compensation for those sales and don't know who does receive compensation. If you
purchase such a book, please be aware that it is a bootleg copy of a module that is freely available
on cnx.org.
69 http://www.youtube.com/watch?v=hmu-l1a7VyE
70 http://www.youtube.com/watch?v=tRpS7c-aPd0
71 http://www.youtube.com/watch?v=cE_ks6Oq3OY
72 http://www.youtube.com/watch?v=4f39g8oEWsY
73 http://www.youtube.com/watch?v=yeay7REkLBY
Command-line output
javac 1.6.0_14
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode,
sharing)
Dick Baldwin.
A 300 by 274 world with 2 turtles in it.
joe turtle at 44, 143 heading -135.0.
sue turtle at 250, 237 heading 0.0.
*********************************************************/
import java.awt.Color;
System.out.println(obj.getMars());
System.out.println(obj.getJoe());
System.out.println(obj.getSue());
}//end main
}//end class Prob01
//*******************************************************/
class Prob01Runner{
//Instantiate the World and Turtle objects.
private World mars = new World(300,274);
private Turtle joe = new Turtle(mars);
private Turtle sue = new Turtle(mars);
public Prob01Runner(){//constructor
System.out.println("Dick Baldwin.");
}//end constructor
//----------------------------------------------------//
//Accessor methods
public Turtle getJoe(){return joe;}
public Turtle getSue(){return sue;}
public World getMars(){return mars;}
//----------------------------------------------------//
"Dick Baldwin",10,20);
-end-
· 1 (p. 854) , 2 (p. 855) , 3 (p. 855) , 4 (p. 855) , 5 (p. 855) , 6 (p. 856) , 7 (p. 856) , 8 (p. 856) ,
9 (p. 856) , 10 (p. 856) , 11 (p. 856) , 12 (p. 856) , 13 (p. 857) , 14 (p. 857) , 15 (p. 857) , 16
(p. 857) , 17 (p. 857) , 18 (p. 857) , 19 (p. 857) , 20 (p. 858) , 21 (p. 858) , 22 (p. 858) , 23 (p.
858) , 24 (p. 858) , 25 (p. 858) , 26 (p. 859) , 27 (p. 859) , 28 (p. 859) , 29 (p. 859) , 30 (p. 859)
, 31 (p. 859) , 32 (p. 860) , 33 (p. 860) , 34 (p. 860) , 35 (p. 860) , 36 (p. 860) , 37 (p. 860) , 38
(p. 860) , 39 (p. 860) , 40 (p. 861) , 41 (p. 861) , 42 (p. 861) , 43 (p. 861) , 44 (p. 861) , 45 (p.
861) , 46 (p. 862) , 47 (p. 862) , 48 (p. 863) , 49 (p. 863) , 50 (p. 863)
5.3.5.2 Preface
This module contains review questions and answers keyed to the module titled Java3002: Creating and
Manipulating Turtles and Pictures in a World Object
75 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.5.3 Questions
5.3.5.3.1 Question 1 .
True or False? The import directive at the very beginning of Listing 1 (p. 855) is a directive to the compiler
and the virtual machine notifying them that the class named Color can be found in the package named
java.awt .
Listing 1. Question 1.
import java.awt.Color;
5.204
5.3.5.3.2 Question 2
True or False? The class named Color imported in Listing 1 (p. 855) is a member of Ericson's multimedia
library.
Answer 2 (p. 871)
5.3.5.3.3 Question 3
True or False? A package is the specication of a particular folder on the disk relative to a standard root
folder.
Answer 3 (p. 871)
5.3.5.3.4 Question 4
True or False? Every Java application and every Java applet must include the denition of a class that
contains the denition of a method named main .
Answer 4 (p. 870)
5.3.5.3.5 Question 5
True or False? The name of the class containing the main method is also the name of the application
insofar as being able to compile and execute the application is concerned.
Answer 5 (p. 870)
5.3.5.3.6 Question 6
True or False? The name of the application shown in Listing 1 (p. 855) is Proj01 .
Answer 6 (p. 870)
5.3.5.3.7 Question 7
True or False? The name of the source code le containing the class denition shown in Listing 1 (p. 855)
must be Prob01.java in order for the application to compile and run as an application named Prob01 .
Answer 7 (p. 870)
5.3.5.3.8 Question 8
True or False? In its simplest form, an application can be compiled by executing the command shown in
Listing 2 (p. 856) at the command prompt where Prob01.java is the name of the le containing the
main method.
Listing 2. Question 8.
javac Prob01
5.205
5.3.5.3.9 Question 9
True or False? It is often necessary to specify the path to various library les on the command line when
compiling an application. In that case, the simplest form given in Listing 3 (p. 870) is not sucient.
Answer 9 (p. 870)
5.3.5.3.10 Question 10
True or False? When a Java application is successfully compiled, it will produce one or more output les
with an extension of .class .
Answer 10 (p. 870)
5.3.5.3.11 Question 11
True or False? The execution of a Java application begins and ends in the method named main .
Answer 11 (p. 870)
5.3.5.3.12 Question 12
True or False? The two commands shown in Listing 4 (p. 857) can be used to compile and execute a Java
application named Prob01 where:
• The only special class library required is contained in the folder named bookClasses .
• The path from the root to the folder named bookClasses is represented by \bookClasses.
5.206
5.3.5.3.13 Question 13
True or False? The Java compiler program is named java.exe .
Answer 13 (p. 869)
5.3.5.3.14 Question 14
True or False? The Prob01.java and Prob01 at the ends of the two commands in Listing 4 (p. 857)
specify the les being operated on by the virtual machine and the compiler respectively.
Answer 14 (p. 869)
5.3.5.3.15 Question 15
True or False? In Listing 4 (p. 857) , the -cp indicates that a classpath follows.
Answer 15 (p. 869)
5.3.5.3.16 Question 16
True or False? A classpath consists of one or more path specications separated by semicolon characters.
Answer 16 (p. 869)
5.3.5.3.17 Question 17
True or False? The purpose of the classpath in Listing 4 (p. 857) is to tell the compiler and the virtual
machine where to look for source code les that the application needs in order to successfully compile and
execute.
Answer 17 (p. 869)
5.3.5.3.18 Question 18
True or False? The period ahead of the semicolon in Listing 4 (p. 857) says to search the root folder rst.
Answer 18 (p. 869)
5.3.5.3.19 Question 19
True or False? The rst statement in the body of the main method in Listing 1 (p. 855) instantiates a
new object of the class named Prob01Runner .
Answer 19 (p. 869)
5.3.5.3.20 Question 20
True or False? The rst statement in Listing 1 (p. 855) saves a reference to a new object of the class named
Prob01Runner in a reference variable named obj . In general, the type of the variable must be:
5.3.5.3.21 Question 21
True or False? In Java, you must save a reference to a newly instantiated object in order to gain access to
that object later in the program.
Answer 21 (p. 868)
5.3.5.3.22 Question 22
True or False? The second statement in the body of the main method in Listing 1 (p. 855) uses the
reference stored in the variable named obj to call the method named run encapsulated in the object
referred to by the contents of obj .
Answer 22 (p. 868)
5.3.5.3.23 Question 23
True or False? The following three methods that are called in Listing 1 (p. 855) are of a type that is
commonly referred to as accessor methods . They are also sometimes referred to by the slang term getter
methods .
• getMars
• getJoe
• getSue
5.3.5.3.24 Question 24
True or False? The method named println that is called in Listing 1 (p. 855) is a member of Ericson's
multimedia library. The purpose of the println method is to display text on an image.
Answer 24 (p. 868)
5.3.5.3.25 Question 25
True or False? Java uses four access modiers to specify the accessibility of various classes and members in
a Java application:
• public
• private
• protected
• package-private
5.3.5.3.26 Question 26
True or False? Listing 5 (p. 859) shows the beginning of a class named Prob01Runner .
class Prob01Runner{
//Instantiate the World and Turtle objects.
private World mars = new World(300,274);
private Turtle joe = new Turtle(mars);
private Turtle sue = new Turtle(mars);
5.207
5.3.5.3.27 Question 27
True or False? The class that begins in Listing 5 (p. 859) does not have an access modier. This puts it
in package-private access category. A class with package-private access can be accessed by code that is
stored in the same package and cannot be accessed by code stored in other packages.
Answer 27 (p. 868)
5.3.5.3.28 Question 28
True or False? The last three statements in Listing 5 (p. 859) declare three private variables. Because
these variables are declared private, they can be accessed by any method dened in any class in the same
package.
Answer 28 (p. 868)
5.3.5.3.29 Question 29
True or False? The three variables declared in Listing 5 (p. 859) are instance variables as opposed to class
variables .
Answer 29 (p. 868)
5.3.5.3.30 Question 30
True or False? Because the three variables declared in Listing 5 (p. 859) are instance variables, they belong
to an object instantiated from the class. Even if the variables were public, they could only be accessed by
rst gaining access to the object to which they belong.
Answer 30 (p. 867)
5.3.5.3.31 Question 31
True or False? The three variables declared in Listing 5 (p. 859) are reference variables . This means that
they are capable of storing references to objects and are also capable of storing values of the eight primitive
types.
Answer 31 (p. 867)
5.3.5.3.32 Question 32
True or False? Ericson's class library contains a class named World and another class named Turtle .
The code in Listing 5 (p. 859) instantiates one object of the World class and populates that world with
three objects of the Turtle class.
Answer 32 (p. 867)
5.3.5.3.33 Question 33
True or False? Every class denition has one or more method-like members called constructors. (If you
don't dene a constructor when you dene a class, a default constructor will be automatically dened for
your class.)
Answer 33 (p. 867)
5.3.5.3.34 Question 34
True or False? The name of the constructor must always be the same as the name of the class in which
it is dened. Like a method, a constructor may or may not take arguments. If there are two or more
(overloaded) constructors, they must have dierent argument lists.
Answer 34 (p. 867)
5.3.5.3.35 Question 35
True or False? To instantiate an object of a class, you apply the new operator to the class' constructor,
passing parameters that satisfy the required arguments for the constructor.
Answer 35 (p. 867)
5.3.5.3.36 Question 36
True or False? When an object is instantiated, the constructor returns an array containing the values in all
of the instance variables.
Answer 36 (p. 867)
5.3.5.3.37 Question 37
True or False? The last two statements in Listing 5 (p. 859) instantiate two objects of the Turtle class
and use them to populate the World object whose reference is stored in the variable named mars .
Answer 37 (p. 867)
5.3.5.3.38 Question 38
True or False? If a variable (exclusive of local variables inside of methods) is not purposely initialized when
the object in instantiated, it will receive a default initialization value. The default values are:
5.3.5.3.39 Question 39
True or False? Code written into a class' constructor is executed when an object of the class is instantiated.
Answer 39 (p. 866)
5.3.5.3.40 Question 40
True or False? Good object-oriented programming practice says that most of the instance variables encap-
sulated in an object should be declared private. If there is a need to make the contents of those variables
available outside the object, that should be accomplished by dening protected accessor methods.
Answer 40 (p. 866)
5.3.5.3.41 Question 41
True or False? Everything in Java is passed and returned by reference.
Answer 41 (p. 866)
5.3.5.3.42 Question 42
True or False? Each of the accessor methods shown in Listing 6 (p. 861) returns a copy of the reference
pointing to either a Turtle object or a World object.
5.208
5.3.5.3.43 Question 43
True or False? Code in the println method calls a method named toString on each incoming primitive
value and displays the string value returned by that method.
Answer 43 (p. 866)
5.3.5.3.44 Question 44
True or False? The toString method is overridden (not overloaded) in the World and Turtle classes
so as to return a string value describing the object.
Answer 44 (p. 866)
5.3.5.3.45 Question 45
True or False? The code in Listing 7 (p. 862) replaces the default all-white picture in a World object with
another picture. (Note, the variable named mars contains a reference to an object of the class World
.)
5.209
5.3.5.3.46 Question 46
True or False? The background of a World object consists of an object of Ericson's Picture class. (A
Picture object is encapsulated in the World object.)
Answer 46 (p. 866)
5.3.5.3.47 Question 47
True or False? The code in Listing 8 (p. 862) uses two levels of indirection to add my name to the picture
that forms the background of the world shown in Image 1 (p. 863) .
mars.getPicture().toString(
"Dick Baldwin",10,20);
5.210
5.211
5.3.5.3.48 Question 48
True or False? A Turtle object encapsulates many methods that can be used to manipulate the turtle in
a variety of dierent ways.
Answer 48 (p. 865)
5.3.5.3.49 Question 49
True or False? A call to the forward method of a turtle object with no parameters causes the turtle to
move forward by a default distance of 100 pixels.
Answer 49 (p. 865)
5.3.5.3.50 Question 50
True or False? A call to the moveTo method of a turtle object with a single parameter value of 150
causes the turtle to move forward by a distance of 150 pixels.
5.3.5.4 Images
• Image 1 (p. 863) . Question 47.
5.3.5.5 Listings
• Listing 1 (p. 855) . Question 1.
• Listing 2 (p. 856) . Question 8.
• Listing 3 (p. 870) . Answer 8.
• Listing 4 (p. 857) . Question 12.
• Listing 5 (p. 859) . Question 26.
• Listing 6 (p. 861) . Question 42.
• Listing 7 (p. 862) . Question 45.
• Listing 8 (p. 862) . Question 47.
• Listing 9. (p. 866) Answer 47.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.5.6 Answers
5.3.5.6.1 Answer 50
False. The moveTo method of the Turtle class cannot be called with a single parameter. Two parameters
are required.
Back to Question 50 (p. 863)
5.3.5.6.2 Answer 49
True.
Back to Question 49 (p. 863)
5.3.5.6.3 Answer 48
True.
Back to Question 48 (p. 863)
5.3.5.6.4 Answer 47
False. The code in Listing 8 (p. 862) won't compile. The toString method does not apply to images. The
correct code is shown in Listing 9 (p. 866) .
mars.getPicture().addMessage(
"Dick Baldwin",10,20);
5.212
5.3.5.6.5 Answer 46
True.
Back to Question 46 (p. 862)
5.3.5.6.6 Answer 45
True.
Back to Question 45 (p. 861)
5.3.5.6.7 Answer 44
True.
Back to Question 44 (p. 861)
5.3.5.6.8 Answer 43
False. Code in the println method calls a method named toString on each incoming object reference
and displays the string value returned by that method.
Back to Question 43 (p. 861)
5.3.5.6.9 Answer 42
True.
Back to Question 42 (p. 861)
5.3.5.6.10 Answer 41
False. Everything in Java is passed and returned by value , not by reference.
Back to Question 41 (p. 861)
5.3.5.6.11 Answer 40
False. If there is a need to make the contents of those variables available outside the object, that should be
accomplished by dening public accessor methods.
Back to Question 40 (p. 861)
5.3.5.6.12 Answer 39
True.
Back to Question 39 (p. 860)
5.3.5.6.13 Answer 38
False.
The default values are:
5.3.5.6.14 Answer 37
True.
Back to Question 37 (p. 860)
5.3.5.6.15 Answer 36
False. When an object is instantiated, the constructor returns a reference to the new object.
Back to Question 36 (p. 860)
5.3.5.6.16 Answer 35
True.
Back to Question 35 (p. 860)
5.3.5.6.17 Answer 34
True.
Back to Question 34 (p. 860)
5.3.5.6.18 Answer 33
True.
Back to Question 33 (p. 860)
5.3.5.6.19 Answer 32
False. The code in Listing 5 (p. 859) instantiates one object of the World class and populates that world
with two objects of the Turtle class.
Back to Question 32 (p. 860)
5.3.5.6.20 Answer 31
False. The three variables declared in Listing 5 (p. 859) are reference variables (as opposed to primitive
variables) . This means that they are capable of storing references to objects as opposed to simply being
able to store values of the eight primitive types. It also means that they are incapable of storing values of
the eight primitive types.
Back to Question 31 (p. 859)
5.3.5.6.21 Answer 30
True.
Back to Question 30 (p. 859)
5.3.5.6.22 Answer 29
True.
Back to Question 29 (p. 859)
5.3.5.6.23 Answer 28
False. Because these variables are declared private , they can only be accessed by code contained in
methods dened inside the same class (and in inner classes of the class, which is beyond the scope of this
module) .
Back to Question 28 (p. 859)
5.3.5.6.24 Answer 27
True.
Back to Question 27 (p. 859)
5.3.5.6.25 Answer 26
True.
Back to Question 26 (p. 859)
5.3.5.6.26 Answer 25
True.
Back to Question 25 (p. 858)
5.3.5.6.27 Answer 24
False. The method named println that is called in Listing 1 (p. 855) is a method belonging to a standard
system object that represents the standard output device (usually the command-line screen) . The purpose
of the println method is to display material on the command-line screen.
Back to Question 24 (p. 858)
5.3.5.6.28 Answer 23
True.
Back to Question 23 (p. 858)
5.3.5.6.29 Answer 22
True.
Back to Question 22 (p. 858)
5.3.5.6.30 Answer 21
True.
Back to Question 21 (p. 858)
5.3.5.6.31 Answer 20
False.
In general, the type of the variable must be:
5.3.5.6.32 Answer 19
True.
Back to Question 19 (p. 857)
5.3.5.6.33 Answer 18
False. The period ahead of the semicolon in Listing 4 (p. 857) says to search the current folder rst.
Back to Question 18 (p. 857)
5.3.5.6.34 Answer 17
False. The purpose of the classpath is to tell the compiler and the virtual machine where to look for previously
compiled class les that the application needs in order to successfully compile and execute.
Back to Question 17 (p. 857)
5.3.5.6.35 Answer 16
True.
Back to Question 16 (p. 857)
5.3.5.6.36 Answer 15
True
Back to Question 15 (p. 857)
5.3.5.6.37 Answer 14
False. The Prob01.java and Prob01 at the ends of the two commands in Listing 4 (p. 857) specify the
les being operated on by the compiler and the virtual machine respectively.
Back to Question 14 (p. 857)
5.3.5.6.38 Answer 13
False. The Java compiler program is named javac.exe . The virtual machine is named java.exe .
Back to Question 13 (p. 857)
5.3.5.6.39 Answer 12
True.
Back to Question 12 (p. 856)
5.3.5.6.40 Answer 11
True.
Back to Question 11 (p. 856)
5.3.5.6.41 Answer 10
True.
Back to Question 10 (p. 856)
5.3.5.6.42 Answer 9
True.
Back to Question 9 (p. 856)
5.3.5.6.43 Answer 8
False. The required command is shown in Listing 3 (p. 870) .
Listing 3. Answer 8.
javac Prob01.java
5.213
5.3.5.6.44 Answer 7
True.
Back to Question 7 (p. 856)
5.3.5.6.45 Answer 6
False. The name of the application shown in Listing 1 (p. 855) is Prob01 .
Back to Question 6 (p. 856)
5.3.5.6.46 Answer 5
True.
Back to Question 5 (p. 855)
5.3.5.6.47 Answer 4
False. Java applets do not require a method named main .
Back to Question 4 (p. 855)
5.3.5.6.48 Answer 3
True.
Back to Question 3 (p. 855)
5.3.5.6.49 Answer 2
False. java.awt.Color belongs to the Java standard edition class library.
Back to Question 2 (p. 855)
5.3.5.6.50 Answer 1
True.
Back to Question 1 (p. 854)
5.3.5.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.6.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
77 http://cnx.org/content/m44149
78 http://cnx.org/content/m45621/latest/a0-Index.htm
79 This content is available online at <http://cnx.org/content/m44203/1.6/>.
5.3.7.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
80 .
5.3.7.2.1.1 Images
• Image 1 (p. 875) . The raw image.
• Image 2 (p. 876) . The modied image.
• Image 3 (p. 877) . Output text on the command line screen.
• Image 4 (p. 879) . javadocs description of the explore method.
• Image 5 (p. 880) . javadocs description of the getPixels method.
• Image 6 (p. 881) . javadocs description of the Pixel class.
5.3.7.2.1.2 Listings
• Listing 1 (p. 878) . The driver class.
• Listing 2 (p. 878) . Beginning of the class named Prob02Runner.
• Listing 3 (p. 879) . The beginning of the run method.
• Listing 4 (p. 880) . Implementing the algorithm.
• Listing 5 (p. 882) . Display again and terminate.
• Listing 6 (p. 884) . Complete program listing.
5.3.7.3 Preview
The program that I will explain in this module is designed to be used as a test of the student's understanding
of programming using Java and Ericson's media library.
The student is provided an image le named Prob02.jpg along with a pair of PictureExplorer
windows containing the raw image and a modied version of the image. (See Image 1 (p. 875) and Image
2 (p. 876) .)
Deduce the algorithm
80 http://cnx.org/content/m44148/latest/
The rst part of the test is to determine if the student can examine the raw image shown in the
PictureExplorer window in Image 1 (p. 875) and deduce the algorithm required to produce the output
shown in the PictureExplorer window in Image 2 (p. 876) .
Implement the algorithm
The second part of the test is to determine if the student can implement the algorithm once it is established
and also satisfy some requirements for text output on the command line screen. Among other things, this
requires that the student be able to:
Program output
The raw image is displayed in the PictureExplorer window shown in Image 1 (p. 875) .
5.214
The modied image is shown in the PictureExplorer window in Image 2 (p. 876) .
5.215
The required output on the command-line screen is shown by the last two lines of text in Image 3 (p.
877) . The other text in Image 3 (p. 877) is produced by the system during the compilation and execution
process.
Dick Baldwin
Picture, filename Prob02.jpg height 274 width 365
5.216
The algorithm
The algorithm required to transform the image from Image 1 (p. 875) to Image 2 (p. 876) is:
obj.run();
System.out.println(obj.getPicture());
}//end main
}//end class Prob02
5.217
You should already be familiar with everything in Listing 1 (p. 878) . The most important aspect of
run method belonging
Listing 1 (p. 878) for purposes of this discussion is the call to the to the object
instantiated from the Prob02Runner class. I will explain the run method shortly.
Beginning of the class named Prob02Runner
The class denition for the class named Prob02Runner begins in Listing 2 (p. 878) .
class Prob02Runner{
private Picture pic = new Picture("Prob02.jpg");
public Prob02Runner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
5.218
Again, you should be familiar with everything in Listing 2 (p. 878) . I will simply highlight the instan-
tiation of a new Picture object using an image le as input and the saving of a reference to that object
in the private instance variable named pic .
The beginning of the run method
The run method begins in Listing 3 (p. 879) . This is where the action is, so to speak.
pic.addMessage("Dick Baldwin",10,20);
pic.explore();
5.219
You are already familiar with the call to the addMessage method to add my name as text to the
image encapsulated in the Picture object. ( See Image 1 (p. 875) .)
The explore method
The call to the explore method is new to this module.
The explore method is dened in the SimplePicture class, which is the superclass of the Picture
class. The method is inherited into the Picture class.
javadocs description of the explore method
The javadocs description of this method is shown in Image 4 (p. 879) .
5.220
• The explore method makes it easy to display copies of an image at various stages during the
processing of the image. Once the PictureExplorer object is created and displayed, it won't be
eected by subsequent changes to the image.
• The availability of a PictureExplorer object makes it easy to manually analyze the colors of the
individual pixels in an image encapsulated in that object.
for(Pixel pixel:pixelArray ){
pixel.setRed(255 - pixel.getRed());
pixel.setGreen(255 - pixel.getGreen());
pixel.setBlue(0);
}//end for loop
5.221
In particular, the code in Listing 4 (p. 880) sets the blue color components to 0 and inverts the red and
green color components for every pixel in the picture.
One of several approaches
There are several ways to do this, and this is only one of those ways. This approach makes use of a
method named getPixels that is dened in the SimplePicture class and inherited into the Picture
class.
Very useful when...
This approach is particularly useful when you want to perform the same action on every pixel in an
image. The advantage is that you don't have to worry about horizontal and vertical coordinates with this
approach. Access to all of the pixels is provided in a one-dimensional array.
javadocs description of the getPixels method
The javadocs description of this method is shown in Image 5 (p. 880) .
5.222
5.223
• Computationally cheap
• Very fast
• Usually visually obvious
• Totally reversible
For example, many software program invert all of the colors in an image when it is selected for some
purpose, such as copying to the clipboard. Then the colors are restored to their original values when the
image is deselected.
Next to redeye correction, color inversion is probably the most commonly used color modication algo-
rithm in use in modern image processing.
Display again and terminate
pic still contains a reference to the original Picture
The variable named object. However, the image
that is encapsulated in that object has been signicantly modied.
Listing 5 (p. 882) calls the explore method again, creating and displaying another PictureExplorer
object that encapsulates a copy of the Picture object with the modied image.
pic.explore();
5.224
5.3.7.5 Summary
In this module, you learned how to invert images and how to display images in PictureExplorer objects.
81 http://cnx.org/content/m44203/latest/Prob02.jpg
· Part01
83
· Part02
84
· Part03
85
· Part04
86
5.3.7.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
82 http://www.youtube.com/playlist?list=PL713DB9A1FF4B92DF
83 http://www.youtube.com/watch?v=SVq_IN4TsTs
84 http://www.youtube.com/watch?v=vcVLr8Z1mo4
85 http://www.youtube.com/watch?v=M1Nns7vYTiM
86 http://www.youtube.com/watch?v=Qw-yzEGuFJU
class Prob02Runner{
private Picture pic = new Picture("Prob02.jpg");
public Prob02Runner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
//----------------------------------------------------//
5.225
-end-
· 1 (p. 886) , 2 (p. 886) , 3 (p. 887) , 4 (p. 888) , 5 (p. 888) , 6 (p. 890) , 7 (p. 891) , 8 (p. 891) ,
9 (p. 891) , 10 (p. 891) , 11 (p. 891)
5.3.8.2 Preface
This module contains review questions and answers keyed to the module titled Image Java3004: Processing
Algorithms, Image Inversion, and PictureExplorer Objects
88 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.8.3 Questions
5.3.8.3.1 Question 1 .
True or False? A color value is inverted by subtracting the value from 256.
Answer 1 (p. 895)
5.3.8.3.2 Question 2
True or False? The code in Listing 1 (p. 886) instantiates a new object of the PictureExplorer class.
Listing 1. Question 2.
class Prob02Runner{
private Picture pic = new Picture("Prob02.jpg");
public Prob02Runner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
5.226
5.3.8.3.3 Question 3
True or False? The code in Listing 2 (p. 887) causes an image to be displayed in the format shown in Image
1 (p. 888) .
Listing 2. Question 2.
pic.addMessage("Dick Baldwin",10,20);
pic.explore();
5.227
Image 1. Question 3.
5.228
5.3.8.3.4 Question 4
True or False? The availability of the explore method and the PictureExplorer class is very important
in at least two respects:
• The explore method makes it easy to display copies of an image at various stages during the
processing of the image. Once the PictureExplorer object is created and displayed, it won't be
eected by subsequent changes to the image.
• The availability of a PictureExplorer object makes it easy to manually analyze the colors of the
individual pixels in an image encapsulated in that object.
5.3.8.3.5 Question 5
True or False? The algorithm shown in Listing 3 (p. 889) can be used to cause the image shown in Image 2
(p. 894) to be transformed into the image shown in Image 3 (p. 890) .
Listing 3. Question 5.
for(Pixel pixel:pixelArray ){
pixel.setRed(255 - pixel.getRed());
pixel.setGreen(255 - pixel.getGreen());
pixel.setBlue(0);
}//end for loop
5.229
Image 3. Question 5.
5.230
5.3.8.3.6 Question 6
True or False? An object of Ericson's Pixel class encapsulates an individual pixel from an image.
Answer 6 (p. 893)
5.3.8.3.7 Question 7
True or False? The Pixel class denes a single method that can be called to invert the color of the pixel.
Answer 7 (p. 893)
5.3.8.3.8 Question 8
True or False? The getPixels method belonging to a Picture object returns references to all of the
Pixel objects encapsulated in the picture in a two-dimensional array where the dimensions of the array
represent the horizontal and vertical coordinates of each pixel.
Answer 8 (p. 893)
5.3.8.3.9 Question 9
True or False? The for loop shown in Listing 3 (p. 889) is of a type that is often referred to as a for-each
loop.
Answer 9 (p. 893)
5.3.8.3.10 Question 10
True or False? The three statements inside the loop in Listing 3 (p. 889) modify the color values of a single
pixel.
Answer 10 (p. 893)
5.3.8.3.11 Question 11
True or False? If the colors of all the pixels in an image are inverted, the process is completely reversible.
All that is necessary to recover the original image is to invert all of the pixels again.
Answer 11 (p. 893)
5.3.8.4 Images
• Image 1 (p. 888) . Question 3.
• Image 2 (p. 894) . Answer 3.
• Image 3 (p. 890) . Question 5.
5.3.8.5 Listings
• Listing 1 (p. 886) . Question 2.
• Listing 2 (p. 887) . Question 2.
• Listing 3 (p. 889) . Question 5.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.8.6 Answers
5.3.8.6.1 Answer 11
True.
Back to Question 11 (p. 891)
5.3.8.6.2 Answer 10
True.
Back to Question 10 (p. 891)
5.3.8.6.3 Answer 9
True.
Back to Question 9 (p. 891)
5.3.8.6.4 Answer 8
False. The getPixels method belonging to a Picture object returns references to all of the Pixel
objects encapsulated in the picture in a one-dimensional array.
Back to Question 8 (p. 891)
5.3.8.6.5 Answer 7
False. The Pixel class denes a large number of methods. Once you have a reference to a Pixel object,
you can manipulate the underlying pixel encapsulated in that object in a variety of ways.
Back to Question 7 (p. 891)
5.3.8.6.6 Answer 6
True.
Back to Question 6 (p. 890)
5.3.8.6.7 Answer 5
True.
Back to Question 5 (p. 888)
5.3.8.6.8 Answer 4
True.
Back to Question 4 (p. 888)
5.3.8.6.9 Answer 3
False. The code in Listing 2 (p. 887) causes an image to be displayed in the format shown in Image 2 (p.
894) .
Image 2. Answer 3.
5.231
5.3.8.6.10 Answer 2
False. The code in Listing 1 (p. 886) instantiates a new object of the Picture class.
Back to Question 2 (p. 886)
5.3.8.6.11 Answer 1
False. A color value is inverted by subtracting the value from 255 .
Back to Question 1 (p. 886)
5.3.8.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.9.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.10.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
93 .
5.3.10.2.1.1 Images
• Image 1 (p. 899) . The raw image.
• Image 2 (p. 900) . The modied image.
• Image 3 (p. 901) . Text output on the command-line screen.
5.3.10.2.1.2 Listings
• Listing 1 (p. 901) . The driver class named Prob03.
• Listing 2 (p. 902) . Beginning of the class named Prob03Runner.
• Listing 3 (p. 902) . The beginning of the run method.
• Listing 4 (p. 903) . Beginning of the for loop.
• Listing 5 (p. 904) . Compute the column number and scale factors.
• Listing 6 (p. 904) . Apply the scale factors.
• Listing 7 (p. 905) . Display the modied image.
• Listing 8 (p. 907) . Complete program listing.
5.3.10.3 Preview
The program that I will explain in this module is designed to be used as a test of the student's understanding
of programming using Java and Ericson's media library.
The student is provided an image le named Prob03.jpg along with a written specication of a
space-wise linear image modication algorithm.
Implement the algorithm
The primary purpose of the test is to determine if the student can implement the algorithm and also
satisfy some requirements for text output on the command line screen. Among other things, this requires
that the student be able to:
The algorithm
Scale the blue and green color components by a scale factor that is less than or equal to 1.0. The green
scale factor:
93 http://cnx.org/content/m44148/latest/
5.232
5.233
Dick Baldwin
Picture, filename Prob03.jpg height 274 width 365
5.234
The required output on the command-line screen is shown by the last two lines of text in Image 3 (p. 901)
. The remaining text in Image 3 (p. 901) is produced by the system during the compilation and execution
process.
5.235
There is nothing in Listing 1 (p. 901) that I haven't explained in earlier modules. Therefore, no expla-
nation of the code in Listing 1 (p. 901) should be required.
Beginning of the class named Prob03Runner
Prob03Runner
The class denition for the class named begins in Listing 2 (p. 902) .
class Prob03Runner{
//Instantiate the Picture object.
private Picture pic = new Picture("Prob03.jpg");
public Prob03Runner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
5.236
Once again, there is nothing in Listing 2 (p. 902) that I haven't explained before. I included it here
simply for the sake of continuity.
The beginning of the run method
The run method begins in Listing 3 (p. 902) . The run method is where most of the interesting
action takes place.
5.237
Much of what you see in Listing 3 (p. 902) has been explained in earlier modules. However, Listing 3 (p.
902) does deserve a few comments.
pixel = pixels[cnt];
green = pixel.getGreen();
blue = pixel.getBlue();
5.238
The loop iterates through the array of Pixel data, modifying the colors in one pixel during each
iteration.
The length property of the array object
length
Every array object in Java contains a property that contains the number of elements in the
array. The value of this property is used in the conditional clause in the for loop in Listing 4 (p. 903) to
establish when the end of the array has been reached in order to terminate the loop.
Get reference to the next Pixel object
for loop in Listing
The rst statement inside the 4 (p. 903) gets a reference to a Pixel object from
the next array element. That reference is stored in the local variable of type Pixel named pixel that
was declared in Listing 3 (p. 902) .
Get the red and green color values for the current pixel
Pixel object, the next statement
Having gotten a reference to the calls the getGreen method on
that reference to get and save the value of the green color component in the current pixel.
Similarly, the statement following that one gets and saves the value of the blue color component in the
current pixel.
int , and can range in value from 0 up to and including 255.
Both values are returned as type
Objective is to scale the green and blue color values
94 http://cnx.org/content/m44204/latest/Java3006old.htm#Organization_of_the_pixel_data
95 http://cnx.org/content/m44204/latest/Java3006old.htm#The_algorithm
Recall that the objective is to scale the green and blue color values on a column by column basis, going
from left to right across the image shown in Image 1 (p. 899) in order to produce the output image shown
in Image 2 (p. 900) .
Organization of the pixel data
The pixel data is stored in the array on a row by row basis. In other words, the rst width elements
contain references to pixels in the rst row of pixels going from left to right across the screen. The next
width elements contain references to pixels in the second row of pixels, etc.
Compute the column number and scale factors
Listing 5 (p. 904) uses the modulus operator to compute the column number for each Pixel object.
5.239
pixel.setGreen((int)(green * greenScale));
pixel.setBlue((int)(blue * blueScale));
}//end for loop
5.240
Then Listing 6 (p. 904) calls the setGreen and setBlue methods on the Pixel object to set the
green and blue color values to the newly computed values.
pic.explore();
5.241
5.3.10.5 Summary
In this module, I showed you how to implement an algorithm that causes the green and blue color values in
an image to change in a linear fashion going from left to right across the image.
96 http://cnx.org/content/m44204/latest/Prob03.jpg
· Part01
98
· Part02
99
· Part03
100
5.3.10.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
97 http://www.youtube.com/playlist?list=PL43014B9ED4419642
98 http://www.youtube.com/watch?v=pdqKvAuzkhg
99 http://www.youtube.com/watch?v=aXoSD7oauLQ
100 http://www.youtube.com/watch?v=1iRiXhTPmMU
class Prob03Runner{
//Instantiate the Picture object.
private Picture pic = new Picture("Prob03.jpg");
public Prob03Runner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
//----------------------------------------------------//
-end-
· 1 (p. 909) , 2 (p. 912) , 3 (p. 912) , 4 (p. 913) , 5 (p. 913) , 6 (p. 913) , 7 (p. 913)
5.3.11.2 Preface
This module contains review questions and answers keyed to the module titled Java3006: Implementing a
space-wise linear color-modication algorithm
102 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.11.3 Questions
5.3.11.3.1 Question 1 .
True or False? The program shown in Listing 1 (p. 910) will transform the image shown in Image 1 (p. 911)
into the image shown in Image 2 (p. 912) (or to an image that looks very similar to the image shown in
Image 2 (p. 912) ).
class Java3006rRunner{
//Instantiate the Picture object.
private Picture pic = new Picture("Java3006r.jpg");
public Java3006rRunner(){//constructor
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
//Accessor method
public Picture getPicture(){return pic;}
//----------------------------------------------------//
5.244
5.245
5.3.11.3.2 Question 2
True or False? The output shown in Image 2 (p. 912) was produced by calling the show method of
Ericson's Picture class.
Answer 2 (p. 915)
5.3.11.3.3 Question 3
True or False? A call to Ericson's getPixels method returns a reference to a one-dimensional array object.
The elements in the array are references to Pixel objects, where each Pixel object represents a single
pixel in an image.
Answer 3 (p. 915)
5.3.11.3.4 Question 4
True or False? A call to the getWidth method of Ericson's Picture class returns a double value that
species the width of the image in inches.
Answer 4 (p. 915)
5.3.11.3.5 Question 5
True or False? Every array object in Java contains a length property that contains the number of elements
in the array.
Answer 5 (p. 915)
5.3.11.3.6 Question 6
True or False? Having gotten a reference to a Pixel object, the getGreen method can be called on that
reference to get the value of the red color component in the current pixel.
Answer 6 (p. 915)
5.3.11.3.7 Question 7
True or False? Red, green, and blue color values range from 0 to 256.
Answer 7 (p. 915)
5.3.11.4 Images
• Image 1 (p. 911) . The image from Java3006r.jpg.
• Image 2 (p. 912) . Possible output image.
5.3.11.5 Listings
• Listing 1 (p. 910) . Source code for Java3006r.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.11.6 Answers
5.3.11.6.1 Answer 7
False. Red, green, and blue color values range from 0 to 255 .
Back to Question 7 (p. 913)
5.3.11.6.2 Answer 6
False. Having gotten a reference to a Pixel object, the getGreen method can be called on that reference
to get the value of the green color component in the current pixel.
Back to Question 6 (p. 913)
5.3.11.6.3 Answer 5
True.
Back to Question 5 (p. 913)
5.3.11.6.4 Answer 4
False. A call to the getWidth method of Ericson's Picture class returns an int value that species
the width of the image in pixels.
Back to Question 4 (p. 913)
5.3.11.6.5 Answer 3
True.
Back to Question 3 (p. 912)
5.3.11.6.6 Answer 2
False. The output shown in Image 2 (p. 912) was produced by calling the explore method of Ericson's
Picture class.
Back to Question 2 (p. 912)
5.3.11.6.7 Answer 1
True.
Back to Question 1 (p. 909)
5.3.11.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.12.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.13.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.3.13.2.1.1 Images
• Image 1 (p. 918) . Program output on the command line screen.
• Image 2 (p. 922) . Default behavior of the toString method.
• Image 3 (p. 923) . More on the default behavior of the toString method.
5.3.13.2.1.2 Listings
• Listing 1 (p. 919) . Source code for class Prob04.
• Listing 2 (p. 921) . Beginning of the class named Prob04MyClass.
• Listing 3 (p. 922) . Override the abstract getData method.
• Listing 4 (p. 922) . Override the toString method.
• Listing 5 (p. 926) . Complete program listing.
5.3.13.3 Preview
The program that I will explain in this module produces no graphics and does not require the use of Ericson's
media library.
OOP concepts
The program illustrates the following OOP concepts:
Program specications
Write a program named Prob04 that uses the class denition shown in Listing 1 (p. 919) to produce
the output on the command-line screen shown in Image 1 (p. 918) .
Prob04
Dick
Baldwin
95
95
5.246
import java.util.*;
System.out.println(objRef);
System.out.println(objRef.getData());
System.out.println(randomNumber);
}//end main
5.247
5.248
5.249
5.250
Prob04MyClass@42e816
5.251
107 http://cnx.org/content/m44205/latest/Java3008old.htm#concrete
Image 2 (p. 922) shows the default behavior of the toString method as dened in the Object class.
For this program, only the six hexadecimal digits at the end would change from one run to the next.
More on the default behavior of the toString method
Furthermore, if thetoString method had not been overridden in the Prob04MyClass class, the
output produced by the program on the command line screen would be similar to that shown in Image 3 (p.
923) instead of that shown in Image 1 (p. 918) .
Prob04
Dick
Prob04MyClass@42e816
-34
-34
5.252
• Prob04MyClass
• Prob04
• Object
Will satisfy type requirement...
Because it can be treated as type Object , it will satisfy the type requirement for the overloaded
version of the println method that requires an incoming parameter of type Object .
Call the toString method
The rst thing that this version of the println method does is to call the toString method on the
incoming reference. Then it displays the string value returned by the toString method on the screen.
In this case, the overridden toString method returns the string "Baldwin" , which is what you see
displayed in Image 1 (p. 918) .
Runtime polymorphism
This is a clear example of an OOP concept known as runtime polymorphism .
Runtime polymorphism is much too complicated to explain in this module. However, I explain it in
detail in my online OOP modules and I strongly recommend that you study it there until you thoroughly
understand it.
A critical concept
It is critical that you understand runtime polymorphism if you expect to go further in Java OOP.
It is almost impossible to write a useful Java application without making heavy use of runtime polymor-
phism, because that is the foundation of the event driven Java graphical user interface system.
Call the overridden getData method
The next statement in Listing 1 (p. 919) calls the overridden getData method and displays the return
value.
As you saw earlier, this method returns a copy of the random value that was received and saved by the
constructor for the Prob04MyClass class in Listing 2 (p. 921) .
Display the original random value
Finally, the last statement in the main method in Listing 1 (p. 919) displays the contents of the
instance variable named randomNumber . This variable contains the random value that was passed to
the constructor for the Prob04MyClass earlier in Listing 1 (p. 919) .
The two values must match
Therefore, the nal two statements in the main method in Listing 1 (p. 919) display the same random
value. This is shown in the command line screen output in Image 1 (p. 918) .
The program terminates
After displaying this value, the main method terminates causing the program to terminate.
5.3.13.6 Summary
You have learned about abstract methods, abstract classes, and overridden methods in this module. Very
importantly, you have learned about overriding the toString method.
· Part01
109
· Part02
110
108 http://www.youtube.com/playlist?list=PL6C202D624F8C5972
109 http://www.youtube.com/watch?v=wReb-ZdxgwQ
110 http://www.youtube.com/watch?v=AMe_hVVZ7CA
· Part03
111
· Part04
112
5.3.13.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
111 http://www.youtube.com/watch?v=DveltVjYqhQ
112 http://www.youtube.com/watch?v=EPwoHu3O1ww
5.253
-end-
· 1 (p. 927) , 2 (p. 929) , 3 (p. 929) , 4 (p. 929) , 5 (p. 929) , 6 (p. 929) , 7 (p. 929) , 8 (p. 930) ,
9 (p. 930) , 10 (p. 930) , 11 (p. 930) , 12 (p. 930)
5.3.14.2 Preface
This module contains review questions and answers keyed to the module titled Java3008: Abstract Methods,
Abstract Classes, and Overridden Methods
114 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.14.3 Questions
5.3.14.3.1 Question 1 .
True or False? The code in Listing 1 (p. 928) produces the output shown in Image 1 (p. 929) where the two
numeric values shown are random but must always match.
5.254
Java3008r
Dick
Baldwin
-80
-80
5.255
5.3.14.3.2 Question 2
True or False? The purpose of an abstract method declaration is to establish the signature of a method that
must be overridden in a (non-abstract) subclass of the class in which the abstract method is declared.
Answer 2 (p. 933)
5.3.14.3.3 Question 3
True or False? When an abstract method is executed, it always exhibits default behavior dened in the class
in which it is declared.
Answer 3 (p. 932)
5.3.14.3.4 Question 4
True or False? An abstract method must be overridden in a subclass in order to be executed.
Answer 4 (p. 932)
5.3.14.3.5 Question 5
True or False? An abstract method can be overridden once and once only and it must be overridden in the
immediate subclass of the class in which it is declared.
Answer 5 (p. 932)
5.3.14.3.6 Question 6
True or False? The existence of an abstract method in a superclass guarantees that objects instantiated
from every (non-abstract) subclass of that superclass will have a concrete (executable) version of a
method having that same signature.
Answer 6 (p. 932)
5.3.14.3.7 Question 7
True or False? Any class can be declared abstract. The consequence of declaring a class abstract is that it
is not possible to instantiate an object of the class.
Answer 7 (p. 932)
5.3.14.3.8 Question 8
True or False? A class must be declared abstract if it contains two or more abstract method declarations.
Answer 8 (p. 932)
5.3.14.3.9 Question 9
True or False? If a class inherits an abstract method, either the subclass must be declared abstract, or it
must provide a concrete overridden version of the inherited abstract method.
Answer 9 (p. 932)
5.3.14.3.10 Question 10
True or False? The primary purpose of a constructor is to assist in the initialization of the state of an object
, which depends on the values stored in its variables.
Answer 10 (p. 932)
5.3.14.3.11 Question 11
True or False? The default version of the toString method is dened in the class named Class .
Answer 11 (p. 932)
5.3.14.3.12 Question 12
True or False? There is an overloaded version of the println method that requires an incoming parameter
of type Object . When that version of the method is called, it calls the toString method on the
incoming object reference and displays the string that is returned by the toString method. If the
toString method belonging to the object has not been overridden, the default version of the toString
method will be executed and the string that will be displayed is the string returned by that default version.
The toString method can be overridden to cause the string that is displayed to be more appropriate for
the object. The toString method can be overridden only once in the class hierarchy.
Answer 12 (p. 932)
5.3.14.4 Images
• Image 1 (p. 929) . Possible output from the code in Listing 1.
• Image 2 (p. 933) . Output from code in Listing 1.
5.3.14.5 Listings
• Listing 1 (p. 928) . Source code for Java3008r.java.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.14.6 Answers
5.3.14.6.1 Answer 12
False. The toString method can be overridden by every class that inherits it.
Back to Question 12 (p. 930)
5.3.14.6.2 Answer 11
False. The default version of the toString method is dened in the class named Object .
Back to Question 11 (p. 930)
5.3.14.6.3 Answer 10
True.
Back to Question 10 (p. 930)
5.3.14.6.4 Answer 9
True.
Back to Question 9 (p. 930)
5.3.14.6.5 Answer 8
False. A class must be declared abstract if it contains one or more abstract method declarations.
Back to Question 8 (p. 930)
5.3.14.6.6 Answer 7
True.
Back to Question 7 (p. 929)
5.3.14.6.7 Answer 6
True.
Back to Question 6 (p. 929)
5.3.14.6.8 Answer 5
False. The same abstract method can be overridden in dierent ways in dierent subclasses. In other words,
the behavior of the overridden version can be tailored to (be appropriate for) the class in which it is
overridden.
Back to Question 5 (p. 929)
5.3.14.6.9 Answer 4
True.
Back to Question 4 (p. 929)
5.3.14.6.10 Answer 3
False. An abstract method has no body. Therefore, it is incomplete, has no behavior, and cannot be
executed.
Back to Question 3 (p. 929)
5.3.14.6.11 Answer 2
True.
Back to Question 2 (p. 929)
5.3.14.6.12 Answer 1
False. Listing 1 (p. 928) produces the output shown in Image 2 (p. 933) except that the numeric values may
vary from one run to the next. Note that the toString method is not overridden in Listing 1 (p. 928) .
Java3008r
Dick
Java3008rMyClass@4f1d0d
27
27
5.256
5.3.14.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.15.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
115 This content is available online at <http://cnx.org/content/m45624/1.3/>.
116 http://cnx.org/content/m44205
117 http://cnx.org/content/m45624/latest/a0-Index.htm
5.3.16.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.3.16.2.1.1 Images
• Image 1 (p. 936) . Program output on command line screen.
5.3.16.2.1.2 Listings
• Listing 1 (p. 937) . Beginning of the Prob05 class.
• Listing 2 (p. 938) . The class named Prob05MyClassA.
• Listing 3 (p. 939) . The next statement in the main method.
• Listing 4 (p. 940) . The class named Prob05MyClassB.
• Listing 5 (p. 941) . The end of the main method.
• Listing 6 (p. 943) . Complete program listing.
5.3.16.3 Preview
The program that I will explain in this module produces no graphics and does not require the use of Ericson's
media library.
OOP concepts
The program illustrates the following OOP concepts among others:
Program specications
Write a program named Prob05 that uses the class denition shown in Listing 1 (p. 937) to produce
an output similar to that shown in Image 1 (p. 936) on the command-line screen.
Prob05
Dick
Baldwin
-28
-28
5.257
A random value
Because the program generates and uses a random data value, the actual values displayed will dier from
one run to the next. However, in all cases, the two values shown in Image 1 (p. 936) must match.
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob05 which begins in Listing 1 (p. 937) .
import java.util.*;
class Prob05{
public static void main(String[] args){
5.258
Everything in Listing 1 (p. 937) should be familiar to you except for the last statement, which I will
explain shortly.
Characteristics of arrays in Java
Before explaining that statement, however, I will discuss some of the important characteristics of array
objects in Java. A list of such characteristics follows in no particular order:
• All arrays in Java are one-dimensional arrays. (Multidimensional arrays are created by creating tree
structures of one-dimensional arrays.)
• Each array in Java is encapsulated in a special type of object that I will refer to as an array object .
• As with all objects, an array object must be accessed using a reference to the array object.
• When the declared type of an array is one of the eight primitive types, the actual values are stored in
the array elements in the array object.
• When the declared type of an array is the type of an object (array object or ordinary object), references
to the objects are stored in the array elements and the objects actually exist elsewhere in memory.
• As with instance variables, the elements in an array are typically initialized with the standard default
values for the types involved (zero, false, or null) . That is not the case in this program however.
• The array that is encapsulated in an array object may have none, one, or more elements. (Yes, it is
possible for a Java array to have no elements, but that normally occurs only in special circumstances.)
• The length or size of the array is established when the array object is instantiated and cannot be
changed thereafter.
• Every array object contains a special property named length that contains the number of elements
in an array. It is always possible to determine the number of elements in an array object at runtime
by accessing the value of the length property for the array object.
A reference is returned
A reference to the array object is returned in much the same way that a constructor for an ordinary
object returns a reference to the object.
As is always the case, if the reference is stored in a variable, the type of the reference must be assignment
compatible with the type of the variable.
What is assignment compatible?
I recommend that you go to Google and search for the following keywords to learn more about this topic:
baldwin java "assignment compatible"
A one-element array
The last statement in Listing 1 (p. 937) instantiates an array object containing a one-element array. The
array element is initialized with a reference to a new object of type Prob05MyClassA , which exists
somewhere else in memory.
The value of a random number that was generated earlier in the main method is passed as a parameter
Prob05MyClassA
to the constructor for the object of type .
Save the reference to the array object
The reference to the array object is stored in the local reference variable named objRef of type Object
. We know that the reference is assignment compatible with this reference variable because the Object
type is completely generic. All non-primitive types are assignment compatible with type Object .
The class named Prob05MyClassA
At this point, I am going to put the explanation of the class named Prob05 temporarily on hold and
explain the class named Prob05MyClassA , which is shown in its entirety in Listing 2 (p. 938) .
5.259
Note that the class named Prob05MyClassA extends the class named Prob05 , which is partially
shown in Listing 1 (p. 937) .
Familiar code
All of the code in Listing 2 (p. 938) should be familiar to you because it is very similar to the code in
the previous module. Therefore, no explanation of Listing 2 (p. 938) is warranted.
Save the incoming value
In summary, when the object of type Prob05MyClassA is instantiated, it saves the value of an
incoming constructor parameter in a private instance variable.
Return the saved value
When the method namedgetData is called on a reference to the object, it returns a copy of that value.
A review
To review what I have already said, the array object that was instantiated in Listing 1 (p. 937) contains
a reference to this object of type Prob05MyClassA in the only element of the one-element array.
The reference to the array object is stored in the reference variable named objRef .
Indirection at work
At this point, objRef contains a reference to an array object, one element of which contains a reference
to an ordinary object, which is located somewhere else in memory. This is indirection.
The next statement in the main method
main method that began in Listing 1 (p. 937) , Listing 3 (p.
Returning now to the 939) shows the
next statement in the main method following the last statement in Listing 1 (p. 937) .
System.out.println(
new Prob05MyClassB().getDataFromObj(objRef[0]));
5.260
class Prob05MyClassB{
Prob05MyClassB(){
System.out.println("Baldwin");
}//end constructor
5.261
System.out.println(randomNumber);
}//end main
}//end class Prob05
5.262
This statement simply displays the original random value that was passed to the constructor for the
Prob05MyClassA in Listing 1 (p. 937) . This statement displays the second numeric value shown as the
last line of text in Image 1 (p. 936) .
The end of the program
At this point, themain method terminates causing the program to terminate.
5.3.16.6 Summary
You learned about the following OOP concepts, among others in this module.
· Part01
120
· Part02
121
· Part03
122
119 http://www.youtube.com/playlist?list=PL13622F7BA83F110C
120 http://www.youtube.com/watch?v=Ow_XzlSrmsw
121 http://www.youtube.com/watch?v=UiT_ZYtNqWo
122 http://www.youtube.com/watch?v=fCiMM4ps3o4
5.3.16.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob05{
public static void main(String[] args){
System.out.println(
new Prob05MyClassB().getDataFromObj(objRef[0]));
System.out.println(randomNumber);
}//end main
}//end class Prob05
//======================================================//
class Prob05MyClassB{
Prob05MyClassB(){
System.out.println("Baldwin");
}//end constructor
5.263
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
944 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
-end-
· 1 (p. 945) , 2 (p. 947) , 3 (p. 947) , 4 (p. 947) , 5 (p. 947) , 6 (p. 947) , 7 (p. 947) , 8 (p. 948) ,
9 (p. 948) , 10 (p. 948) , 11 (p. 948) , 12 (p. 948) , 13 (p. 948)
5.3.17.2 Preface
This module contains review questions and answers keyed to the module titled Java3010: Indirection, Array
Objects, and Casting
124 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.17.3 Questions
5.3.17.3.1 Question 1 .
True or False? The code shown in Listing 1 (p. 946) produces the output shown in Image 1 (p. 947) where
the numeric values are random and vary from one run to the next.
Listing 1. Question 1.
class Java3010ra{
public static void main(String[] args){
System.out.println(
new Java3010raMyClassB().getDataFromObj(objRef[0]));
System.out.println(randomNumber);
}//end main
}//end class Java3010ra
//======================================================//
class Java3010raMyClassB{
Java3010raMyClassB(){
System.out.println("Baldwin");
}//end constructor
Image 1. Question 1.
Java3010ra
Dick
Baldwin
-37
-37
5.265
5.3.17.3.2 Question 2
True or False? All array objects in Java contain one-dimensional array structures.
Answer 2 (p. 953)
5.3.17.3.3 Question 3
True or False? Each array in Java is encapsulated in an array object. An array object must be accessed
using a reference to the array object.
Answer 3 (p. 953)
5.3.17.3.4 Question 4
True or False? When the declared type of an array is one of the eight primitive types, the actual values are
stored in the array elements in the array object.
Answer 4 (p. 953)
5.3.17.3.5 Question 5
True or False? When the declared type of an array is the type of an object (array object or ordinary object)
, those objects are stored in the array elements.
Answer 5 (p. 953)
5.3.17.3.6 Question 6
True or False? Unless code is written to do otherwise, the elements in a new array object are initialized with
the standard default values for the types involved (zero, true, or null) .
Answer 6 (p. 953)
5.3.17.3.7 Question 7
True or False? The array structure that is encapsulated in an array object must have one, or more elements.
Answer 7 (p. 953)
5.3.17.3.8 Question 8
True or False? The length or size of the array is established when the array object is instantiated and
cannot be changed thereafter.
Answer 8 (p. 953)
5.3.17.3.9 Question 9
True or False? Every array object contains a special property named size that contains the number of
elements in an array. It is always possible to determine the number of elements in an array object at runtime
by accessing the value of the size property for the array object.
Answer 9 (p. 953)
5.3.17.3.10 Question 10
True or False? There is a special syntax that allows for the instantiation of an array object and the
initialization of the array elements in a single statement.
Answer 10 (p. 952)
5.3.17.3.11 Question 11
True or False? An anonymous class is an object whose reference is not saved in a named reference variable.
Answer 11 (p. 952)
5.3.17.3.12 Question 12
True or False? Every class that doesn't explicitly extend another class automatically extends the class named
Class .
Answer 12 (p. 952)
5.3.17.3.13 Question 13
True or False? The code shown in Listing 3 (p. 949) produces the output shown in Image 3 (p. 950) where
the numeric values are random and vary from one run to the next.
class Java3010rb{
public static void main(String[] args){
System.out.println(
new Java3010rbMyClassB().getDataFromObj(objRef[0]));
System.out.println(randomNumber);
}//end main
}//end class Java3010rb
//======================================================//
class Java3010rbMyClassB{
Java3010rbMyClassB(){
System.out.println("Baldwin");
}//end constructor
Java3010rb
Dick
Baldwin
120
120
5.267
5.3.17.4 Images
• Image 1 (p. 947) . Question 1.
• Image 2 (p. 954) . Answer 1.
• Image 3 (p. 950) . Question 13.
• Image 4 (p. 952) . Answer 13.
5.3.17.5 Listings
• Listing 1 (p. 946) . Question 1.
• Listing 2 (p. 952) . Answer 10.
• Listing 3 (p. 949) . Question 13.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.17.6 Answers
5.3.17.6.1 Answer 13
False: The code shown in Listing 3 (p. 949) produces the compiler error shown in Image 4 (p. 952) . A cast
is required to x the problem.
5.268
5.3.17.6.2 Answer 12
False. Every class that doesn't explicitly extend another class automatically extends the class named Object
.
Back to Question 12 (p. 948)
5.3.17.6.3 Answer 11
False. An anonymous object is an object whose reference is not saved in a named reference variable. An
anonymous class is something entirely dierent.
Back to Question 11 (p. 948)
5.3.17.6.4 Answer 10
True. Listing 2 (p. 952) shows an example of this syntax. (Note the use of the curly brackets in Listing 2
(p. 952) as opposed to the use of square brackets in Listing 1 (p. 946) .)
5.269
5.3.17.6.5 Answer 9
False. Every array object contains a special property named length that contains the number of elements
in an array. It is always possible to determine the number of elements in an array object at runtime by
accessing the value of the length property for the array object.
Back to Question 9 (p. 948)
5.3.17.6.6 Answer 8
True.
Back to Question 8 (p. 948)
5.3.17.6.7 Answer 7
False. The array structure that is encapsulated in an array object may have none, one, or more elements.
Back to Question 7 (p. 947)
5.3.17.6.8 Answer 6
False. Unless code is written to do otherwise, the elements in a new array object are initialized with the
standard default values for the types involved (zero, false , or null) .
Back to Question 6 (p. 947)
5.3.17.6.9 Answer 5
False. When the declared type of an array is the type of an object (array object or ordinary object),
references to the objects are stored in the array elements and the objects actually exist elsewhere in memory.
Back to Question 5 (p. 947)
5.3.17.6.10 Answer 4
True.
Back to Question 4 (p. 947)
5.3.17.6.11 Answer 3
True.
Back to Question 3 (p. 947)
5.3.17.6.12 Answer 2
True. Multidimensional arrays are created by creating tree structures of one-dimensional array objects.
Back to Question 2 (p. 947)
5.3.17.6.13 Answer 1
False. The program produces the compiler error shown in Image 2 (p. 954) .
Image2. Answer 1.
5.270
5.3.17.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.18.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
126 http://cnx.org/content/m44206
127 http://cnx.org/content/m45625/latest/a0-Index.htm
128 This content is available online at <http://cnx.org/content/m44207/1.6/>.
5.3.19.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
129 .
5.3.19.2.1.1 Images
• Image 1 (p. 957) . Raw image.
• Image 2 (p. 958) . Modied image.
• Image 3 (p. 959) . Required text output.
5.3.19.2.1.2 Listings
• Listing 1 (p. 959) . The driver class named Prob01.
• Listing 2 (p. 960) . The constructor for the class named Prob01Runner.
• Listing 3 (p. 960) . Beginning of the method named run.
• Listing 4 (p. 961) . Beginning of the mirrorUpperQuads method.
• Listing 5 (p. 961) . Mirror pixel colors around the midpoint.
• Listing 6 (p. 962) . Remainder of the run method.
• Listing 7 (p. 963) . The method named mirrorHoriz.
• Listing 8 (p. 965) . Complete program listing..
5.3.19.3 Preview
In this module, you will learn how to use nested for loops to process pixels on a row and column basis.
Program specications
Write a program named Prob01 that uses the class denition shown in Listing 1 (p. 959) along with
Ericson's media library and the image le named Prob01.jpg to produce the graphic output images shown
in Image 1 (p. 957) and Image 2 (p. 958) .
129 http://cnx.org/content/m44148/latest/
5.271
5.272
5.273
• Examine the input and output images and determine how the input image has been modied to produce
the output image.
• Manipulate the individual pixels in the image to perform the required modications.
5.274
There is nothing in Listing 1 (p. 959) that I haven't explained in earlier modules.
The println statement in Listing 1 (p. 959) causes the second line of text to be displayed in Image 3
(p. 959) .
class Prob01Runner{
public Prob01Runner(){
System.out.println("Display your name here.");
}//end constructor
5.275
The code in Listing 2 (p. 960) simply causes the rst line of text in Image 3 (p. 959) to be displayed on
the command line screen.
Beginning of the method named run
The code in the driver class in Listing 1 (p. 959) instantiates a new object of the Prob01Runner class
and immediately calls the run method belonging to that object. The run method begins in Listing 3
(p. 960) .
5.276
5.277
return pix;
}//end mirrorUpperQuads
5.278
The outer loop in Listing 5 (p. 961) iterates down through each of the rows in the top half of the image.
The inner loop iterates across the left half of each row, copying the color of the pixels from the left half
to the corresponding mirror-image pixels on the right half.
Return a reference to the modied object
Finally, Listing 5 (p. 961) returns a reference to the modied Picture object. The reference is assigned
to the variable namedpix in Listing 3 (p. 960) .
Superuous but self-documenting code
Returning and storing a reference to the modied picture is superuous and unnecessary. The code in
Listing 3 (p. 960) already has a reference to the picture and that reference doesn't change just because the
object to which it refers is modied.
However, I prefer this programming style because I consider it to be more self-documenting.
Remainder of the run method
run method, Listing 6 (p.
Returning now to the 962) calls the method named mirrorHoriz to mirror
the top half of the image into the bottom half. (I will explain the mirrorHoriz method shortly.)
pix.explore();
return pix;
}//end run
5.279
return pix;
}//end mirrorHoriz
//----------------------------------------------------//
5.280
5.3.19.5 Summary
In this module, you learned how to use nested for loops to process pixels on a row and column basis.
130 http://cnx.org/content/m44207/latest/Prob01.jpg
· Part01
132
· Part02
133
5.3.19.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
131 http://www.youtube.com/playlist?list=PLB8C60363CB918BAA
132 http://www.youtube.com/watch?v=JOhc503IPj8
133 http://www.youtube.com/watch?v=vQBdVdqAxq4
class Prob01Runner{
public Prob01Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public Picture run(){
Picture pix = new Picture("Prob01.jpg");
//Display the input picture.
pix.explore();
}//end run
//----------------------------------------------------//
return pix;
}//end mirrorUpperQuads
//----------------------------------------------------//
966 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
-end-
5.3.20.2 Preface
This module contains review questions and answers keyed to the module titled Java3012: Using Nested
Loops to Process Pixels
135 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.20.3 Questions
5.3.20.3.1 Question 1 .
True or False? The code shown in Listing 1 (p. 968) will transform the image shown in Image 1 (p. 969)
into the image shown in Image 2 (p. 970) .
Listing 1. Question 1.
class Java3012raRunner{
public Java3012raRunner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture pix = new Picture("Java3012ra.jpg");
}//end run
//----------------------------------------------------//
return pix;
}//end mirrorUpperQuads
//----------------------------------------------------//
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
5.283
5.284
5.3.20.3.2 Question 2
True or False? The code in Listing 2 (p. 971) instantiates an object of an anonymous class.
Listing 2. Question 2.
new Java3012raRunner().run();
5.285
5.3.20.3.3 Question 3
True or False? The code in Listing 2 (p. 971) instantiates an anonymous object..
Answer 3 (p. 973)
5.3.20.3.4 Question 4
True or False? The statement shown in Listing 3 (p. 971) will return a reference to a Pixel object that
represents a physical pixel located at a horizontal coordinate of col and a vertical coordinate of row .
Listing 3. Question 4.
leftPixel = pix.getPixels(col,row);
5.286
5.3.20.4 Images
• Image 1 (p. 969) . Image from the le named Java3012ra.jpg.
• Image 2 (p. 970) . Possible output produced by the program in Listing 1.
5.3.20.5 Listings
• Listing 1 (p. 968) . Question 1.
• Listing 2 (p. 971) . Question 2.
• Listing 3 (p. 971) . Question 4.
• Listing 4 (p. 973) . Answer 4.
The image is also an example of the kinds of things that we do in my course titled ITSE 2321, Object-
Oriented Programming.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.20.6 Answers
5.3.20.6.1 Answer 4
False. The code in Listing 3 (p. 971) has the wrong spelling for the method that returns the Pixel object.
The correct spelling is shown in Listing 4 (p. 973) . You learned about the spelling (with no parameters)
shown in Listing 3 (p. 971) in an earlier module.
Listing 4. Answer 4.
leftPixel = pix.getPixel(col,row);
5.287
5.3.20.6.2 Answer 3
True. The object instantiated from the class named Java3012raRunner is an anonymous object because
its reference is not saved in a named reference variable in the current scope. Anonymous classes and
5.3.20.6.3 Answer 2
False. A discussion of anonymous classes would be a somewhat advanced topic. That topic is not explained
in the module named Java3012: Using Nested Loops to Process Pixels
136 .
Back to Question 2 (p. 970)
5.3.20.6.4 Answer 1
True.
Back to Question 1 (p. 967)
5.3.20.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
136 http://cnx.org/content/m44207
137 This content is available online at <http://cnx.org/content/m45626/1.2/>.
5.3.21.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
138 http://cnx.org/content/m44207
139 http://cnx.org/content/m45626/latest/a0-Index.htm
140 This content is available online at <http://cnx.org/content/m44238/1.7/>.
5.3.22.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
141 .
5.3.22.2.1.1 Images
• Image 1 (p. 977) . Raw buttery image.
• Image 2 (p. 978) . Beach scene with student's name added.
• Image 3 (p. 979) . Composite image.
• Image 4 (p. 980) . Required text output.
• Image 5 (p. 984) . Cropped and ipped version of the buttery image.
• Image 6 (p. 988) . Partially complete version of the output picture.
5.3.22.2.1.2 Listings
• Listing 1 (p. 981) . The driver class named Prob02.
• Listing 2 (p. 981) . Beginning of the Prob02Runner class.
• Listing 3 (p. 982) . Beginning of the run method.
• Listing 4 (p. 982) . Beginning of the cropAndFlip method.
• Listing 5 (p. 983) . Process using nested loops.
• Listing 6 (p. 984) . Call the copyPictureWithCrop method from the run method..
• Listing 7 (p. 985) . Beginning of the method named copyPictureWithCrop.
• Listing 8 (p. 987) . Process using nested loops.
• Listing 9 (p. 989) . The remainder of the run method.
• Listing 10 (p. 992) . Complete program listing.
5.3.22.3 Preview
In this module, you will learn how to:
• Work directly with individual pixels and keep track of coordinate values.
• Copy a portion of one picture into a specic location in another picture.
141 http://cnx.org/content/m44148/latest/
Program specications
Write a program named Prob02 that uses the class denition shown in Listing 1 (p. 981) and Ericson's
media library along with the image les named Prob02a.jpg and Prob02b.jpg to produce the three
graphic output images shown in Image 1 (p. 977) , Image 2 (p. 978) , and Image 3 (p. 979) .
5.288
5.289
5.290
5.291
• Work directly with individual pixels and keep track of coordinate values.
• Copy a portion of one picture into a specic location in another picture.
• Crop and ip a picture.
import java.awt.Color;
System.out.println(pictures[0]);
System.out.println(pictures[1]);
System.out.println(pictures[2]);
}//end main method
}//end class Prob02
5.292
class Prob02Runner{
public Prob02Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
5.293
The constructor simply causes the student's name to be displayed on the command line screen, producing
the rst line of output text shown in Image 4 (p. 980) .
Beginning of the run method
The run method, that was called in Listing 1 (p. 981) begins in Listing 3 (p. 982) .
5.294
Listing 3 (p. 982) instantiates two Picture objects from image les and displays them by calling the
explore method on each Picture object. In addition, the student's name is added near the upper-left
corner of the beach image. This code results in the images shown in Image 1 (p. 977) and Image 2 (p. 978)
.
Call the cropAndFlip method
Then Listing 3 (p. 982) calls the cropAndFlip method passing the reference to the buttery image
of Image 1, along with some other information as parameters. The return value is stored in a new local
reference variable of type Picture named picC .
Put discussion of the run method on hold
I will put the discussion of the run method on temporary hold at this point and explain the method
named cropAndFlip , which begins in Listing 4 (p. 982) .
Beginning of the cropAndFlip method
The cropAndFlip method crops a picture to the specied coordinate values and ips it around a
vertical line at its center.
5.295
Incoming parameters
In addition to a reference to the picture to be processed, the method receives four incoming integer values
as parameters. The parameters named x1 and y1 specify the coordinates of the upper-left corner of a
rectangular area of the picture that is to be retained in the output.
The parameters named x2 and y2 specify the coordinates of the lower-right corner of the rectangular
area of the picture that is to be retained in the output.
An empty Picture object
Listing 4 (p. 982) begins by creating an empty Picture object of the correct size to hold the cropped
image. A reference to the empty picture is saved in the local reference variable named output .
Then Listing 4 (p. 982) gets and saves the width of the output picture.
Following this, Listing 4 (p. 982) declares two local working variables named pixel (of type Pixel )
and color (of type Color ) .
Process using nested loops
Listing 5 (p. 983) uses a pair of nested for loops to cause the output picture to be a cropped version
of the picture received as an incoming parameter. The cropped image is ipped around its center.
return output;
}//end cropAndFlip method
5.296
The code in Listing 5 (p. 983) copies the pixel colors of the selected pixels of the incoming image to the
pixels of the output image, ipping the image around its center line in the process.
Cropped and ipped version of the buttery image
output in Listing
If you display the picture referred to by 5 (p. 983) , you will get the image shown
in Image 5 (p. 984) .
5.297
copyPictureWithCrop(picA,picB,82,70,4,5,77,101);
5.298
5.299
note: Not really cropped For clarity, I will refer to this as a cropped source picture even
though the program doesn't actually save a cropped version of the picture as was the case with the
cropAndFlip method.
The program simply copies a rectangular portion of the source picture into the destination picture.
The parameters named xCoor and yCoor in Listing 7 (p. 985) specify the upper-left corner of the
rectangular area of pixels that is to be preserved when the source image is cropped.
Coordinate values of (4,5) are passed for these two values when the method is called in Listing 6 (p. 984)
.
Same values as Listing 3
Note that these are the same two values that were passed for this purpose when the cropAndFlip
method was called in Listing 3 (p. 982) .
Two ways to specify a rectangle
There are two commonly used ways to specify a rectangular area in programming. One way is to specify
the coordinates of the upper-left and bottom right corners. This is the approach used in the cropAndFlip
method in Listing 4 (p. 982) .
The other way is to specify the coordinates of the upper-left corner and then to specify the width and
copyPictureWithCrop
the height. This is the approach used in the method in Listing 7 (p. 985) .
The width and height parameters
The parameters named width and height in Listing 7 (p. 985) specify the width and height of the
rectangular area of pixels that is to be preserved when the source picture is cropped.
If you compare the width and height parameter values passed in Listing 6 (p. 984) with the coordinate
values passed in Listing 3 (p. 982) , you will see that the same rectangular area of the buttery image is
being preserved after cropping in both cases.
Conrm that the cropped image will t
Listing 7 (p. 985) begins by conrming that the cropped rectangular area of the source picture will t
within the destination picture when placed at the specied location. If the conditional clause of the if
statement returns true, then the code in the body of the statement will be executed. If not, control bypasses
the body of the if statement and the source picture will not be copied into the destination picture.
Process using nested for loops
As was the case in Listing 4 (p. 982) , Listing 7 (p. 985) declares two working variables named pixel
and color .
The variables named pixel and color are used along with various parameter values in the pair of
nested for loops shown in Listing 8 (p. 987) to crop the source picture and to copy the cropped source
picture into the destination picture at the specied location.
}//end if
5.300
5.301
At this point, only one cropped version of the buttery image has been copied into the beach image.
Return control to the run method
ThecopyPictureWithCrop method terminates in Listing 8 (p. 987) and returns control to the run
method, picking up where Listing 6 (p. 984) left o.
The remainder of the run method
run method is shown in Listing 9 (p.
The remainder of the 989) .
copyPictureWithCrop(picC,picB,161,70,0,0,77,101);
picB.explore();
5.302
142 http://cnx.org/content/m44238/latest/Prob02a.jpg
143 http://cnx.org/content/m44238/latest/Prob02b.jpg
5.3.22.7 Summary
In this module, you learned how to:
• Work directly with individual pixels and keep track of coordinate values.
• Copy a portion of one picture into a specic location in another picture.
• Crop and ip a picture.
· Part01
145
· Part02
146
· Part03
147
5.3.22.10 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
144 http://www.youtube.com/playlist?list=PL3D7CCC0D884E2EF4
145 http://www.youtube.com/watch?v=AY1oMeuFWwY
146 http://www.youtube.com/watch?v=IWNm1xWA7wQ
147 http://www.youtube.com/watch?v=P0thqN0Fofs
System.out.println(pictures[0]);
System.out.println(pictures[1]);
System.out.println(pictures[2]);
}//end main method
}//end class Prob02
//======================================================//
class Prob02Runner{
public Prob02Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
copyPictureWithCrop(picA,picB,82,70,4,5,77,101);
copyPictureWithCrop(picC,picB,161,70,0,0,77,101);
picB.explore();
-end-
5.3.23.2 Preface
This module contains review questions and answers keyed to the module titled Java3014: Cropping, Flipping,
and Combining Pictures
149 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.23.3 Questions
5.3.23.3.1 Question 1 .
True or False? The code in Listing 1 (p. 995) combined with the images in Image 1 (p. 996) and Image 2
(p. 996) produces the output shown in Image 3 (p. 997) .
Listing 1. Question 1.
class Java3014raRunner{
}//end run
//----------------------------------------------------//
return output;
}//end crop and flip
//----------------------------------------------------//
Image 1. Prob02a.jpg.
5.305
Image 2. Prob02b.jpg.
5.306
5.307
5.3.23.3.2 Question 2
True or False? The call to the run method in Listing 2 (p. 998) returns a reference to an object of the class
Picture .
Listing 2. Question 2.
5.308
5.3.23.4 Images
• Image 1 (p. 996) . Prob02a.jpg.
• Image 2 (p. 996) . Prob02b.jpg.
• Image 3 (p. 997) . Possible output image.
• Image 4 (p. 1001) . Answer 1.
5.3.23.5 Listings
• Listing 1 (p. 995) . Question 1.
• Listing 2 (p. 998) . Question 2.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.23.6 Answers
5.3.23.6.1 Answer 2
False. The call to the run method in Listing 2 (p. 998) returns a reference to an array object whose elements
may or may not contain references to objects of the class Picture (or some subclass of the class Picture
) . However, since array objects in Java may have a length of 0, without seeing the source code for the
run method, it is impossible to know what is contained in the array object.
Back to Question 2 (p. 997)
5.3.23.6.2 Answer 1
False. The code in Listing 1 (p. 995) combined with the images in Image 1 (p. 996) and Image 2 (p. 996)
produces the output shown in Image 4 (p. 1001) .
Image 4. Answer 1.
5.309
5.3.23.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.24.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.25.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
154 .
5.3.25.2.1.1 Images
• Image 1 (p. 1005) . Input image le Prob03a.bmp.
• Image 2 (p. 1006) . Input image le Prob03b.bmp.
• Image 3 (p. 1007) . Input image le Prob03c.bmp.
• Image 4 (p. 1008) . Input image le Prob03d.jpg.
• Image 5 (p. 1009) . Output picture.
• Image 6 (p. 1010) . Required output text.
• Image 7 (p. 1013) . Front view of the skater after cropping.
5.3.25.2.1.2 Listings
• Listing 1 (p. 1011) . The driver class named Prob03.
• Listing 2 (p. 1011) . Beginning of the class named Prob03Runner.
• Listing 3 (p. 1012) . Beginning of the run method.
• Listing 4 (p. 1014) . Remainder of the run method.
• Listing 5 (p. 1016) . The greenScreenDraw method.
• Listing 6 (p. 1019) . Complete program listing.
5.3.25.3 Preview
n this lesson, you will learn how to write a program to do green-screen processing to superimpose a
source image onto a destination image while making the green background of the source image appear to be
transparent.
Program specications
Write a program named Prob03 that uses the class denition shown in Listing 1 (p. 1011) and Ericson's
media library along with the image les in the following list to produce the ve graphic output images shown
in Image 1 (p. 1005) through Image 5 (p. 1009) .
• Prob03a.bmp
• Prob03b.bmp
• Prob03c.bmp
• Prob03d.jpg
5.310
5.311
5.312
5.313
5.314
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob03 given in Listing 1 (p. 1011) .
Required output text
In addition to the output images mentioned above, your program must display your name and one other
line of text on the command-line screen as shown in Image 6 (p. 1010) .
5.315
155 http://www.alice.org/
import java.awt.Color;
5.316
The main method in Listing 1 (p. 1011) instantiates a new object of the class named Prob03Runner
and calls the method named run that belongs to that object.
When the run method returns, the program terminates.
Beginning of the class named Prob03Runner
The beginning of the class named Prob03Runner , and its constructor, is shown in Listing 2 (p. 1011)
.
class Prob03Runner{
public Prob03Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
5.317
The constructor simply displays the student's name on the command line screen producing the rst line
of text shown in Image 6 (p. 1010) .
Beginning of the run method
run method that is called in Listing 1 (p.
The beginning of the 1011) is shown in Listing 3 (p. 1012) .
5.318
The code in Listing 3 (p. 1012) instantiates, displays, and crops the four input images.
All four images must be cropped to remove the Alice runtime window. In addition, the three skater
images are also cropped to remove excess blank green background material.
Image formats: bmp versus jpg
Note that the three views of the skater are extracted from bmp image les instead of jpg image les.
This is necessary in order to preserve the pure green background color. Storing the images as jpg les
would corrupt the background color in the low order bits making it more dicult to achieve the green-screen
processing required by this program.
The method named crop
crop method
Listing 3 calls the four times in succession. once for each of the four Picture objects
instantiated from the image les.
I explained image cropping in an earlier module. The crop method used in this program is very similar
to the methods that I explained in the earlier module, so I won't explain it again in this module. You can
view the crop method in detail in Listing 6 (p. 1019) near the end of the module.
Five incoming parameters
The crop method requires ve incoming parameters. The rst parameter is a reference to the Picture
object that is to be cropped. The remaining four integer parameters specify the rectangular area that is to
be preserved after the picture is cropped.
The rectangular area to be preserved
The rst two integers specify the column and row coordinates for the upper-left corner of the rectangular
area that is to be preserved. The last two integers specify the width and the height of the rectangle that is
to be preserved.
Note that in all four cases, the height of the rectangular area that is to be preserved is 256 pixels. This
will be important later on with respect to scaling two of the images.
Returns a reference to a cropped picture
The crop method returns a reference to a Picture object that is a cropped version of the picture
whose reference is passed to the method. In each case, the code in Listing 3 (p. 1012) replaces the reference
to the original Picture object with the reference to the cropped Picture object.
Front view of the skater after cropping
If you were to display the Picture object referred to by the variable front after cropping, you would
see the image shown in Image 7 (p. 1013) .
5.319
Transparent pixels
This is the image that appears as the center ice skater in Image 5 (p. 1009) after green-screen processing.
Note that all of the green pixels in Image 7 (p. 1013) appear to be transparent in Image 5 (p. 1009) .
Remainder of the run method
run method,
Continuing with the Listing 4 (p. 1014) calls the method named greenScreenDraw
three times in succession to draw the three skater images at specic locations on the snow scene with green-
screen processing.
5.320
}//end greenScreenDraw
5.321
weather map pixels to show with the exception of those that are replaced by the pixels that comprise the
human forecaster. (The forecaster must be careful to avoid wearing clothing that matches the color of the
green or blue screen.)
Returning to the run method
When the third call to thegreenScreenDraw method returns in Listing 4 (p. 1014) , the run
method:
1. Prob03a.bmp
156
2. Prob03b.bmp
157
3. Prob03c.bmp
158
4. Prob03d.jpg
159
5.3.25.7 Summary
In this module, you learned how to write a program to do green-screen processing to superimpose a
source image onto a destination image while making the green background of the source image appear to be
transparent.
· Part01
161
· Part02
162
· Part03
163
156 http://cnx.org/content/m44210/latest/Prob03a.bmp
157 http://cnx.org/content/m44210/latest/Prob03b.bmp
158 http://cnx.org/content/m44210/latest/Prob03c.bmp
159 http://cnx.org/content/m44210/latest/Prob03d.jpg
160 http://www.youtube.com/playlist?list=PLF12CDA1C72ACC167
161 http://www.youtube.com/watch?v=EW6ZEDGJi2w
162 http://www.youtube.com/watch?v=JqK_42UnXoI
163 http://www.youtube.com/watch?v=4bM6qElbxpc
5.3.25.10 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob03Runner{
public Prob03Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
-end-
· 1 (p. 1021)
5.3.26.2 Preface
This module contains review questions and answers keyed to the module titled Java3016: Green-Screen
Processing
165 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.26.3 Questions
5.3.26.3.1 Question 1 .
Given Image 1 (p. 1023) , Image 2 (p. 1024) , Image 3 (p. 1025) , and Image 4 (p. 1026) , which of the
following output images is produced by the code in Listing 1 (p. 1022) ?
A. Image 5 (p. 1027)
B. Image 6 (p. 1028)
Listing 1. Question 1.
class Java3016raRunner{
greenScreenDraw(crop(new Picture("Prob03a.bmp"),
123,59,110,256),snowScene,117,0);
greenScreenDraw(
crop(new Picture("Prob03c.bmp"),123,59,110,256).
getPictureWithHeight(256/2),snowScene,55,64);
greenScreenDraw(
crop(new Picture("Prob03b.bmp"),123,59,110,256).
getPictureWithHeight(256/3),snowScene,260,96);
snowScene.explore();
//----------------------------------------------------//
Image 1. Prob03a.bmp.
5.324
Image 2. Prob03b.bmp.
5.325
Image 3. Prob03c.bmp.
5.326
Image 4. Prob03d.jpg.
5.327
5.328
5.329
5.3.26.4 Images
• Image 1 (p. 1023) . Prob03a.bmp.
• Image 2 (p. 1024) . Prob03b.bmp.
• Image 3 (p. 1025) . Prob03c.bmp.
• Image 4 (p. 1026) . Prob03d.jpg.
• Image 5 (p. 1027) . Possible output image.
5.3.26.5 Listings
• Listing 1 (p. 1022) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.26.6 Answers
5.3.26.6.1 Answer 1
The code in Listing 1 (p. 1022) produces the output image shown in Image 6 (p. 1028) .
Back to Question 1 (p. 1021)
5.3.26.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.27.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
166 This content is available online at <http://cnx.org/content/m45637/1.2/>.
167 http://cnx.org/content/m44210
168 http://cnx.org/content/m45637/latest/a0-Index.htm
5.3.28.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
170 .
5.3.28.2.1.1 Images
• Image 1 (p. 1034) . Input le Prob04a.bmp.
• Image 2 (p. 1035) . Input le Prob04b.bmp.
• Image 3 (p. 1036) . Input le Prob04c.jpg.
• Image 4 (p. 1037) . Required output image.
• Image 5 (p. 1038) . Required text output.
• Image 6 (p. 1040) . Cropped version of the snow scene image.
• Image 7 (p. 1045) . The skater with a red tint applied.
5.3.28.2.1.2 Listings
• Listing 1 (p. 1038) . The driver class named Prob04.
• Listing 2 (p. 1039) . Beginning of the class named Prob04Runne.
• Listing 3 (p. 1039) . Beginning of the run method.
• Listing 4 (p. 1041) . Darken the background of the snow scene.
• Listing 5 (p. 1042) . Beginning of the darkenBackground method.
• Listing 6 (p. 1042) . Beginning of the processing loop.
5.3.28.3 Preview
In this module, you will learn how to darken, brighten, and tint the colors in a Picture object.
Program specications
Write a program named Prob04 that uses the class denition shown in Listing 1 (p. 1038) and Ericson's
media library along with the image les in the following list to produce the four graphic output images shown
in Image 1 (p. 1034) through Image 4 (p. 1037) .
• Prob04a.bmp
• Prob04b.bmp
• Prob04c.jpg
5.330
5.331
5.332
5.333
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob04 shown in Listing 1 (p. 1038) .
Required text output
In addition to the four output images mentioned above, your program must display your name and the
other line of text shown in Image 5 (p. 1038) on the command-line screen.
5.334
import java.awt.Color;
5.335
class Prob04Runner{
public Prob04Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
5.336
Listing 2 (p. 1039) shows the constructor for the class, which simply displays the student's name on the
command line screen as shown in Image 5 (p. 1038) .
Beginning of the run method
The beginning of therun method, which is called in Listing 1 (p. 1038) , is shown in Listing 3 (p.
1039) .
5.337
Listing 3 (p. 1039) calls a method named crop on all three Picture objects to eliminate the Alice
runtime controls. Note that the same rectangular area is preserved for all three images. Thus, all three
images are the same size after cropping.
The cropped snow scene image
If you were to display the picture whose reference is stored in the variable named snowScene after
the crop method returns, you would see the image shown in Image 6 (p. 1040) with the Alice runtime
controls no longer visible.
5.338
darkenBackground(hole,snowScene);
5.339
5.340
5.341
• Gets the color from the corresponding pixel in the destination array.
• Calls the method named darker , which is a method of the Color class in the standard Sun library,
to produce a darker version of the pixel color.
• Replaces the pixel color in the destination array with the darker version of the color.
}else{
//Apply a red tint to the corresponding pixel in
// the destination.
color = destPixels[cnt].getColor();
red = color.getRed();
if(red*1.25 < 255){
red = (int)(red * 1.25);
}else{
red = 255;
}//end else
green = (int)(color.getGreen() * 0.8);
blue = (int)(color.getBlue() * 0.8);
destPixels[cnt].setColor(new Color(red,green,blue));
}//end else
}//end for loop
}//end darkenBackground
5.342
The objective is to modify the pixel color in the destination picture at this location to give it a red tint
as shown in Image 4 (p. 1037) .
Get, save, and modify the red color value
Listing 7 (p. 1043) begins by getting the color of the pixel from the current location in the destination
picture. It extracts and saves the red color value of the pixel. Then, depending on the current value of the
red color value, it either:
redTint(skater);
5.343
The redTint method assumes that the image being processed has a pure green background like that
shown in Image 1 (p. 1034) . The method applies an algorithm very similar to that shown in Listing 7 (p.
1043) to apply a red tint to every pixel that is not pure green.
Because of the similarity of the code in the redTint method and the code in Listing 7 (p. 1043) ,
a detailed explanation of the redTint method should not be required. You can view the method in its
entirety in Listing 10 (p. 1049) near the end of the module.
The skater with the red tint applied
If you were to display the picture referred to by skater immediately after the redTint method returns
in Listing 8 (p. 1044) , you would see the image shown in Image 7.
5.344
snowScene.explore();
System.out.println(snowScene);
5.345
• Prob04a.bmp
172
• Prob04b.bmp
173
• Prob04c.jpg
174
172 http://cnx.org/content/m44234/latest/Prob04a.bmp
173 http://cnx.org/content/m44234/latest/Prob04b.bmp
174 http://cnx.org/content/m44234/latest/Prob04c.jpg
5.3.28.7 Summary
In this module, you learned how to darken, brighten, and tint the colors in a Picture object.
· Part01
176
· Part02
177
· Part03
178
5.3.28.10 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
175 http://www.youtube.com/playlist?list=PL11F9AC688AC89E56
176 http://www.youtube.com/watch?v=T-pcmz5XmQY
177 http://www.youtube.com/watch?v=T16JMwpBIUI
178 http://www.youtube.com/watch?v=aXLKqYA_0Ng
import java.awt.Color;
public class Prob04{
public static void main(String[] args){
Prob04Runner obj = new Prob04Runner();
obj.run();
}//end main
}//end class Prob04
//======================================================//
class Prob04Runner{
public Prob04Runner(){//constructor
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
snowScene.explore();
System.out.println(snowScene);
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
-end-
· 1 (p. 1051)
5.3.29.2 Preface
This module contains review questions and answers keyed to the module titled Java3018: Darkening, Bright-
ening, and Tinting the Colors in a Picture
180 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.29.3 Questions
5.3.29.3.1 Question 1 .
Given Image 1 (p. 1053) , Image 2 (p. 1054) , and Image 3 (p. 1055) , which of the following output images
is produced by the code in Listing 1 (p. 1052) ?
A. Image 4 (p. 1056)
B. Image 5 (p. 1057)
Listing 1. Question 1.
import java.awt.Color;
public class Java3018ra{
public static void main(String[] args){
new Java3018raRunner().run();
}//end main
}//end class Java3018ra
//======================================================//
class Java3018raRunner{
public Java3018raRunner(){//constructor
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
blue = (int)(color.getBlue()*0.8);
Image 1. Prob04a.bmp.
5.348
Image 2. Prob04b.bmp.
5.349
Image 3. Prob04c.jpg.
5.350
5.351
5.352
5.3.29.4 Images
• Image 1 (p. 1053) . Prob04a.bmp.
• Image 2 (p. 1054) . Prob04b.bmp.
5.3.29.5 Listings
• Listing 1 (p. 1052) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.29.6 Answers
5.3.29.6.1 Answer 1
The code in Listing 1 (p. 1052) produces the output image shown in Image 4 (p. 1056) .
Back to Question 1 (p. 1051)
5.3.29.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.30.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.31.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
5.3.31.2.1.1 Images
• Image 1 (p. 1062) . Command line output for Prob05.
5.3.31.2.1.2 Listings
• Listing 1 (p. 1063) . Beginning of driver class for Prob05.
• Listing 2 (p. 1064) . The interface named Prob05X.
• Listing 3 (p. 1065) . Beginning of the class named Prob05MyClassA.
• Listing 4 (p. 1066) . The method named getModiedData.
• Listing 5 (p. 1066) . The method named getData.
• Listing 6 (p. 1067) . Overridden toString method.
• Listing 7 (p. 1067) . Beginning of the class named Prob05MyClassB.
• Listing 8 (p. 1068) . The method named getModiedData.
• Listing 9 (p. 1069) . The getData and toString methods.
• Listing 10 (p. 1069) . Print three items of information.
• Listing 11 (p. 1070) . Three more print statements.
• Listing 12 (p. 1071) . Print the references to the two objects.
• Listing 13 (p. 1074) . Complete program listing
5.3.31.3 Preview
In this module, you will learn about :
• Interface denitions
• Implementing an interface in a class denition
• Dening interface methods in a class denition
• Storing references to new objects in elements of an array of type Object
• Casting elements to an interface type in order to call interface methods
• Parameterized constructors
• Overridden toString method
Program specications
Write a program named Prob05 that uses the class denition shown in Listing 1 (p. 1063) to produce
the output shown in Image 1 (p. 1062) on the command line screen.
Prob05
Put your first name here
Put your last name here
-18 -17 -16
-17 -17 -17
-12 -12 -12
5.353
• The values in the rst row of numbers will be a sequence of consecutive integers in increasing algebraic
order from left to right.
• All three values in the second row of numbers will match the value of the center number in the rst
row of numbers.
• All three values in the third row of numbers will be algebraically ve greater than the values in the
second row of numbers.
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob05 shown in Listing 1 (p. 1063) .
• Interface denitions
• Implementing an interface in a class denition
• Dening interface methods in a class denition
• Storing references to new objects in elements of an array of type Object
• Casting elements to an interface type in order to call interface methods
• Parameterized constructors
• Overridden toString method
import java.util.*;
class Prob05{
public static void main(String[] args){
5.354
· Prob05MyClassA
· Prob05MyClassB
The same random value is passed to the constructor for both objects when they are instantiated.
Put the driver class on temporary hold
At this point, I am going to put the driver class named Prob05 on temporary hold and explain the
class named Prob05MyClassA .
The interface named Prob05X
Having glanced ahead, I know that the class named Prob05MyClassA implements the interface
named Prob05X so I will explain that interface rst.
The interface named Prob05X is shown in its entirety in Listing 2 (p. 1064) .
interface Prob05X{
public int getModifiedData();
public int getData();
}//end interface
5.355
An interface denition
An interface denition can contain only two kinds of members:
• Constants
• Method declarations
By now, you should have studied interfaces in my online tutorials. Therefore, this explanation will be very
brief.
Method declarations
Listing 2 (p. 1064) contains two method declarations.
A method declaration does not have a body. Its purpose is to establish the programming interface for
that method in any class that implements the interface (return type, name, arguments, etc.) .
A method declaration provides no information about the behavior of the method.
A method declaration in an interface is implicitly abstract.
A concrete denition is required
Any class that implements an interface:
• Must provide a concrete version of every method that is declared in the interface, or
• The class must be declared abstract . (In this case, abstract essentially means incomplete.)
Prob05MyClassA(int inData){//constructor
System.out.println("Prob05");
System.out.println("Put your first name here");
data = inData;
}//end constructor
5.356
With the exception of some very subtle dierences (that are beyond the scope of this course) , that concrete
denition must match the signature of the declared method.
Code for the method named getModiedData
The method named getModiedData is shown in its entirety in Listing 4 (p. 1066) .
When this method is called, it
• subtracts a value of 1 from the value stored in the instance variable named data , and
• returns that modied value.
185 http://cnx.org/content/m44214/latest/Java3020old.htm#concrete
5.357
5.358
A round trip
When the code in Listing 1 (p. 1063) instantiates an object of the Prob05MyClassA class, it passes
a random value as a parameter to the constructor.
The constructor shown in Listing 3 (p. 1065) stores that random value in the instance variable named
data .
When the method named getModiedData is called, it returns a value that is the original random
value less 1.
When the method named getData is called, it returns a copy of the original random value.
The toString method
The class named Prob05MyClassA extends the class named Object by default. It inherits a method
named toString from the class named Object . The inherited method has very specic behavior.
Overridden toString method
The code in Listing 6 (p. 1067) overrides the inherited method to provide a dierent behavior when the
method is executed in conjunction with an object of the Prob05MyClassA class.
The new behavior is to construct and return a string version of the value obtained by adding 5 to the
value stored in data , which is the original random value.
5.359
Prob05MyClassB(int inData){
System.out.println("Put your last name here");
data = inData;
}//end constructor
5.360
Implements Prob05X
The rst thing we notice is that this class also implements the interface named Prob05X . This requires
that the class provide concrete denitions of the two methods declared in that interface.
Save the incoming parameter value
Prob05MyClassB
The constructor for the class, which is shown in Listing 7 (p. 1067) , saves the
incoming parameter value in a private instance variable named data .
Unrelated to the variable named data from before
It is important to note that this variable named data is completely unrelated to the private instance
variable named data that is declared in Listing 3 (p. 1065) , even though they are the same type and they
have the same name.
They belong to two dierent objects. Objects do not share instance variables.
The two objects are related
However, even though the two objects instantiated in Listing 1 (p. 1063) are instantiated from dierent
classes, they are related in the sense that they have two ancestors in common. They both extend the class
named Object by default and they both explicitly implement the interface named Prob05X . That
means that they can both be treated as either type Object or type Prob05X .
Related through the interface by design
Because all classes are direct or indirect subclasses of the class named Object , all objects instantiated
for any class are related at the Object level. However, the objects in this program are related through the
Prob05X interface only because I designed the program that way.
The method named getModiedData
The method named getModiedData is shown in Listing 8 (p. 1068) .
5.361
5.362
System.out.print(
((Prob05X)var1[0]).getModifiedData() + " ");
System.out.println(
((Prob05X)var1[1]).getModifiedData());
5.363
Recall that the reference to each object instantiated in Listing 1 (p. 1063) is stored in an array element
as type Object .
A reference to any object can be stored in a reference of type Object because the Object class is
(References to array objects can also be stored as type
the superclass of all classes. Object but that fact
is not germane to this program.)
Only eleven methods can be called on type Object
Object
However, once an object's reference is stored as type , the only methods that can be called
on that object (without casting) are the eleven methods that are dened in the Object class. That
group of eleven methods includes the method named toString but it does not include the methods named
getData and getModiedData .
Must change the type of the reference
Therefore, the rst statement in Listing 10 (p. 1069) requires that a cast to be used to change the
type of the reference back to a type on which the method can be called. There are a couple of choices in
this regard.
Could cast to the class type
First, it is always possible to cast the reference back to the class from which the object was instantiated.
Therefore, it would work to cast the reference from array element 0 in Listing 10 (p. 1069) to type
Prob05MyClassA and to cast the reference from array element 1 to type Prob05MyClassB .
Cast to the interface type
In this program, there is another choice. Because both classes implement the interface named Prob05X
, and the method named getModiedData is declared in that interface, it also works to cast both
references to the common interface type Prob05X .
That is what was done in Listing 10 (p. 1069) . Both references were cast to the interface type Prob05X
.
The printed values
The rst statement in Listing 10 (p. 1069) calls the method named getModiedData as dened in
Listing 4 (p. 1066) . This causes the original random value less 1 to be printed.
The second statement in Listing 10 (p. 1069) simply prints the original random value that was saved in
the variable named randomData in Listing 1 (p. 1063) .
The third statement in Listing 10 (p. 1069) calls the method named getModiedData as dened in
Listing 8 (p. 1068) . This causes the original random value plus 1 to be printed.
Because this is a call to the println method, the onscreen cursor advances to the left side of the next
line after the value is printed.
The three statements in Listing 10 (p. 1069) cause the rst three values shown in Image 1 (p. 1062) to
be printed on the command line screen.
Three more print statements
Continuing with the driver class named Prob05 , Listing 11 (p. 1070) shows three more print state-
ments.
5.364
A cast is required
In this case, the getData method belonging to each of the objects is called in the rst and third
statements. (Once again a cast is required.)
Behavior of the getData methods is the same
getData method is the same in both objects.
Recall that the behavior of the It simply returns a copy
of the original random value that was passed to the constructor when each of the objects was instantiated.
The three statements in Listing 11 (p. 1070) produce the second set of three matching values shown in
Image 1 (p. 1062) .
These three values match because all three print statements are printing essentially the same value. The
original random value is printed in the middle statement in Listing 11 (p. 1070) . A copy of the original
random value is printed in the rst and third statements.
Print the references to the two objects
Things get a little bit more complicated in Listing 12 (p. 1071) .
}//end main
}//end class Prob05
5.365
The print and println methods cause the code in Listing 6 (p. 1067) and Listing 9 (p. 1069) to be
executed. In both cases, this code returns a string that represents the original random value plus 5. This is
the value that is displayed.
Print the random value plus 5
The second statement in Listing 12 (p. 1071) adds ve to the original random number and prints the
result. These three statements produce the third line of text in Image 1 (p. 1062) where all three values are
the algebraic sum of the original random number plus 5.
Important - The cast is not required
Even though the references extracted from the array in the rst and third statements in Listing 12 (p.
1071) are cast to the interface type Prob05X , that cast is unnecessary.
Because the original denition of the toString method appears in the class named Object , the
toString method can be called on those objects even while they are being treated as though they are of
type Object .
Runtime polymorphism
Furthermore, a very powerful capability of OOP known as runtime polymorphism would cause the over-
ridden versions of the methods dened in Listing 6 (p. 1067) and Listing 9 (p. 1069) to be executed instead
of the default version of the method dened in the Object class.
The end of the main method
Listing 12 (p. 1071) signals the end of the main method and the end of the class named Prob05 .
When the main method has nothing further to do, it terminates causing the program to terminate and
return control to the operating system.
5.3.31.7 Summary
In this module, you learned about :
• Interface denitions
• Implementing an interface in a class denition
• Dening interface methods in a class denition
• Storing references to new objects in elements of an array of type Object
• Casting elements to an interface type in order to call interface methods
• Parameterized constructors
• Overridden toString method
186 http://www.youtube.com/playlist?list=PL3DB0B7840C943C4C
· Part01
187
· Part02
188
· Part03
189
· Part04
190
5.3.31.10 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
187 http://www.youtube.com/watch?v=10R_Xgo9QEo
188 http://www.youtube.com/watch?v=vNPd6Sd7Wk8
189 http://www.youtube.com/watch?v=_JFcPromgGk
190 http://www.youtube.com/watch?v=A3bgpy5dCtQ
import java.util.*;
class Prob05{
public static void main(String[] args){
System.out.print(
((Prob05X)var1[0]).getModifiedData() + " ");
System.out.print(randomData + " ");
System.out.println(
((Prob05X)var1[1]).getModifiedData());
}//end main
}//end class Prob05
//======================================================//
interface Prob05X{
public int getModifiedData();
public int getData();
}//end interface
//======================================================//
Prob05MyClassA(int inData){
System.out.println("Prob05");
System.out.println("Put your first name here");
data = inData;
}//end constructor
//----------------------------------------------------//
return data - 1;
}//end getModifiedData()
//----------------------------------------------------//
1075
-end-
5.3.32.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
191 This content is available online at <http://cnx.org/content/m45632/1.2/>.
192 http://cnx.org/content/m44214
193 http://cnx.org/content/m45632/latest/a0-Index.htm
5.3.33.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
195 .
5.3.33.2.1.1 Images
• Image 1 (p. 1077) . Input le named Prob01.jpg.
• Image 2 (p. 1078) . First output image.
• Image 3 (p. 1079) . Second output image.
• Image 4 (p. 1080) . Required output text.
5.3.33.2.1.2 Listings
• Listing 1 (p. 1081) . The driver class named Prob01.
• Listing 2 (p. 1081) . Beginning of the class named Prob01Runner.
• Listing 3 (p. 1082) . The run method.
• Listing 4 (p. 1083) . Beginning of the method named rotatePicture.
• Listing 5 (p. 1085) . Compute the dimensions of the new Picture object.
• Listing 6 (p. 1085) . Prepare the translation transform.
• Listing 7 (p. 1086) . Concatenate the transforms.
• Listing 8 (p. 1086) . Instantiate the new Picture object .
5.3.33.3 Preview
In this module, you will learn how to scale images and how to rotate and translate images using the
AneTransform class.
Program specications
Write a program named Prob01 that uses the class denition shown in Listing 1 (p. 1081) and Ericson's
media library along with the image le named Prob01.jpg (see Image 1 (p. 1077) ) to produce the
output images shown in Image 2 (p. 1078) and Image 3 (p. 1079) .
5.367
5.368
5.369
The image from the le named Prob01.jpg must be scaled and then rotated 30 degrees clockwise. A
scale factor of 0.95 must be applied to the horizontal and a scale factor of 0.9 must be applied to the vertical.
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob01 shown in Listing 1 (p. 1081) .
Required output text
In addition to the two output images mentioned above, your program must display your name and the
other line of text shown in Image 4 (p. 1080) on the command-line screen.
5.370
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.Graphics;
5.371
class Prob01Runner{
public Prob01Runner(){
System.out.println("Display your name here.");
}//end constructor
5.372
Listing 2 (p. 1081) shows the constructor for the class, which simply displays the student's name on the
command line screen as shown in Image 4 (p. 1080) .
The run method
The run method, which is called in Listing 1 (p. 1081) , is shown in its entirety in Listing 3 (p. 1082) .
pic = pic.scale(0.95,0.9);
pic = rotatePicture(pic,30);
pic.explore();
System.out.println(pic);
}//end run
5.373
196 http://cnx.org/content/m44148/latest/
5.374
197 http://java.sun.com/javase/6/docs/api/java/awt/geom/AneTransform.html
fashion. Concatenation of transform objects can result in considerable computational savings in certain
situations.
A larger Picture object is required
Looking back at Image 2 (p. 1078) and Image 3 (p. 1079) , you can see that the Picture object
required to contain the rotated image must be larger than the Picture object required to contain the
original image. You will learn how to compute the dimensions of the larger Picture object later in this
module.
Behavior of the rotatePicture method
The rotatePicture method performs the following operations:
• Prepare an AneTransform object that can be used to rotate the incoming image around its center
by the specied angle.
• Get the dimensions of a rectangle of sucient size to contain the rotated image.
• Prepare an AneTransform object that will translate the rotated image to the center of a new,
larger Picture object having the dimensions computed above.
• Concatenate the rotation transform object with the translation transform object.
• Create a new Picture object with the dimensions computed above.
• Apply the concatenated transform to the incoming image and draw the transformed image in the new
Picture object.
• Return a reference to the new Picture object containing the rotated and translated image.
Rectangle2D rectangle2D =
pic.getTransformEnclosingRect(rotateTransform);
5.375
AffineTransform translateTransform =
new AffineTransform();
translateTransform.translate(
(resultWidth - pic.getWidth())/2,
(resultHeight - pic.getHeight())/2);
5.376
198 http://java.sun.com/javase/6/docs/api/java/awt/geom/AneTransform.html#translate%28double,%20double%29
translateTransform.concatenate(rotateTransform);
5.377
5.378
Graphics2D g2 = (Graphics2D)result.getGraphics();
g2.drawImage(pic.getImage(),translateTransform,null);
return result;
}//end rotatePicture
}//end class Prob01Runner
5.379
• Calls Ericson's explore method on the returned Picture object producing the screen output shown
in Image 3 (p. 1079) .
• Passes the returned Picture object to the println method producing the last line of text output
shown in Image 4 (p. 1080) .
• Returns control the main method in Listing 1 (p. 1081) , causing the program to terminate as soon
as the user dismisses both images from the screen.
5.3.33.7 Summary
You learned how to scale images and how to rotate and translate images using the AneTransform class.
5.3.33.10 Miscellaneous
This section contains a variety of miscellaneous information.
• File: Java3022.htm
• Published: 08/02/12
• Revised: 02/17/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
199 http://cnx.org/content/m44223/latest/Prob01.jpg
200 http://vimeo.com/channels/itse2321/21211960
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob01Runner{
public Prob01Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture pic = new Picture("Prob01.jpg");
//Add your name and display the picture.
pic.addMessage("Display your name here.",10,20);
pic.explore();
pic = pic.scale(0.95,0.9);
pic = rotatePicture(pic,30);
pic.explore();
System.out.println(pic);
}//end run
//----------------------------------------------------//
-end-
· 1 (p. 1092)
5.3.34.2 Preface
This module contains review questions and answers keyed to the module titled Java3022: Scaling, Rotating,
and Translating Images using Ane Transforms
202 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.34.3 Questions
5.3.34.3.1 Question 1 .
Given the input image in Image 1 (p. 1094) , which of the following output images is produced by the code
in Listing 1 (p. 1093) ?
A. Image 2 (p. 1095)
B. Image 3 (p. 1096)
Listing 1. Question 1.
class Java3022raRunner{
public void run(){
procPix(new Picture("Prob01.jpg").scale(0.7,0.7),-30);
}//end run
//----------------------------------------------------//
Rectangle2D rectangle2D =
pic.getTransformEnclosingRect(xformA);
int resultWidth = (int)(rectangle2D.getWidth());
int resultHeight = (int)(rectangle2D.getHeight());
xformB.concatenate(xformA);
Picture result = new Picture(
resultWidth,resultHeight);
Graphics2D g2 = (Graphics2D)result.getGraphics();
g2.drawImage(pic.getImage(),xformB,null);
result.explore();
}//end
//----------------------------------------------------//
5.381
Image 1. Prob01.jpg.
5.382
5.383
5.384
5.3.34.4 Images
• Image 1 (p. 1094) . Prob01.jpg.
• Image 2 (p. 1095) . Possible output image.
• Image 3 (p. 1096) . Possible output image.
5.3.34.5 Listings
• Listing 1 (p. 1093) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.34.6 Answers
5.3.34.6.1 Answer 1
The code in Listing 1 (p. 1093) produces the output image shown in Image 3 (p. 1096) .
Back to Question 1 (p. 1092)
5.3.34.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.35.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.36.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
207 .
5.3.36.2.1.1 Images
• Image 1 (p. 1101) . Input le named Prob02a.jpg.
• Image 2 (p. 1102) . First output image.
• Image 3 (p. 1103) . Second output image.
• Image 4 (p. 1104) . Third output image.
• Image 5 (p. 1105) . Required output text.
• Image 6 (p. 1109) . Picture output from the mirrorUpperQuads method.
5.3.36.2.1.2 Listings
• Listing 1 (p. 1105) . The driver class named Prob02.
• Listing 2 (p. 1106) . Beginning of the class named Prob02Runner.
• Listing 3 (p. 1106) . The run method.
• Listing 4 (p. 1107) . The method named mirrorUpperQuads.
• Listing 5 (p. 1110) . The method named mirrorHoriz.
• Listing 6 (p. 1113) . Complete program listing.
5.3.36.3 Preview
In this module, you will learn how to mirror images, both horizontally and vertically.
Program specications
Prob02
Write a program named that uses the class denition shown in Listing 1 (p. 1105) and Ericson's
media library along with the image le named Prob02a.jpg (shown in Image 1 (p. 1101) ) to produce
the three graphic output images shown in Image 2 (p. 1102) , Image 3 (p. 1103) , and Image 4 (p. 1104) .
5.385
5.386
5.387
5.388
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob02 shown in Listing 1 (p. 1105) .
Rotate and mirror
The image from the le named Prob02a.jpg is rotated by 35 degrees. It is not scaled. Then the top-left
quadrant of the picture containing the rotated image is mirrored into the top-right quadrant. Following this,
the top half of the picture is mirrored into the bottom half.
Required output text
In addition to the three output images mentioned above, your program must display your name and the
other line of text shown in Image 5 (p. 1105) on the command-line screen
5.389
5.390
class Prob02Runner{
public Prob02Runner(){
System.out.println("Display your name here.");
}//end constructor
5.391
The constructor displays the student's name, producing the rst line of output text shown in Image 5
(p. 1105) .
The run method
The run method that is called in Listing 1 (p. 1105) is shown in its entirety in Listing 3 (p. 1106) .
pix = rotatePicture(pix,35);
pix.explore();
pix = mirrorUpperQuads(pix);
pix = mirrorHoriz(pix);
pix.explore();
System.out.println(pix);
}//end run
5.392
return pix;
}//end mirrorUpperQuads
5.393
The nal picture shown in Listing 4 (p. 1107) contains only pixel from the upper-left quadrant of the
picture with the rotated image.
Return a modied Picture object
Finally, the code in Listing 4 (p. 1107) returns the modied Picture object to the run method in
Listing 3 (p. 1106) .
At this point, the picture with the rotated image is replaced by the version of the picture returned by
the mirrorUpperQuads method.
Picture output from the mirrorUpperQuads method
If you were to display the picture at that point, you would see the image shown in Image 6 (p. 1109) .
5.394
return pix;
}//end mirrorHoriz method
5.395
Listing 5 (p. 1110) also signals the end of the class named Prob02Runner and the end of the program.
5.3.36.6 Summary
You learned how to mirror images both horizontally and vertically.
5.3.36.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
208 http://cnx.org/content/m44228/latest/Prob02a.jpg
209 http://vimeo.com/channels/itse2321/21217708
class Prob02Runner{
public Prob02Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture pix = new Picture("Prob02a.jpg");
//Add your name and display the output picture.
pix.addMessage("Display your name here.",10,20);
//Display the input picture.
pix.explore();
pix = rotatePicture(pix,35);
pix.explore();
pix = mirrorUpperQuads(pix);
pix = mirrorHoriz(pix);
pix.explore();
System.out.println(pix);
}//end run
//----------------------------------------------------//
-end-
· 1 (p. 1115)
5.3.37.2 Preface
This module contains review questions and answers keyed to the module titled Java3024: Mirroring Images
211 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.37.3 Questions
5.3.37.3.1 Question 1 .
Given the input image shown in Image 1 (p. 1117) , which of the following output images is produced by
the code in Listing 1 (p. 1116) ?
A. Image 2 (p. 1118)
B. Image 3 (p. 1119)
Listing 1. Question 1.
class Java3024raRunner{
public void run(){
Picture pix = new Picture("Prob02a.jpg");
pix = rotatePicture(pix,35);
pix = mirrorUpperQuads(pix);
pix = mirrorHoriz(pix);
pix.explore();
System.out.println(pix);
}//end run
//----------------------------------------------------//
AffineTransform rotateTransform =
new AffineTransform();
rotateTransform.rotate(Math.toRadians(angle),
pix.getWidth()/2,
pix.getHeight()/2);
Rectangle2D rectangle2D =
pix.getTransformEnclosingRect(rotateTransform);
int resultWidth = (int)(rectangle2D.getWidth());
int resultHeight = (int)(rectangle2D.getHeight());
AffineTransform translateTransform =
new AffineTransform();
translateTransform.translate(
(resultWidth - pix.getWidth())/2,
(resultHeight - pix.getHeight())/2);
translateTransform.concatenate(rotateTransform);
Picture result = new Picture(
resultWidth,resultHeight);
Graphics2D g2 =Available
(Graphics2D)result.getGraphics();
for free at Connexions <http://cnx.org/content/col11441/1.121>
g2.drawImage(pix.getImage(),translateTransform,null);
return result;
1117
Image 1. Prob02a.jpg.
5.398
5.399
5.400
5.3.37.4 Images
• Image 1 (p. 1117) . Prob02a.jpg.
• Image 2 (p. 1118) . Possible output image.
• Image 3 (p. 1119) . Possible output image.
5.3.37.5 Listings
• Listing 1 (p. 1116) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.37.6 Answers
5.3.37.6.1 Answer 1
The code in Listing 1 (p. 1116) produces the output image shown in Image 2 (p. 1118) .
Back to Question 1 (p. 1115)
5.3.37.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.38.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
212 This content is available online at <http://cnx.org/content/m45640/1.2/>.
213 http://cnx.org/content/m44228
214 http://cnx.org/content/m45640/latest/a0-Index.htm
5.3.39.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
216 .
5.3.39.2.1.1 Images
• Image 1 (p. 1125) . Required graphic output.
• Image 2 (p. 1126) . Required text output.
• Image 3 (p. 1130) . A drawing of an ellipse.
5.3.39.2.1.2 Listings
• Listing 1 (p. 1126) . The driver class named Prob03.
• Listing 2 (p. 1127) . Beginning of the class named Prob03Runner.
• Listing 3 (p. 1128) . Beginning of the method named process.
• Listing 4 (p. 1128) . Translate the origin to the center of the image.
• Listing 5 (p. 1129) . Draw the black horizontal and vertical axes.
• Listing 6 (p. 1131) . Draw the solid green lled ellipse in the upper-left quadrant.
• Listing 7 (p. 1132) . Draw a circle with a gradient ll in the upper-right quadrant.
• Listing 8 (p. 1135) . Code for the remaining two quadrants..
• Listing 9 (p. 1138) . Complete program listing.
5.3.39.3 Preview
In this module you will learn to use the GradientPaint class along with a variety of other Java2D classes.
Program specications
Write a program named Prob03 that uses the class denition shown in Listing 1 (p. 1126) and Ericson's
media library along with the image le named Prob03.jpg to produce the graphic output image shown in
Image 1 (p. 1125) . (Note that the image in the le named Prob03.jpg is a blank white image. You could
also create this blank image using one of the constructors for the Picture class.)
5.401
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob03 shown in Listing 1 (p. 1126) .
Required text output
In addition to the output image mentioned above, your program must display your name and the other
line of text shown in Image 2 (p. 1126) .
5.402
5.403
If you have been studying the earlier modules in this series, no explanation of Listing 1 (p. 1126) should
be required.
Beginning of the class named Prob03Runner
The class named Prob03Runner begins in Listing 2 (p. 1127) .
class Prob03Runner{
public Prob03Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
pic.setAllPixelsToAColor(Color.RED);
process(pic);
5.404
Graphics2D g2 = (Graphics2D)(pic.getGraphics());
5.405
Java2D graphics
This is basically a module on the use of classes from the Java2D section of the standard class library.
(See my lessons 300 through 324 on Java2D graphics here 217 .) Classes from Ericson's library are used
mainly to support the display aspects of the program.
What are Java2D graphics?
Although the capabilities provided by Java2D graphics are wide and varied, in one way or another, they
generally have to do with the creation of images by drawing.
A graphics context is required
In order to use the methods that will be using, it is necessary to gain access to the graphics context of
an object as type Graphics2D . The rst statement in Listing 3 (p. 1128) calls Ericson's getGraphics
method to gain access to the graphics context of a Picture object.
A cast to type Graphics2D is required
However, the getGraphics method returns a reference to the graphics context as type Graphics .
In order for us to use it to do what we want to do, we must cast it to type Graphics2D . This gives us
access to many more methods that would be the case without the cast.
Save as type Graphics2D in a variable named g2
The graphics context for the Picture object is saved in Listing 3 (p. 1128) as type Graphics2D .
The reference is saved in the reference variable named g2 .
Save the width and height of the Picture object
The last two statements in Listing 3 (p. 1128) get and save the width and the height of the image
Picture object.
encapsulated in the
Translate the origin to the center of the image
By default, the origin (with coordinates of 0,0) is in the upper-left corner of the image. However, we
would like to be able to work with a coordinate system in which the origin is at the center.
Listing 4 (p. 1128) calls the translate method to move the origin to the center of the image.
g2.translate(width/2,height/2);
5.406
217 http://www.dickbaldwin.com/tocadv.htm
(Fortunately, you already understand ane transforms. Otherwise, you might not be able to understand
the documentation for the translate method.)
From this point forward...
From this point forward, we can think of the coordinates of the pixel at the very center of the object as
having values of 0,0. Locations to the left of center have negative X coordinates and locations above the
center have negative Y coordinates.
Draw the black horizontal and vertical axes
The next thing we want to do is to draw the black horizontal and vertical axes that you see in the center
of the image in Image 1 (p. 1125) . This is accomplished by the code in Listing 5 (p. 1129) .
//Draw x-axis
g2.draw(new Line2D.Double(-width/2, 0.0,
width/2, 0.0));
//Draw y-axis
g2.draw(new Line2D.Double(0.0, -width/2,
0.0, height/2));
5.407
218 http://www.dickbaldwin.com/java/Java300.htm
5.408
Listing 6: Draw the solid green lled ellipse in the upper-left quadrant.
g2.fill(circle1);
g2.draw(circle1);
5.409
constructed. This results in the lled green circle in the upper-left quadrant in Image 1 (p. 1125) .
Draw a circle with a gradient ll in the upper-right quadrant
This is where things tend to get a little complicated.
If you compare the circles in the upper-left and upper-right quadrants in Image 1 (p. 1125) , you will see
that they look considerably dierent.
Dierence caused by parameter to the setPaint method
If you compare the code in Listing 6 (p. 1131) with the code in Listing 7 (p. 1132) , you will see that
except for the coordinate values that position the circle, the only dierence is the parameter that is passed
to the setPaint method.
5.410
Think of the two points as being at the ends of an imaginary line segment, which can be at any angle
relative to the horizontal.
Colors at the ends of the line segment
When a shape is drawn using a gradient ll, one of the colors will appear at one end of the line segment
and the other color will appear at the other end of the line segment.
The color will change
The color will change gradually from one color to the other along the imaginary line segment connecting
the two points.
Perpendicular color bands on the sides
The colors extend out to the sides of the imaginary line segment in bands that are perpendicular to the
line segment.
The cyclic parameter
If the last (cyclic) parameter is set to false, the color will only change along the imaginary line segment.
Areas beyond each end of the line segment will be the colors that are specied for the points at the ends of
the line segment.
(This parameter was not set to false for any of the circles in Image 1.)
If the cyclic parameter is true...
The pattern of color change that occurs along the line segment will extend in a cyclic fashion beyond the
ends of the line segment all the way to innity.
Compare constructor parameters with upper-right quadrant
Now consider the parameter values used in Listing 7 (p. 1132) and compare them with the image in the
upper-right quadrant in
A simple color paint versus a gradient paint
Color class
Listing 6 passes an object of the simple representing the color green to the setPaint
method.
Listing 7 passes an object of the GradientPaint class to the setPaint method.
Therefore, we need to understand the behavior of an object of the GradientPaint class.
Constructor parameters
There are four overloaded constructors for the GradientPaint class. The constructor highlighted in
yellow in Listing 7 is one of the most complicated. It requires the following parameters:
g2.fill(circle4);
g2.draw(circle4);
}//end process
5.411
An interesting anomaly
I will point out one interesting anomaly, however. Even though we shifted the origin to the center, we
did not change the direction that represents positive values on the Y axis.
Coordinates above the center are negative and coordinates below the center are positive.
Where is the line segment?
If you examine the constructor parameters for the lower-left quadrant in Listing 8 (p. 1135) , you will
see that the imaginary line segment isn't in the lower-left quadrant.
The line segment is 21 pixels in length, parallel to the horizontal axis. However, it is 64 pixels above the
horizontal axis. That is not in the lower-left quadrant.
The eect is...
The eect is as though the color gradient lls the universe, and is based on a line segment placed anywhere
in the universe.
However, we only see the color gradient through the shape that we specify as a parameter to the ll
method. In other words, that shape is a window through which we can see a background consisting of
5.3.39.6 Summary
In this module, you learned to use the GradientPaint class along with a variety of other Java2D classes.
5.3.39.9 Miscellaneous
This section contains a variety of miscellaneous information.
219 http://cnx.org/content/m44242/latest/Prob03.jpg
220 http://vimeo.com/channels/itse2321/21220418
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob03Runner{
public Prob03Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture pic = new Picture("Prob03.jpg");
pic.setAllPixelsToAColor(Color.RED);
process(pic);
//Add your name and display the output picture.
pic.addMessage("Display your name here.",10,20);
pic.explore();
System.out.println(pic);
}//end run
//----------------------------------------------------//
Graphics2D g2 = (Graphics2D)(pic.getGraphics());
new Ellipse2D.Double(-128,-128,128,128);
g2.setPaint(Color.GREEN);
g2.fill(circle1);
1139
-end-
· 1 (p. 1140)
5.3.40.2 Preface
This module contains review questions and answers keyed to the module titled Java3026: GradientPaint and
other Java2D Classes
222 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.40.3 Questions
5.3.40.3.1 Question 1 .
Which of the following output images is produced by the program shown in Listing 1 (p. 1141) ?
A. Image 1 (p. 1142)
B. Image 2 (p. 1143)
Listing 1. Question 1.
class Java3026raRunner{
public void run(){
Picture pic = new Picture(300,300);
pic.setAllPixelsToAColor(Color.RED);
process(pic);
pic.explore();
}//end run
//----------------------------------------------------//
Graphics2D g2 = (Graphics2D)(pic.getGraphics());
g2.translate(width/2,height/2);
g2.setColor(Color.BLACK);
g2.draw(new Line2D.Double(-width/2,0.0,width/2,0.0));
g2.draw(new Line2D.Double(0.0,-width/2,0.0,height/2));
Ellipse2D.Double circle1 =
new Ellipse2D.Double(-128,-128,128,128);
g2.setPaint(new GradientPaint(-64,-64,Color.BLUE,
-32,-32,Color.GREEN,true));
g2.fill(circle1);
g2.draw(circle1);
Ellipse2D.Double circle2 =
new Ellipse2D.Double(0.0,-128,128,128);
g2.fill(circle2);
g2.draw(circle2);
Ellipse2D.Double circle3
Available = at Connexions <http://cnx.org/content/col11441/1.121>
for free
new Ellipse2D.Double(-128,0.0,128,128);
g2.fill(circle3);
g2.draw(circle3);
1142 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
5.414
5.415
5.3.40.4 Images
• Image 1 (p. 1142) . Possible output image.
• Image 2 (p. 1143) . Possible output image.
5.3.40.5 Listings
• Listing 1 (p. 1141) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.40.6 Answers
5.3.40.6.1 Answer 1
The code in Listing 1 (p. 1141) produces the output image shown in Image 1 (p. 1142) .
Back to Question 1 (p. 1140)
5.3.40.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.41.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.42.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
227 .
5.3.42.2.1.1 Images
• Image 1 (p. 1148) . Input le named Prob04a.jpg.
• Image 2 (p. 1149) . First output image.
• Image 3 (p. 1150) . Second output image.
• Image 4 (p. 1151) . Required text output.
5.3.42.2.1.2 Listings
• Listing 1 (p. 1151) . The driver class named Prob04.
• Listing 2 (p. 1152) . Beginning of the class named Prob04Runner.
• Listing 3 (p. 1153) . Clip the picture and display your name.
• Listing 4 (p. 1154) . The method named clipToEllipse.
• Listing 5 (p. 1157) . Complete program listing.
5.3.42.3 Preview
In this module, you will learn how to use shapes to clip images during the drawing process.
Program specications
Prob04
Write a program named that uses the class denition shown in Listing 1 (p. 1151) and Ericson's
media library along with the image le named Prob04a.jpg (see Image 1 (p. 1148) ) to produce the
graphic output images shown in Image 2 (p. 1149) and Image 3 (p. 1150) . Don't forget to display your
name in the output image as shown.
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob04 shown in Listing 1 (p. 1151) .
Rotate, mirror, and clip
The program rotates a Picture object by 35 degrees with no scaling. Then it does a four-way mirror
on the rotated picture. Finally, it clips the image to an elliptical format as shown in Image 3 (p. 1150) .
Required output text
In addition to the two output images shown above, your program must display your name and the other
line of text shown in Image 4 (p. 1151) .
If you have been studying the earlier modules in this collection, no explanation of Listing 1 (p. 1151)
should be required.
Beginning of the class named Prob04Runner
The class named Prob04Runner begins in Listing 2 (p. 1152) .
class Prob04Runner{
public Prob04Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
pix.explore();
pix = clipToEllipse(pix);
System.out.println(pix);
}//end run
Figure 5.422: Listing 3: Clip the picture and display your name.
The remaining code in Listing 3 (p. 1153) is a repeat of code that I have explained in earlier modules,
so I won't have anything further to say about it.
The method named clipToEllipse
clipToEllipse is shown in its entirety in Listing 4 (p.
The method named 1154) .
return result;
}//end clipToEllipse
The only code in Listing 4 (p. 1154) that is new to this module is the call to the setClip method.
The setClip method is dened in the Graphics class and inherited into the Graphics2D class.
(Among other things, that means that it wasn't necessary for me to cast the Graphics object to type
Graphics2D in Listing 4 (p. 1154) .)
The setClip method
There are a couple of overloaded versions of the setClip method. The one used in Listing 4 (p. 1154)
requires an incoming parameter of the interface type Shape .
The Shape interface
Briey, Sun tells us that the Shape interface "provides denitions for objects that represent some
form of geometric shape."
There are several dozen classes that implement the Shape interface, one of which is the class named
Ellipse2D.Double . Therefore, the object of that type that is instantiated in Listing 4 (p. 1154) satises
the type requirement for being passed to thesetClip method.
Behavior of the setClip method
With regard to the behavior of the setClip method, Sun tells us that the method
"Sets the current clipping area to an arbitrary clip shape."
What is the signicance of the clipping area?
The closest answer that I can nd for that question is the following statement in Sun's description of the
Graphics class:
"All rendering operations modify only pixels which lie within the area bounded by the current clip, which
is specied by a Shape in user space and is controlled by the program using the Graphics object."
In other words...
The clipping area is analogous to the current clip . In this case, the position and shape of the current
clip is the position and shape of the ellipse.
When the image is later drawn on the red Picture object, only those pixels within the ellipse are
modied to show the image. The remaining pixels retain their original color, which was set to red early in
Listing 4 (p. 1154) .
End of discussion
That concludes my explanation of this program. You will nd the methods that I didn't discuss in Listing
5 (p. 1157) near the end of the module.
5.3.42.6 Summary
In this module, you learned how to use shapes to clip images during the drawing process.
228 http://cnx.org/content/m44246/latest/Prob04a.jpg
229 http://vimeo.com/channels/itse2321/21221510
5.3.42.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob04Runner{
public Prob04Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture pix = new Picture("Prob04a.jpg");
pix.explore();
System.out.println(pix);
}//end run
//----------------------------------------------------//
//Create an ellipse
Availablefor clipping
for free at Connexions <http://cnx.org/content/col11441/1.121>
Ellipse2D.Double ellipse =
new Ellipse2D.Double(28,64,366,275);
1158 CHAPTER 5. ITSE 2321 OBJECT-ORIENTED PROGRAMMING (JAVA)
-end-
· 1 (p. 1159)
5.3.43.2 Preface
This module contains review questions and answers keyed to the module titled Java3028: Clipping Images
231 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.43.3 Questions
5.3.43.3.1 Question 1 .
Given the input image shown in Image 1 (p. 1161) , which of the following output images is produced by
the code in Listing 1 (p. 1160) ?
A. Image 2 (p. 1162)
B. Image 3 (p. 1163)
Listing 1. Question 1.
class Java3028raRunner{
AffineTransform rotateTransform =
new AffineTransform();
rotateTransform.rotate(Math.toRadians(angle),
Available for pix.getWidth()/2,
free at Connexions <http://cnx.org/content/col11441/1.121>
pix.getHeight()/2);
Rectangle2D rectangle2D =
1161
Image 1. Prob04a.jpg
5.426
5.427
5.428
5.3.43.4 Images
• Image 1 (p. 1161) . Prob04a.jpg
• Image 2 (p. 1162) . Possible output image.
• Image 3 (p. 1163) . Possible output image.
5.3.43.5 Listings
• Listing 1 (p. 1160) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.43.6 Answers
5.3.43.6.1 Answer 1
The code in Listing 1 (p. 1160) produces the output image shown in Image 3 (p. 1163) .
Back to Question 1 (p. 1159)
5.3.43.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.44.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
232 This content is available online at <http://cnx.org/content/m45646/1.2/>.
233 http://cnx.org/content/m44246
234 http://cnx.org/content/m45646/latest/a0-Index.htm
5.3.45.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
236 .
5.3.45.2.1.1 Images
• Image 1 (p. 1168) . Input le named Prob05a.jpg.
• Image 2 (p. 1169) . Input le named Prob05b.jpg.
• Image 3 (p. 1170) . Required graphic output image.
• Image 4 (p. 1170) . Required output text.
5.3.45.2.1.2 Listings
• Listing 1 (p. 1171) . The driver class named Prob05.
• Listing 2 (p. 1171) . Beginning of the class named Prob05Runner.
• Listing 3 (p. 1172) . The run method of the Prob05Runner class.
• Listing 4 (p. 1173) . Beginning of the merge method.
• Listing 5 (p. 1174) . Do the merge.
• Listing 6 (p. 1177) . Complete program listing.
5.3.45.3 Preview
In this module, you will learn how to do a linear merge on two pictures based on the distance of each pixel
from the left side of the picture.
Program specications
Prob05
Write a program named that uses the class denition shown in Listing 1 (p. 1171) and Ericson's
media library along with the image les named Prob05a.jpg and Prob05b.jpg (see Image 1 (p. 1168)
and Image 2 (p. 1169) ) to produce the graphic output image shown in Image 3 (p. 1170) .
5.429
5.430
5.431
5.432
5.433
The code in Listing 1 (p. 1171) shouldn't require an explanation at this stage in the course.
Beginning of the class named Prob05Runner
The class named Prob05Runner begins in Listing 2 (p. 1171) .
class Prob05Runner{
public Prob05Runner(){
System.out.println("Display your name here.");
}//end constructor
5.434
As with Listing 1 (p. 1171) , the code in Listing 2 (p. 1171) shouldn't require an explanation.
The run method of the Prob05Runner class
1171) calls the run method on an
Listing 1 (p. object of the Prob05Runner class. The run
method is shown in its entirety in Listing 3 (p. 1172) .
5.435
The only thing in Listing 3 (p. 1172) that I haven't explained in earlier modules is the call to the merge
method, so I will limit my discussion to that method.
The merge method
The merge method is used to merge the image in Image 1 (p. 1168) with the image in Image 2 (p.
1169) to produce the image shown in Image 3 (p. 1170) .
(Note, however, that the merged image was cropped to eliminate the buttons at the top of F igure 1 (p.
1168) and Image 2 (p. 1169) before displaying it in Image 3 (p. 1170) .)
A linear merge
The merge method does a linear merge on two pictures based on the distance of each pixel from the
left side of the picture.
The method assumes that both pictures have the same dimensions.
Beginning of the merge method
The merge method begins in Listing 4 (p. 1173) .
double scaleL = 0;
double scaleR = 0;
int redL = 0;
int greenL = 0;
int blueL = 0;
int redR = 0;
int greenR = 0;
int blueR = 0;
Pixel pixelL = null;
Pixel pixelR = null;
5.436
The code in Listing 4 (p. 1173) simply declares and initializes a large number of working variables.
Do the merge
The merge is accomplished in the nested for loop in Listing 5 (p. 1174) .
redL = pixelL.getColor().getRed();
greenL = pixelL.getColor().getGreen();
blueL = pixelL.getColor().getBlue();
redR = pixelR.getColor().getRed();
greenR = pixelR.getColor().getGreen();
blueR = pixelR.getColor().getBlue();
pixelL.setColor(new Color(redL,greenL,blueL));
}//end inner loop
}//end outer loop
}//end merge
5.437
Dicult to explain
Although the code in Listing 5 (p. 1174) is long, tedious, and ugly, it isn't complicated However, it is
somewhat dicult to explain in words.
Two scale factors
The body of the for loop begins by computing a pair of scale factors named scaleR and scaleL .
The factor named scaleR has a maximum value of 1.0 and is directly proportional to the distance of the
current pixel from the left edge of the picture.
The factor named scaleL also has a maximum value of 1.0 and is inversely proportional to the distance
of the pixel from the left edge.
Get and save color components
The red, green, and blue values for the same pixel location in each of the pictures are obtained and saved.
Compute a new set of color values
A new set of red, green, and blue color values are computed as the sum of scaled versions of the pixel
colors from the rabbit image pixel and the penguin image pixel.
The nature of the scaling
The scaling is such that the pixel colors from the rabbit image contribute most heavily to output pixels
to the left of center and pixel colors from the penguin image contribute most heavily to output pixels to the
right of center.
You can see the eect of this scaling algorithm in Image 3 (p. 1170) .
5.3.45.6 Summary
In this module, you learned how to merge two pictures.
5.3.45.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
237 http://cnx.org/content/m44247/latest/Prob05a.jpg
238 http://cnx.org/content/m44247/latest/Prob05b.jpg
239 http://vimeo.com/channels/itse2321/21222484
class Prob05Runner{
public Prob05Runner(){
System.out.println("Display your name here.");
}//end constructor
//----------------------------------------------------//
public void run(){
Picture penguin = new Picture("Prob05a.jpg");
Picture hare = new Picture("Prob05b.jpg");
merge(hare,penguin);
hare = crop(hare,6,58,330,252);
hare.addMessage("Display your name here.",10,20);
drawSun(hare);
hare.show();
System.out.println(hare);
}//end run
//----------------------------------------------------//
-end-
· 1 (p. 1179)
5.3.46.2 Preface
This module contains review questions and answers keyed to the module titled Java3030: Merging Pictures
241 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
5.3.46.3 Questions
5.3.46.3.1 Question 1 .
Given the two input images shown in Image 1 (p. 1181) and Image 2 (p. 1182) , which of the following
two output images is produced by the code in Listing 1 (p. 1180) ? Note that the dierences in the two
possible output images are subtle. Also note the RGB color values shown at the same cursor location in all
four images.
A. Image 3 (p. 1183)
B. Image 4 (p. 1184)
Listing 1. Question 1.
class Java3030raRunner{
public void run(){
Picture penguin = new Picture("Prob05a.jpg");
penguin.explore();
Picture hare = new Picture("Prob05b.jpg");
hare.explore();
merge(hare,penguin);
hare.explore();
}//end run
//----------------------------------------------------//
double scaleL = 0;
double scaleR = 0;
int redL = 0;
int greenL = 0;
int blueL = 0;
int redR = 0;
int greenR = 0;
int blueR = 0;
Pixel pixelL = null;
Pixel pixelR = null;
redL = pixelL.getColor().getRed();
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
greenL = pixelL.getColor().getGreen();
blueL = pixelL.getColor().getBlue();
1181
5.440
5.441
5.442
5.443
5.3.46.4 Images
• Image 1 (p. 1181) . One of two input images.
• Image 2 (p. 1182) . The second of two input images.
5.3.46.5 Listings
• Listing 1 (p. 1180) . Question 1.
This image was also inserted for the purpose of inserting space between the questions and the answers.
5.3.46.6 Answers
5.3.46.6.1 Answer 1
The code in Listing 1 (p. 1180) produces the output image shown in Image 3 (p. 1183) .
Back to Question 1 (p. 1179)
5.3.46.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.3.47.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
242 This content is available online at <http://cnx.org/content/m45648/1.2/>.
243 http://cnx.org/content/m44247
244 http://cnx.org/content/m45648/latest/a0-Index.htm
5.4.1.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming in
general and the Java Collections framework in particular.
The purpose of this module is to introduce you to the Java Collections Framework. Once you learn how
to use the framework, it is unlikely that you will need to reinvent common data structures, search algorithms,
or sorting algorithms again, because those capabilities are neatly packaged within the framework.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
246 in
Oracle's Java Tutorials
247 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.1.2.1.1 Listings
• Listing 1 (p. 1191) . A new object of the TreeSet class.
• Listing 2 (p. 1192) . Populate the collection.
• Listing 3 (p. 1192) . The Populator class.
• Listing 4 (p. 1194) . Get an Iterator object.
• Listing 5 (p. 1194) . Traverse the collection.
• Listing 6 (p. 1198) . Complete program listing
5.4.1.3 Preview
This module provides a brief introduction to the use of the Java Collections Framework . The framework
is designed to encourage you to reuse rather than to reinvent collections and maps.
A collection represents a group of objects, known as its elements. Some collections allow duplicate
elements while others do not. Some collections are ordered and others are not. (Maps will be discussed in
future modules.)
The Collections Framework is dened by a set of interfaces and associated contracts, and provides
concrete implementations of the interfaces for the most common data structures. In addition, the framework
also provides several abstract implementations, which are designed to make it easier for you to create new
and dierent implementations while still maintaining the structural polymorphic integrity of the framework.
5.4.1.4 Generics
The code in this series of modules is written with no thought given to Generics
248 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
246 http://docs.oracle.com/javase/tutorial/collections/index.html
247 http://docs.oracle.com/javase/tutorial/index.html
248 http://docs.oracle.com/javase/tutorial/java/generics/index.html
5.4.1.5 Introduction
5.4.1.5.1 A quiz
Let's begin with a little quiz to establish your baseline knowledge of the Collections Framework. Take a look
at the program in Listing 6 (p. 1198) near the end of this module. Which of the following is the output
produced by that program?
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 12344
• E. 1234
• F. None of the above.
If your answer was 1234 (and it wasn't a guess) then you may already know quite a lot about the use of
the Collections Framework. If not, keep reading to begin learning about the framework.
class Worker{
public void doIt(){
Collection ref = new TreeSet();
Populator.fillIt(ref);
At this point, I am going to discuss the llIt method of the Populator class called in Listing 2 (p.
1192) . The entire class denition of the Populator class, including the llit method, is shown in Listing
3 (p. 1192) .
class Populator{
public static void fillIt(Collection ref){
ref.add(new Integer(4));
ref.add(new Integer(4));
ref.add(new Integer(3));
ref.add(new Integer(2));
ref.add(new Integer(1));
}//end fillIt()
}//end class populator
The call to the iterator method on any Collection object returns an instance of a class that
implements the Iterator interface. The Iterator object can be used to traverse the collection, gaining
access to each element in order. (The concept of in order means dierent things for dierent kinds of
collections. For a collection instantiated from the TreeSet class, in order means in ascending order.)
• hasNext()
• next()
• remove()
You might say that an Iterator object acts as a doorkeeper for the collection object that it represents,
providing access to the contents of the collection in a very specic manner.
As mentioned earlier, when the collection is an object instantiated from the TreeSet class, access to the
elements is provided in ascending order.
while(iter.hasNext()){
System.out.print(iter.next());
}//end while loop
5.4.1.7.6.3 An analogy
Frankly, I don't care how the programmers at Sun implemented the TreeSet class, so long as the behavior
of objects instantiated from that class meets the published specications.
As an analogy, I also don't care how they implemented the Random class, so long as objects instantiated
from the Random class provide the pseudo random values that I need in my programs.
I see no conceptual dierences between the TreeSet class and the Random class from a software
reuse viewpoint.
• I can instantiate an object of the Random class to produce pseudo random values, without caring
how those values are actually generated. However, if I am working in cryptography, I might need to
know how many such values can be generated before the sequence repeats.
• I can use any of the thirty or so methods of the Math class to produce a variety of complex
mathematical values without caring about how those values are actually produced. However, since
many of those values are approximations, I might need to know something about the quality of the
approximation.
• I can instantiate an object of the TreeSet class to create a collection object, which guarantees that
the sorted set will be in ascending element order, and provide log(n) time cost for the basic operations
of add , remove , and contains . As long as I know that, I have very little need to know exactly
how the collection object is implemented.
5.4.1.9 Summary
In this module, I have provided a brief introduction to the use of the Java Collections Framework . The
framework is designed to encourage you to reuse rather than to reinvent collections and maps (I will have
more to say about maps in a future module).
A collection represents a group of objects, known as its elements.
While some collections allow duplicate elements, others do not. Some collections are ordered and others
are not ordered.
The Collections Framework is dened by a set of interfaces and associated contracts. The framework
provides concrete implementations of the interfaces (classes) for the most common data structures. In
addition, the framework also provides several abstract implementations, which are designed to make it easier
for you to create new and dierent concrete implementations.
The TreeSet class is a concrete implementation of the SortedSet interface. The SortedSet
interface extends Set , which extends Collection . Thus, a TreeSet object is a SortedSet . Also
it is a Set , and it is a Collection .
The TreeSet class guarantees that the sorted set will be in ascending element order, and provides
guaranteed log(n) time cost for the basic operations ( add , remove and contains ).
TreeSet objects can be treated as the generic type Collection . Methods declared in the Collection
interface can be called on a TreeSet object without regard for the actual class from which the object was
instantiated. (This is polymorphic behavior.)
When such methods are called, the author of the program can have condence that the behavior of the
method will be appropriate for an object of the class from which the object was instantiated. In my opinion,
this is the true essence of object-oriented behavior.
5.4.1.11 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import java.util.TreeSet;
import java.util.Collection;
import java.util.Iterator;
class Worker{
public void doIt(){
Collection ref = new TreeSet();
Populator.fillIt(ref);
Iterator iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}//end while loop
System.out.println();
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(
Collection ref){
ref.add(new Integer(4));
ref.add(new Integer(4));
ref.add(new Integer(3));
ref.add(new Integer(2));
ref.add(new Integer(1));
}//end fillIt()
}//end class populator
-end-
5.4.2.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
The purpose of this module is to explain some of the details surrounding the use of a Java collection for
creating data structures. The module also discusses the interfaces and some of the concrete implementations
in the Java Collections Framework.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
250 in
Oracle's Java Tutorials
251 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.2.3 Preview
Collection is not only the name of a Java interface, it is also the term given to an object that groups multiple
elements into a single unit.
I will discuss the advantages of passing collections between methods as type Collection .
I will summarize the core interfaces in the Collections Framework and show you how they are related.
I will very briey discuss some of the concrete implementations of the interfaces that are provided by the
framework.
And nally, I will introduce you to the three kinds of things that are part of a collections framework.
5.4.2.4 Generics
The code in this series of modules is written with no thought given to Generics
252 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
250 http://docs.oracle.com/javase/tutorial/collections/index.html
251 http://docs.oracle.com/javase/tutorial/index.html
252 http://docs.oracle.com/javase/tutorial/java/generics/index.html
5.4.2.5 Discussion
5.4.2.5.1 What is a collection?
Just to see if you are awake today, let's start with a little quiz.
What is a collection insofar as Java programming is concerned?
If you answered A, you are probably reading an article on the wrong website by mistake. If you answered
Both B and C , then you are o to a good start on this module.
Collection is the name of a Java interface. This interface is an integral part of the Java Collections
Framework . Collection is one of two top-level interfaces in the framework. The other top-level interface
in the framework is named Map .
According to The Java Tutorial from Oracle, a collection (sometimes called a container) is also an object
that groups multiple elements into a single unit.
Typical collection objects might contain information about employees in the company telephone book, all
the purchase orders issued during the past year, or the transactions occurring in a person's checking account.
253 http://docs.oracle.com/javase/tutorial/java/generics/index.html
• Collection
• Set
• List
• Queue
• Deque
• SortedSet
• Map
• SortedMap
• Iterator
• Collection
· Set
* SortedSet
· List
· Queue
· Deque
• Map
· SortedMap
As you can see, as mentioned earlier, Collection and Map are the two top-level interfaces.
You should probably commit the above list of interfaces and their relationships to memory. You might
nd that helpful when navigating the Oracle documentation.
• AbstractSet
• AbstractList
• AbstractMap
• HashSet
• TreeSet
• LinkedList
• Vector
• ArrayList
• HashMap
• Hashtable
• WeakHashMap
• TreeMap
• Iterator
• Attributes
• RenderingHints
Hopefully your answer was False, but even so, that isn't the complete answer.
• Interfaces
• Implementations
• Algorithms
This is probably a good place to close o the discussion for this module. The next module will take up
at this point, providing a more in-depth discussion of the interfaces, implementations, and algorithms that
make up the framework.
5.4.2.6 Summary
I started out by telling you that a collection is not only the name of a Java interface (Collection) but is
also an object that groups multiple elements into a single unit.
Java Collection objects don't store objects or primitive values directly. Rather, they store references
to objects. Further, all such references are stored as the type Object . However, the use of the Generics
syntax can eliminate the need to downcast the reference in order to gain access to the members of the object
to which it refers. (Generics also provide other useful properties as well.)
If you need to store primitive values in a collection, you will rst need to wrap those values in appropriate
objects. Standard wrapper classes are provided for all the primitive types.
Collections are not only useful for storing and retrieving data, they are also useful for moving data among
methods.
Because a collection can be passed to a method as type Collection , all of the methods declared in
the Collection interface can be called on the incoming reference in a polymorphic manner.
In addition to the interfaces dened in the Collections Framework, the framework also provides various
concrete implementations of the interfaces for many of the commonly-used data structures. This makes
it possible for you to conveniently use the framework without the requirement to dene new Collection
classes.
There are eight core interfaces in the Collections Framework. Although the Iterator interface is often
used with collections, it is not one of the core interfaces.
I ended the module by telling you that there are basically three things in a collections framework:
interfaces, implementations, and algorithms.
5.4.2.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.3.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
There are eight core interfaces in the Collections Framework . Each interface declares several methods
and provides a contract that applies to each declared method. The method declarations and their associated
contracts specify the general behavior of matching methods in the classes that implement the interfaces.
The purpose of this module is to provide a brief explanation of those interfaces.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
255 in
Oracle's Java Tutorials
256 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.3.3 Preview
At least three things are included in a collections framework:
• interfaces
• implementations
• algorithms
This module will discuss the purpose of the interfaces in the Collections Framework. Future modules will
discuss implementations and algorithms.
5.4.3.4 Introduction
In an earlier module, we learned that the Collections Framework contains eight core interfaces with the
parent-child relationships shown below :
• Collection
· Set
* SortedSet
· List
· Queue
· Deque
• Map
· SortedMap
255 http://docs.oracle.com/javase/tutorial/collections/index.html
256 http://docs.oracle.com/javase/tutorial/index.html
5.4.3.5 Generics
The code in this series of modules is written with no thought given to Generics
257 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
5.4.3.6 Discussion
5.4.3.6.1 Purpose of framework interfaces
A collection is an object of some type, and that type is dened in a generic sense by one or more interfaces
that make up the Collections Framework.
257 http://docs.oracle.com/javase/tutorial/java/generics/index.html
As you can see, the contract for the add method declared in the List interface, (which extends
Collection) , does not prohibit duplicate elements. However, it does have some other requirements that
don't apply to Set objects. For example, it must add new methods at the end of the list.
• HashSet
• TreeSet
• LinkedList
• Vector
• ArrayList
• HashMap
• Hashtable
• WeakHashMap
• TreeMap
In addition, Oracle provided us with several partial implementation classes including AbstractSet ,
AbstractList , and AbstractMap , which are intended to serve a starting point for new implementations
that we choose to dene. According to Oracle, these classes provide a skeletal implementation of the Set,
List, and Map interfaces to minimize the eort required to implement those interfaces.
5.4.3.7 Summary
There are eight core interfaces in the Collections Framework.
As is always the case, each of the core interfaces denes a data type. Each interface declares several
methods. In addition, each interface provides a contract that applies to each declared method. The contracts
become more specic as we traverse down the interface inheritance hierarchy.
Objects instantiated from classes that implement the interfaces can be considered to be of the interface
type or any ancestor interface in the interface's hierarchical family tree.
The method declarations and their associated contracts in the interfaces specify the general behavior of
matching methods in the classes that implement the interfaces.
The framework provides several concrete implementations of the interfaces that we can use to instantiate
new objects to use as data structures or data containers.
The framework also provides several abstract implementations that we can use as a starting point for
dening our own implementations.
5.4.3.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.4.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module explains how the core collection interfaces in the Java Collections Framework allow collec-
tions to be manipulated without regard for how they are implemented. The framework provides nine or more
concrete implementations of the interfaces. The framework also provides various algorithms for manipulating
the data in the collections.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
260 in
Oracle's Java Tutorials
261 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.4.2.1.1 Listings
• Listing 1 (p. 1212) . SpeedTest01.
• Listing 2 (p. 1213) . Beginning of the doIt method.
• Listing 3 (p. 1213) . Instantiate and populate an ArrayList object.
• Listing 4 (p. 1214) . Identify a target element.
• Listing 5 (p. 1215) . Search for the test value in each collection.
260 http://docs.oracle.com/javase/tutorial/collections/index.html
261 http://docs.oracle.com/javase/tutorial/index.html
5.4.4.3 Preview
At least three things are included in the Java Collections Framework:
• interfaces
• implementations
• algorithms
The previous module discussed the purpose of the interfaces. This module will discuss the purpose of the
implementations and the algorithms in the Collections Framework.
5.4.4.4 Generics
The code in this series of modules is written with no thought given to Generics
262 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
5.4.4.5 Introduction
We learned in an earlier module that the framework provides at least nine concrete implementations of the
interfaces in the framework. These nine implementation classes are available for immediate instantiation to
produce objects to satisfy your collection needs.
We also learned that the framework provides at least three incomplete implementations. These classes are
available for you to use as a starting point in dening your own implementations. Default implementations
of many of the interface methods are provided in the incomplete implementations.
• HashSet
• TreeSet
• LinkedList
• ArrayList
• Vector
• HashMap
• WeakHashMap
• TreeMap
• Hashtable
• AbstractSet
• AbstractList
• AbstractMap
Therefore, by either using one of the three classes listed above as a starting point, or by starting from
scratch and fully implementing one or more of the interfaces, you can provide new concrete implementations
to augment the framework to include collections that meet your special needs. If you do that, be sure to
satisfy the contract requirements of the Collections Framework in addition to the technical requirements
imposed by implementing interfaces.
Listing 1. SpeedTest01.
/*File SpeedTest01
Copyright 2001 R.G.Baldwin
**************************************/
import java.util.*;
class Worker{
public void doIt(){
int size = 2000000;
//Create a TreeSet object
Collection aTree = new TreeSet();
}//end doIt()
1213
The code in Listing 4 (p. 1214) extracts a value near the center of the ArrayList object using an
index to nd and extract the value. This is a very fast operation on a List object. This value is saved in
testVal to be used later for test purposes.
Note that the reference to the ArrayList object was saved as type Collection (and not as type
ArrayList ) in Listing 3 (p. 1213) above.
Note also that it was necessary to cast that reference to type List in Listing 4 (p. 1214) in order to call
the get method on the reference. This is because the Collection interface does not declare a method
named get . Rather, the get method is added to the List interface to dene a more specialized form
of collection.
(Author's note: This program was originally written before the introduction of Generics. The
above requirement may not be true if the program were to be rewritten making proper use of
Generics.)
}//end doIt()
Figure 5.454: Listing 5. Search for the test value in each collection.
The rst output value applies to the ArrayList object, and the second output value applies to the
TreeSet object.
As we would expect, the test value was successfully found in both cases; hence the display of true in both
cases.
The interfaces in the Collections Framework make it possible to manipulate the contents of
collections in a manner that is (dependent on) (independent of) the underlying implementation
of each collection.
(Author's note: Once again, this document was originally written before the release of Generics.
The use of the more specialized sub-interfaces described above may not be required if the program
is written making proper use of Generics.)
For a detailed explanation of these benets, I am simply going to refer you directly to The Java Tutorial
265
.
5.4.4.8 Summary
Let's recap some of what we have learned in this and the previous modules.
The core collection interfaces in the Collections Framework are shown below.
• Collection
· Set
* SortedSet
· List
· Queue
· Deque
• Map
· SortedMap
The basic purpose of the core collection interfaces in the Java Collections Framework is to allow collections
to be manipulated without regard for how the collections are implemented, provided of course that the
implementations comply with the contracts.
The framework provides at least the following nine concrete implementations (classes) of the interfaces
shown above:
• HashSet
• TreeSet
264 http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html
265 http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html
• LinkedList
• ArrayList
• Vector
• HashMap
• WeakHashMap
• TreeMap
• Hashtable
For example, the classes TreeSet and ArrayList are concrete implementations of the Collection
interface as shown in the above list.
A collection object instantiated from the class TreeSet and a collection object instantiated from the class
ArrayList can each be viewed as being of the interface type Collection .
Methods having the same signatures can be used to manipulate either collection with condence that the
behavior of the method will be appropriate for the actual type of collection involved.
The framework also provides the following incomplete implementations of the core interfaces:
• AbstractSet
• AbstractList
• AbstractMap
The purpose of these implementations is to provide you with a starting point for dening your own concrete
implementations for more specialized collections.
5.4.4.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.5.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
The Java Collections Framework denes eight core interfaces, in two distinct trees. You will learn about
the inheritance structure and the purpose of those interfaces. You will also learn how the interfaces declare
polymorphic methods that apply to implementations of the interfaces, and you will learn about the optional
methods of the Collection and Map interfaces.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
267 in
Oracle's Java Tutorials
268 . The modules in this collection are intended to supplement and not to replace
those tutorials.
266 This content is available online at <http://cnx.org/content/m46138/1.2/>.
267 http://docs.oracle.com/javase/tutorial/collections/index.html
268 http://docs.oracle.com/javase/tutorial/index.html
5.4.5.2.1.1 Listings
• Listing 1 (p. 1221) . The program named Ap401.
• Listing 2 (p. 1222) . The Populator class.
• Listing 3 (p. 1223) . Create and populate a TreeSet object.
• Listing 4 (p. 1224) . Create and populate an ArrayList object.
5.4.5.3 Preview
In earlier modules, you learned that at least three things are included in a collections framework:
• interfaces
• implementations
• algorithms
Earlier modules provided a general discussion of the purpose of the interfaces, implementations, and algo-
rithms in the Collections Framework . This module takes that discussion further and illustrates the use of
the core collection interfaces.
The Java Collections Framework denes eight core interfaces, in two distinct trees. You will learn the
names and the inheritance structure of those interfaces. You will also learn about the purpose of some of
those interfaces. You will see how the interfaces declare polymorphic methods that apply to implementations
of the interfaces, and you will learn about the optional methods of the Collection interface.
5.4.5.4 Generics
The code in this series of modules is written with no thought given to Generics
269 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
• A. Compiler Error
• B. Runtime Error
• C. 44321 44321
• D. 12344 12344
• E. 1234 44321
• F. 1234 4321
• D. None of the above.
269 http://docs.oracle.com/javase/tutorial/java/generics/index.html
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Worker{
public void doIt(){
Collection ref = new TreeSet();
Populator.fillIt(ref);
Iterator iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}//end while loop
System.out.print(" ");
class Populator{
public static void fillIt(Collection ref){
ref.add(new Integer(4));
ref.add(new Integer(4));
ref.add(new Integer(3));
ref.add(new Integer(2));
ref.add(new Integer(1));
}//end fillIt()
}//end class populator
The program in Listing 1 (p. 1221) illustrates the basic purpose of the core collection interfaces in the
Java Collections Framework. That purpose is to allow collections to be manipulated without regard for how
the collections are implemented.
class Populator{
public static void fillIt(Collection ref){
ref.add(new Integer(4));
ref.add(new Integer(4));
ref.add(new Integer(3));
ref.add(new Integer(2));
ref.add(new Integer(1));
}//end fillIt()
}//end class populator
The llIt method will be used to populate two collections of dierent types with the same data values
in the same order.
The code in Listing 3 (p. 1223) instantiates an object of type TreeSet , and passes that object's
reference to the llIt method as type Collection . As described above, the llIt method adds ve
elements to the collection, in random order with two of the elements being duplicates.
"Note that this program does not use the syntax for Generics. Therefore, if you copy and compile
this program, you will probably see a warning regarding unchecked or unsafe operations"
The code in Listing 4 (p. 1224) instantiates a new collection of type ArrayList , and passes that
object's reference to the same llIt method, once again as type Collection .
The code in the llIt method adds ve elements having the same values as before to the collection and
adds them in the same order as before. The added elements are references to Integer objects encapsulating
the same values as were earlier added to the TreeSet collection. Although they are physically dierent
objects, the result is that essentially the same data is added to both collections.
• Collection
· Set
* SortedSet
· List
· Queue
· Deque
• Map
· SortedMap
• add()
• addAll()
• clear()
• remove()
• removeAll()
• retainAll()
• clear()
• put()
• putAll()
• remove()
5.4.5.7 Summary
A collections framework contains at least the following items:
• interfaces
• implementations
• algorithms
The Java Collections Framework denes eight core interfaces, in two distinct trees. One tree is rooted in
Collection and the other is rooted in Map .
The basic purpose of the core interfaces is to make it possible for collections to be manipulated without
regard for how they are implemented, so long as the implementation satises the contracts of the interfaces.
When the same method name (and signature) is called on references to collections of dierent types,
the behavior of the method is likely to be dierent for each collection. However, in each case, that behavior
will be appropriate for the type of collection object on which the method is called. This is polymorphic
behavior.
Six of the methods declared in the Collection interface are optional insofar as being supported by
implementing classes is concerned. The optional methods all have the ability to modify the contents of the
collection. Those implementing classes that don't support an optional method must throw anUnsupport-
edOperationException if that method is called on an object of the class. Similarly four of the methods
declared in the Map interface are optional.
Many methods declared in the Collection interface are not optional. Generally, the non-optional
methods don't have the ability to modify the collection.
5.4.5.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.6.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
271 in
Oracle's Java Tutorials
272 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.6.3 Preview
You learned in earlier modules that the Java Collections Framework denes eight core interfaces, in two
distinct trees. One of the trees, which consists of six interfaces, is rooted in the interface named Collection
. The other tree, which consists of two interfaces, is rooted in the interface named Map .
You learned the names and the inheritance structure of those interfaces. You also learned about their
purpose. You saw how the interfaces declare polymorphic methods that apply to implementations of the
interfaces, and you learned about the optional methods of the Collection interface and the Map interface.
In this module you will learn that all of the implementations of the interfaces on the Collection side
of the Java Collections Framework (the Collection hierarchy) implement one of the sub-interfaces of the
Collection interface.(A similar discussion regarding the Map side of the Java Collections framework
will be deferred until a future module.)
You will learn that a Set object cannot contain duplicate elements, but a List object can contain
duplicate elements.
You will learn about the dierence between ordered collections and sorted collections. You will also
learn about ascending order and the natural ordering of objects.
In addition, you will learn how more specialized stipulations are placed on interfaces as you progress
down the interface inheritance hierarchy of the Java Collections Framework.
5.4.6.4 Generics
The code in this series of modules is written with no thought given to Generics
273 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
271 http://docs.oracle.com/javase/tutorial/collections/index.html
272 http://docs.oracle.com/javase/tutorial/index.html
273 http://docs.oracle.com/javase/tutorial/java/generics/index.html
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
5.4.6.5 Discussion
5.4.6.5.1 We will start with a quiz
I am going to begin this module with a quiz just to make sure that you are still awake. Is the following
statement True or False?
• Collection
· Set
* SortedSet
· List
· Queue
· Deque
• Map
· SortedMap
As you learned in an earlier module, the Java Collections Framework doesn't have a single root. As shown
above, there are two distinct trees in the framework The Collection hierarchy and the Map hierarchy.
A sample program in that earlier module created two collection objects and applied the polymorphic add
method to add the same elements to each collection. One of the collection objects was of type ArrayList ,
and the other collection object was of type TreeSet . The elements added to each collection contained one
pair of duplicate elements. The duplicate element was automatically excluded from the TreeSet object,
but was retained in the ArrayList object.
On the other hand, the add method of the Collection interface simply states:
Thus, the contract for the add method of an object of a class that implements the Set interface is more
specialized than the contract for the add method of an object of a class that implements the Collection
interface.
An additional stipulation on the constructor for a Set object is that all constructors must create a set
that contains no duplicate elements.
5.4.6.5.9.1 Question 1
True or False? A collection that implements the List interface maintains its elements in ascending
alphanumeric order.
The answer to question 1 is False. Unlike collections that implement the SortedSet interface, the order
of the elements in a collection that implements the List interface is not based on the values of the objects
referred to by the elements in the list.
5.4.6.5.9.2 Question 2
True or False? A collection that implements the List interface is an unordered collection.
The answer to question 2 is also False. A collection that implements the List interface is an ordered
collection (also known as a sequence) . According to Oracle, "The user of the interface has precise control
over where in the list each element is inserted." Elements can be inserted and retrieved on the basis of their
integer index (position in the list) using the following methods:
• get(int index)
Valid index values are positive integers that begin with zero. When the add method is used to insert
an element at a specic position in the sequence, the element currently at that position (if any) and any
subsequent elements are shifted toward higher index values to make room for the new element.
Another version of the add method takes a reference to an object as an incoming parameter and
appends the specied element to the end of the collection.
The get method simply returns the element at the specied position in the collection.
The List interface also declares various other methods that can be used to manipulate the contents of
the collection.
5.4.6.5.9.3 Question 3
True or False? A collection that implements the List interface is allowed to contain duplicate values.
The answer to question 3 is True. Unlike a collection that implements the Set interface, a collection that
implements the List interface is typically allowed to contain duplicate values. More formally, according to
Oracle, "lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow
multiple null elements if they allow null elements at all."
5.4.6.5.9.4 Question 4
True or False? The contracts of the methods in the List interface are the same as the contracts of the
methods inherited from the Collection interface.
The answer to question 4 is False. According to Oracle, "The List interface places additional stipu-
lations, beyond those specied in the Collection interface, on the contracts of the iterator , add ,
remove , equals , and hashCode methods."
For example, the iterator method (for both the List and Collection interfaces) returns an iterator
over the elements in the collection. For the Collection interface, there are no guarantees concerning the
order in which the elements are returned by the methods of the Iterator object.
On the other hand, the iterator method for the List interface returns an iterator over the elements
in the collection in proper sequence, where the sequence is determined by the numeric index. In other words,
when you call the methods of the Iterator object on a List , the elements will be returned in the proper
sequence as determined by a numeric index.
Similarly, according to Oracle, the SortedSet interface "guarantees that its iterator will traverse the
set in ascending element order, sorted according to the natural ordering of its elements (see Comparable
), or by a Comparator provided at sorted set creation time."
5.4.6.6 Summary
In this module you learned that all of the implementations of the interfaces in the Collection hierarchy
implement one of the sub-interfaces of the Collection interface. You learned that a Set object cannot
contain duplicate elements, but a List object can contain duplicate elements.
You learned about the dierence between ordered collections and sorted collections. You also learned
about ascending order and the natural ordering of objects. In addition, you learned how more specialized
stipulations are placed on interfaces as you progress down the interface inheritance hierarchy of the Java
Collections Framework.
5.4.6.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.7.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections Framework in particular.
This is also the rst module in a sub-collection on the Comparable interface. The purpose of the
modules in this sub-collection is to teach you about the interactions between the Comparable interface
and the Collections Framework, particularly with respect to the Set , SortedSet , and SortedMap
interfaces of the Collections Framework.
This module explains the (lack of) interaction between the Comparable interface and the Java
Collections Framework with respect to collections of type List .
In addition to studying these modules, I strongly recommend that you study the Collections Trail
275 in
Oracle's Java Tutorials
276 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.7.2.1.1 Listings
• Listing 1 (p. 1236) . The program named Comparable01.
• Listing 2 (p. 1237) . The code with the problem.
• Listing 3 (p. 1239) . The program named Comparable02.
• Listing 4 (p. 1240) . The corrected code.
• Listing 5 (p. 1241) . Display using an iterator.
• Listing 6 (p. 1243) . The program named Comparable03.
• Listing 7 (p. 1244) . No need to cast to type List.
275 http://docs.oracle.com/javase/tutorial/collections/index.html
276 http://docs.oracle.com/javase/tutorial/index.html
5.4.7.3 Preview
In this module, I will begin discussing the interaction between the Comparable interface and the Collec-
tions Framework.
5.4.7.3.1 Generics
The code in this module is written with no thought given to Generics
277 . As a result, if you copy and
compile this code, you will probably get a warning about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
5.4.7.3.2 Specialization
I will provide a concrete example of the specialization that occurs while moving down the interface hierarchy
from Collection to List . I will show an example of using two dierent overloaded versions of the
add method to add new elements to an ArrayList object. One version is declared in the Collection
interface and both versions are declared in the List interface.
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 4321
• E. 1234
• F. 12344
• G. None of the above.
277 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparable01.java
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
class Populator{
public static void fillIt(Collection ref){
ref.add(0,new MyClass(4));
ref.add(1,new MyClass(4));
ref.add(2,new MyClass(3));
ref.add(3,new MyClass(2));
ref.add(4,new MyClass(1));
}//end fillIt()
}//end class Populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
The problem here is that the method named llIt receives a reference to an object of the ArrayList
class as the interface type Collection , and attempts to call the following overloaded method on that
reference:
add(int index, Object element)
However, the Collection interface knows nothing about a method having that signature.
• add(Object o)
• add(int index, Object element)
The second of these two methods, which is called in Listing 2 (p. 1237) , is unknown to the Collection
interface. The Collection interface declares only the rst version of the add method shown above.
5.4.7.4.1.3 Specialization
This is the result of specialization. A List object is a more-specialized collection than a Collection
object.
Therefore, the version of the add method that requires two parameter cannot be called on a reference
to an ArrayList object when that object is treated as the generic type Collection .
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 4321
• E. 1234
• F. 12344
• G. 443521
• H. None of the above.
//File Comparable02.java
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
class Populator{
public static void fillIt(Collection ref){
((List)ref).add(0,new MyClass(4));
((List)ref).add(1,new MyClass(4));
((List)ref).add(2,new MyClass(3));
((List)ref).add(3,new MyClass(2));
((List)ref).add(4,new MyClass(1));
((List)ref).add(3,new MyClass(5));
}//end fillIt()
}//end class populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
}//end MyClass
class Populator{
public static void fillIt(Collection ref){
((List)ref).add(0,new MyClass(4));
((List)ref).add(1,new MyClass(4));
((List)ref).add(2,new MyClass(3));
((List)ref).add(3,new MyClass(2));
((List)ref).add(4,new MyClass(1));
((List)ref).add(3,new MyClass(5));
}//end fillIt()
}//end class populator
The incoming parameter to thellIt method in Listing 4 (p. 1240) is a reference to an object instantiated
from the ArrayList class. That reference is passed to the llIt method as type Collection , which is
legal because the ArrayList class implements both the Collection interface and the List interface.
(A List is an ordered collection because the user has control over the location of each element
in the collection relative to the other elements in the collection.)
"Inserts the specied element at the specied position in this list (optional operation). Shifts
the element currently at that position (if any) and any subsequent elements to the right (adds
one to their indices)."
Thus, the new element is inserted at that position, and the other elements are pushed up, as required, toward
higher index values to make room for the new element.
As a result, the code shown in Listing 5 (p. 1241) , along with the overriddentoString method of the
MyClass class causes the program to display the elements in the following order:
443521 .
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}//end while loop
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 4321
• E. 1234
• F. 12344
• G. None of the above.
//File Comparable03.java
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
class Populator{
public static void fillIt(
Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class populator
This program does not change the type of the incoming reference to the ArrayList object in the llIt
method. Rather, it continues to treat the incoming reference as type Collection , and calls the version of
the add method that is declared in the Collection interface. This avoids the requirement to cast the
incoming reference to type List .
The contract for this version of the add method in the List interface is
"Appends the specied element to the end of this list (optional operation)."
As a result, the new elements are added to the collection in increasing index order. Since an iterator on a
List returns the elements in increasing index order, this program displays the elements in the same order
that they are added.
5.4.7.6 Summary
In this module, I began discussing the interaction between the Comparable interface and the Collections
Framework.
I provided a concrete example of the specialization that occurs when moving down the interface hierarchy
from Collection to List . I showed an example of using two dierent overloaded versions of the add
method to add new elements to an ArrayList object. One version is declared in the Collection interface
and both versions are declared in the List interface.
I illustrated the use of a cast to change the type of a reference from Collection to List , in order
to call a version of the add method that is declared only in the List interface. This version makes it
possible for the user to control the location of each individual element added to a List .
I illustrated that a cast is not required on a reference being treated as type Collection in order to call
the version of the add method that is declared in the Collection interface. This version of the add
method supports the addition of new elements only at the end of the List .
Finally, I explained that it is not necessary for objects to implement the Comparable interface to
make them eligible for inclusion in a List .
Although I didn't demonstrate it, I told you that it is necessary for objects to implement the Compa-
rable interface to make them eligible for inclusion in a SortedSet .
5.4.7.8 Miscellaneous
This section contains a variety of miscellaneous information.
• Published: 04/19/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.8.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module explains why the elements stored in aTreeSet collection must be references to objects
Comparable interface. The module also briey discusses
instantiated from a class that implements the
an alternative approach using the Comparator interface.
The module shows you how to implement the Comparable interface for a new class denition, explains
the "natural ordering of the elements" for a class, and discusses the "consistent with equals" requirement.
Finally, the module shows you how to dene a new class whose objects are eligible for inclusion in a TreeSet
collection.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
279 in
Oracle's Java Tutorials
280 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.8.2.1.1 Listings
• Listing 1 (p. 1249) . The program named Comparable04.
• Listing 2 (p. 1250) . The code with the problem.
• Listing 3 (p. 1253) . The program named Comparable05.
• Listing 4 (p. 1254) . Beginning of the class named MyClass.
• Listing 5 (p. 1255) . The compareTo method.
• Listing 6 (p. 1255) . The overridden equals method.
5.4.8.3 Preview
In this module, I will teach you why the elements stored in a TreeSet collection must be references to
objects instantiated from a class that implements the Comparable interface. ( In a subsequent module,
I will teach you about an alternative approach that makes use of the Comparator interface.)
I will provide an example of implementing the Comparable interface for a new class denition, and
will teach you about the natural ordering of the elements for a class.
I will teach you the meaning of the consistent with equals requirement and show you how to satisfy
that requirement for a new class denition.
Finally, I will show you how to dene a new class whose objects are eligible for inclusion in a TreeSet
collection.
279 http://docs.oracle.com/javase/tutorial/collections/index.html
280 http://docs.oracle.com/javase/tutorial/index.html
281 http://docs.oracle.com/javase/tutorial/java/generics/index.html
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 4321
• E. 1234
• F. 12344
• G. None of the above.
//File Comparable04.java
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class Populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
}//end MyClass
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
"Adds the specied element to this set if it is not already present ... If this set already contains
the specied element, the call leaves this set unchanged and returns false. ... this ensures that
sets never contain duplicate elements."
"... the Set interface is dened in terms of the equals operation, but a TreeSet instance
performs all key comparisons using its compareTo (or compare ) method ..."
What this means is that insofar as the handling of duplicate elements is concerned, (with the possible
exception given below involving a Comparator ), in order for a reference to an object to be included in
a TreeSet collection, the class from which that object is instantiated must implement the Comparable
interface.
"A set that further guarantees that its iterator will traverse the set in ascending element or-
der, sorted according to the natural ordering of its elements (see Comparable ), or by a
Comparator provided at sorted set creation time."
"This interface imposes a total ordering on the objects of each class that implements it. This
ordering is referred to as the class's natural ordering, and the class's compareTo method is
referred to as its natural comparison method."
//File Comparable05.java
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class Populator
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
The code shown in Listing 4 (p. 1254) is identical to the code in the previous version with one major
exception. This version of the class denition implements the Comparable interface. That means that
this class must provide a concrete denition for the following method, which is the only method declared in
the Comparable interface:
public int compareTo(Object o)
"Compares this object with the specied object for order. Returns a negative integer, zero, or
a positive integer as this object is less than, equal to, or greater than the specied object."
Beyond this, there are a number of additional stipulations that I won't repeat here. You can view them in
the Oracle documentation if you are interested in that level of detail.
Listing 5 (p. 1255) shows my implementation of the compareTo method. Although this implementation
satises the general description given above, I haven't taken the time to test it fully to conrm that it meets
all of the additional stipulations provided by Oracle.
"Note that the ordering maintained by a set (whether or not an explicit comparator is provided)
must be consistent with equals if it is to correctly implement the Set interface. ..."
As was the case in dening the compareTo method, there are also a large number of stipulations
involved in properly overriding the equals method. I will simply refer you to the Oracle documentation if
you are interested in reading about those stipulations.
5.4.8.6 Summary
I explained why the elements stored in a TreeSet collection must be references to objects instantiated
from a class that implements the Comparable interface. ( In a future module, I will teach you about an
alternative approach that makes use of the Comparator interface.)
I provided an example of implementing the Comparable interface for a new class denition, and I
taught you about the natural ordering of the elements for a class.
I taught you the meaning of the consistent with equals requirement and showed you how to satisfy that
requirement for a new class denition.
I showed you how to dene a new class whose objects are eligible for inclusion in a TreeSet collection.
5.4.8.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.9.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module discusses and illustrates the use of the Comparator interface. The sorting order estab-
lished by a Comparator may be dierent or may be the same as the natural order. A Comparator
can be used to establish a sorting order for objects that don't have a natural ordering. The use of a
Comparator Comparable interface.
is an alternative to the implementation of the
Comparator interface. The purpose
This module is also the rst module in a series of modules on the
of the modules in this series is to teach you about the interactions between the Comparator interface
and the Collections Framework , particularly with respect to the Set , SortedSet , and SortedMap
interfaces of the Collections Framework. This module discusses Set and SortedSet . A discussion of
SortedMap will be deferred to a future module.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
283 in
Oracle's Java Tutorials
284 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.9.2.1.1 Listings
• Listing 1 (p. 1260) . The program named Comparator02.
• Listing 2 (p. 1261) . Passing Comparator to TreeSet constructor.
• Listing 3 (p. 1262) . The llIt method.
• Listing 4 (p. 1263) . The class named MyClass.
• Listing 5 (p. 1263) . Beginning of the class named TheComparator.
• Listing 6 (p. 1264) . Beginning of the compare method.
• Listing 7 (p. 1265) . Implementation of required behavior.
• Listing 8 (p. 1266) . The overridden equals method.
• Listing 9 (p. 1266) . Display the contents of the TreeSet object.
5.4.9.3 Preview
Previous modules have discussed the use of the Comparable interface. This module discusses and
illustrates the use of the Comparator interface.
The Comparable interface establishes natural ordering. The sorting order established by a
Comparator may be dierent or may be the same as the natural order.
A Comparator can be used to establish a sorting order for objects that don't have a natural ordering
.
The use of a Comparator is an alternative to the implementation of the Comparable interface. A
TreeSet object instantiated with the benet of a Comparator object doesn't require the objects in its
collection to implement Comparable .
283 http://docs.oracle.com/javase/tutorial/collections/index.html
284 http://docs.oracle.com/javase/tutorial/index.html
• A. Compiler Error
• B. Runtime Error
• C. 44321
• D. 4321
• E. 1234
• F. 12344
• G. None of the above.
285 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator02.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import java.io.Serializable;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class Populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
}//end MyClass
1261
Collection ref;
ref = new TreeSet(new TheComparator());
Populator.fillIt(ref);
class Populator{
public static void fillIt(Collection ref){
ref.add(new MyClass(4));
ref.add(new MyClass(4));
ref.add(new MyClass(3));
ref.add(new MyClass(2));
ref.add(new MyClass(1));
}//end fillIt()
}//end class Populator
class MyClass{
int data;
MyClass(){
data = 0;
}//end noarg constructor
MyClass(int data){
this.data = data;
}//end parameterized constructor
class TheComparator
implements Comparator,Serializable{
As you can see, the class named TheComparator implements both the Comparator interface and
the Serializable interface.
"Note: It is generally a good idea for comparators to implement java.io.Serializable, as they may
be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order
for the data structure to serialize successfully, the comparator (if provided) must implement
Serializable."
Since the Serializable interface doesn't declare any methods, implementing the interface simply requires
a declaration that the interface is being implemented.
The purpose of a Comparator is to compare the values stored in the instance variables of two objects
and to return a value indicating which object is greater .
The code in Listing 6 (p. 1264) conrms that both of the objects to be compared are of the correct type,
which in this case is type MyClass .
"Compares its two arguments for order. Returns a negative integer, zero, or a positive integer
as the rst argument is less than, equal to, or greater than the second."
(Note that it is up to the author of the compare method to decide what constitutes larger. This
gives the author of the method a great deal of control over the results of a sorting operation.)
"Note that it is always safe not to override Object.equals(Object). However, overriding this
method may, in some cases, improve performance by allowing programs to determine that two
distinct Comparators impose the same order."
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}//end while loop
"A set that further guarantees that its iterator will traverse the set in ascending element or-
der, sorted according to the natural ordering of its elements (see Comparable ), or by a
Comparator provided at sorted set creation time."
In this case, the sorted order was controlled by the Comparator object, and not by the natural ordering
of the elements. The natural ordering is controlled by implementation of the Comparable interface,
and the elements in this collection did not implement the Comparable interface. Therefore, objects of
the class named MyClass do not have a natural order in this program.
However, the code in this version of the Comparator produced an output order that matches the
ascending natural order that one might expect for objects of type MyClass . Future modules will show
you how to design the Comparator object to produce dierent output orders, such as descending order
for example.
5.4.9.6 Summary
This module has discussed and illustrated the use of the Comparator interface.
The sorting order established by a Comparator may be dierent or may be the same as the natural
ordering for a collection of objects .
A Comparator can be used to establish a sorting order for objects that don't have a natural ordering
.
The use of a Comparator is an alternative to the implementation of the Comparable interface.
A TreeSet object instantiated with the benet of a Comparator object doesn't require the objects
in its collection to implement Comparable .
5.4.9.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.10.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to use a Comparator object to achieve natural (ascending) order on a
set of names added as String objects to a TreeSet collection while ignoring the case used to write the
names.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
287 in
Oracle's Java Tutorials
288 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.10.2.1.1 Listings
• Listing 1 (p. 1270) . The program named Comparator03
• Listing 2 (p. 1272) . Create, populate, and display a TreeSet collection.
• Listing 3 (p. 1273) . The class named Populator.
• Listing 4 (p. 1274) . A TreeSet with a Comparator.
• Listing 5 (p. 1274) . Populating the TreeSet collection.
• Listing 6 (p. 1275) . Beginning of the Comparator class.
• Listing 7 (p. 1275) . The interesting code in the compare method.
5.4.10.3 Preview
In this module, I will show you how to use a Comparator object to achieve a natural ordering of a set
of names ( String objects) added to a TreeSet collection while ignoring the case used to write the
names. (The natural ordering for String objects is ascending.)
• A. Compiler Error
• B. Runtime Error
• C. Joe Bill Tom JOE BILL TOM
• D. Tom TOM Joe JOE Bill BILL
• E. Joe Bill Tom
• F. None of the above.
287 http://docs.oracle.com/javase/tutorial/collections/index.html
288 http://docs.oracle.com/javase/tutorial/index.html
289 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator03.java
//Copyright 2001 R.G.Baldwin
import java.util.*;
import java.io.Serializable;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
System.out.println("Natural ordering");
ref = new TreeSet();
Populator.fillIt(ref);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
System.out.println();
System.out.println("Comparator in use");
ref = new TreeSet(new TheComparator());
Populator.fillIt(ref);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
System.out.println();
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
class TheComparator
implements Comparator,Serializable{
• Natural ordering
• BILL Bill JOE Joe TOM Tom
• Comparator in use
• Bill Joe Tom
• Natural ordering
• BILL Bill JOE Joe TOM Tom
As you will see later, the names were added to the collection in a dierent order than the output order shown
above.
In this step, each of the six names that were added to the collection were displayed after they were
arranged into their natural ordering .
In case you are unfamiliar with this aspect of character encoding, upper-case characters appear before
lower-case characters in the natural ordering of characters in the Unicode character set. Therefore, the
names consisting of all upper-case characters appear in the output ahead of the same names consisting of a
mixture of upper-case and lower-case characters.
• Comparator in use
• Bill Joe Tom
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
Populator.fillIt(ref);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
The code in Listing 4 (p. 1274) was also used to populate the collection, and to display the contents of
the collection after it was populated.
class TheComparator
implements Comparator,Serializable{
Listing 6 (p. 1275) doesn't contain the interesting part of this class. The code in Listing 6 (p. 1275)
simply throws an exception if the compare method receives any incoming parameters of types other than
String .
int result =
((String)o1).toUpperCase().
compareTo(((String)o2).
toUpperCase());
return result;
}//end compare()
The code in Listing 7 (p. 1275) makes use of two methods of the String class to compare the two
incoming objects.
"Returns: the value 0 if the argument is a string lexicographically equal to this string; a value
less than 0 if the argument is a string lexicographically greater than this string; and a value
greater than 0 if the argument is a string lexicographically less than this string."
5.4.10.6 Summary
In this module, I showed you how to use a Comparator object to achieve a natural ordering of a set
of names ( String objects) added to a TreeSet collection while ignoring the case used to write the
names. (Natural ordering for String objects is ascending.)
5.4.10.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.11.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
The module shows you how to use a Comparator to cause a TreeSet collection to be sorted in
descending order while preserving the impact of dierences in case.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
291 in
Oracle's Java Tutorials
292 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.11.2.1.1 Listings
• Listing 1 (p. 1280) . The program named Comparator04.
• Listing 2 (p. 1281) . A new TreeSet object with a Comparator.
• Listing 3 (p. 1282) . The llIt method.
• Listing 4 (p. 1282) . Beginning of the class named TheComparator.
• Listing 5 (p. 1283) . The most interesting code.
5.4.11.3 Preview
In this module, I will teach you how to use a Comparator to cause a TreeSet collection to be sorted
in descending order while preserving the impact of dierences in case. We might refer to this as reverse
natural order. In other words, the sorting order is the same as the natural order except that the order is
descending instead of ascending.
5.4.11.4 Generics
The code in this series of modules is written with no thought given to Generics
293 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
• A. Compiler Error
• B. Runtime Error
• C. BILL Bill JOE Joe TOM Tom
• D. Tom TOM Joe JOE Bill BILL
• E. Joe Bill Tom
291 http://docs.oracle.com/javase/tutorial/collections/index.html
292 http://docs.oracle.com/javase/tutorial/index.html
293 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator04.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import java.io.Serializable;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
Collection ref;
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
names beginning with letters that are high in the alphabet occur before names beginning with letters that
are lower in the alphabet. In addition, names containing lower case characters appear before the same names
containing only upper case characters.
The code in Listing 4 (p. 1282) isn't particularly interesting. That code simply throws an exception if
either of the references passed to the compare method refer to an object of some type other than String
.
"Returns: the value 0 if the argument is a string lexicographically equal to this string; a value
less than 0 if the argument is a string lexicographically greater than this string; and a value
greater than 0 if the argument is a string lexicographically less than this string."
return result*(-1);
5.4.11.7 Summary
In this module, I taught you how to use a Comparator to cause a TreeSet collection to be sorted in
reverse natural order. In other words, the sorting order is the same as the natural order except that the
order is descending instead of ascending.
5.4.11.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.12.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to extract the contents of a collection into an array, and how to use a
Comparator object to sort the contents of the array into reverse natural order. The module also shows
you how to sort the contents of the array into natural order without the use of a Comparator object.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
295 in
Oracle's Java Tutorials
296 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.12.2.1.1 Listings
• Listing 1 (p. 1287) . The program named Comparator 05.
• Listing 2 (p. 1288) . A new Vector object.
• Listing 3 (p. 1289) . Call the llIt method.
295 http://docs.oracle.com/javase/tutorial/collections/index.html
296 http://docs.oracle.com/javase/tutorial/index.html
5.4.12.3 Preview
The primary purpose of recent modules in this series was to teach you about the interactions between the
Comparator interface and the Collections Framework.
This module departs somewhat from that primary purpose and teaches you how to use a Comparator
object to sort the contents of an array containing references to objects. Technically speaking, an array is not
part of the core Collections Framework. However, it is denitely a rst cousin to the Framework.
5.4.12.4 Generics
The code in this series of modules is written with no thought given to Generics
297 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
297 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator05.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import java.io.Serializable;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
Object[] array;
array = ref.toArray();
System.out.println("Raw array data");
display(array);
iter = ref.iterator();
System.out.println("Collection data");
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
System.out.println();
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
}//end doIt()
If you wrote down the following for the program output, you already understand most of the material
covered in this module and you can probably skip this module and move on to the next module.
note:
Collection data
Joe Bill Tom JOE BILL TOM
Raw array data
Joe Bill Tom JOE BILL TOM
Natural order sorted array data
BILL Bill JOE Joe TOM Tom
Custom order sorted array data
Tom TOM Joe JOE Bill BILL
Collection data
Joe Bill Tom JOE BILL TOM
If you didn't write down the correct output for the program in Listing 1 (p. 1287) , you should probably
continue with your study of this module.
The Vector class was part of Java long before the Collections Framework was released. However, with
the release of the Collections Framework, the Vector class was upgraded to implement the Collection
interface and the List interface.
Populator.fillIt(ref);
The code for the llIt method is shown in Listing 4 (p. 1289) . As you can see, the names were added
to the collection in no particular order relative to their values. (The add method for the Vector class simply
adds each new element to the end of the list.)
class Populator{
public static void fillIt(
Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
iter = ref.iterator();
System.out.println("Collection data");
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
note:
Collection data
Joe Bill Tom JOE BILL TOM
As you can see, this is the same order in which the names were added to the collection by the llIt method
in Listing 4 (p. 1289) .
array = ref.toArray();
(Recall that the variable named array was declared as a reference to an array object of type
Object in Listing 1 (p. 1287) .)
"Returns an array containing all of the elements in this Vector in the correct order."
The documentation for the toArray method of the Collection interface is a little more verbose, reading
partially as follows:
"Returns an array containing all of the elements in this collection. If the collection makes any
guarantees as to what order its elements are returned by its iterator, this method must return
the elements in the same order.
"The returned array will be "safe" in that no references to it are maintained by this collection.
... The caller is thus free to modify the returned array."
In the code in Listing 6 (p. 1290) above, the returned reference to an array object is assigned to a reference
variable that previously contained null. Following the execution of the toArray method, that reference
variable refers to an array object of type Object containing the same elements as the Vector collection,
in ascending index order.
(Regarding the concept of a "safe" array, it is easy to demonstrate that the elements in the array
refer to the same objects referred to by the elements in the Vector. Thus, using the references
stored in the array to modify the objects to which they refer also modies the objects referred
to by the elements stored in the Vector. In other words, the elements in the array are copies of
the elements in the Vector. The elements in the array refer to the original objects, and do no
refer to copies of those objects. As usual when dealing with multiple references to objects, care
should be taken to avoid inadvertently corrupting those objects.)
The output produced by the code in Listing 7 (p. 1291) is as shown below:
note:
As you can see, this is the same data, in the same order, as the contents of the collection displayed earlier.
(The method named display is a simple utility method that I won't discuss here because of
its simplicity. You can view the display method in its entirety in Listing 1 (p. 1287) .)
Arrays.sort(array);
Here is part of what Oracle has to say about the Arrays class:
"This class contains various methods for manipulating arrays (such as sorting and searching)."
The class contains many overloaded versions of the sort method. Here is part of what Oracle has to say
about the version of the sort method used in Listing 8 (p. 1292) above:
"Sorts the specied array of objects into ascending order, according to the natural ordering of
its elements. All elements in the array must implement the Comparable interface."
note:
"Sorts the specied array of objects according to the order induced by the specied comparator.
All elements in the array must be mutually comparable by the specied comparator (that is,
c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array)."
Suce it to say at this point that this Comparator object causes the elements in the array to be
sorted into reverse natural order . That term was also explained in the previous module, so I won't discuss
it further here.
note:
You will recognize this as reverse natural order for the elements contained in the array.
iter = ref.iterator();
System.out.println("Collection data");
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
note:
Collection data
Joe Bill Tom JOE BILL TOM
If you compare this with the output produced by the code at the beginning of the program, you will see
that the iterator still returns the elements in the Vector in the same order that they were added. Thus,
modications to the array did not disturb the contents of the Vector collection.
Run the program and observe the results. Experiment with the code. Make changes, run the program
again, and observe the results of your changes. Make certain that you can explain why your changes behave
as they do.
5.4.12.7 Summary
In this module, I taught you how to extract the contents of a collection into an array and how to use a
Comparator to sort the contents of the array into reverse natural order .
Although I elected to use reverse natural order for purposes of illustration, I could have sorted the
array into some other order simply by dening the comparison rules in the compare method of the
Comparator class dierently.
In order to further expand your knowledge of array sorting, I also sorted the array into natural order
without the use of a Comparator .
Sorting the contents of the array did not disturb the contents of the Vector collection from which the
contents of the array were derived.
5.4.12.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.13.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to use the sort method of the Collections class along with a Com-
parator object to sort the contents of a List into reverse natural order.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
299 in
Oracle's Java Tutorials
300 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.13.2.1.1 Listings
• Listing 1 (p. 1299) . The program named Comparator06.
• Listing 2 (p. 1300) . A new LinkedList object.
• Listing 3 (p. 1301) . The llIt method.
• Listing 4 (p. 1301) . Sort the list.
• Listing 5 (p. 1303) . The Comparator.
• Listing 6 (p. 1303) . Display the sorted list.
299 http://docs.oracle.com/javase/tutorial/collections/index.html
300 http://docs.oracle.com/javase/tutorial/index.html
5.4.13.3 Preview
In this module, I will teach you how to use the sort method of the Collections class along with a
Comparator object to sort the contents of a List into reverse natural order .
The methodology that I will teach you is completely general, and can be used to sort a list in a wide
variety of ways, depending on how you dene the compare method of a Comparator object.
Furthermore, the same sort method and the same Comparator object can be used to sort any
implementation of a list, so long as the list properly implements the List interface.
5.4.13.4 Generics
The code in this series of modules is written with no thought given to Generics
301 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
• A. Compiler Error
• B. Runtime Error
• C. BILL Bill JOE Joe TOM Tom
• D. Tom TOM Joe JOE Bill BILL
• E. Joe Bill Tom
• F. None of the above.
301 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator06.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import java.io.Serializable;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
The LinkedList class is one of the concrete implementation classes of the Collections Framework. This
class implements the Collection interface and the List interface. Here is part of what Oracle has to say
about the LinkedList class:
"Linked list implementation of the List interface. Implements all optional list operations,
and permits all elements (including null). In addition to implementing the List interface, the
LinkedList class provides uniformly named methods to get, remove and insert an element at the
beginning and end of the list. These operations allow linked lists to be used as a stack, queue,
or double-ended queue (deque)."
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
The sort method expects to receive an incoming parameter of type List . Therefore, it was
necessary to cast the reference from type Collection to type List .
(The programs in previous modules that sorted the array did not rearrange the contents of the
list. Only the contents of the array were rearranged.)
Thus, the relationship between an element in the list and the index associated with that element can change
as a result of the sorting operation shown in Listing 4 (p. 1301) .
Following the sort, when an iterator is used to access the elements, the elements will be returned by the
iterator in the newly-sorted order.
public static void sort(List list, Comparator c) "Sorts the specied list according to the
order induced by the specied comparator. All elements in the list must be mutually comparable
using the specied comparator ...
The specied list must be modiable, but need not be resizable. This implementation dumps
the specied list into an array, sorts the array, and iterates over the list resetting each element
from the corresponding position in the array. This avoids the n2 log(n) performance that would
result from attempting to sort a linked list in place."
"iterates over the list resetting each element from the corresponding position in the array"
In other words, after sorting the array, the sort method uses the sorted results in the array to rearrange
the positions of the elements in the list, resulting in a sorted list.
I have presented and explained this class in previous modules, so I won't discuss it in detail again here.
Suce it for now to say that an object instantiated from this class will induce the list to be sorted into
reverse natural order .
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
The output produced by the code in Listing 6 (p. 1303) is shown below:
Tom TOM Joe JOE Bill BILL
As you can see, this is reverse natural order as induced by the Comparator object.
5.4.13.7 Summary
In this module, I taught you how to use the sort method of the Collections class along with a Comparator
object to sort the contents of a list.
By using this approach, you can sort the contents of list according to any set of comparison rules that
you can program into the compare method of the Comparator object.
Furthermore, the ability to sort the list is independent of the actual implementation of the list, so long
as the list properly implements the List interface. For example, the same Comparator object (and
the same code) can be used to sort an ArrayList , a LinkedList , or a Vector , producing the same
results regardless of which class the list object is instantiated from.
5.4.13.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.14.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to use a Comparator created by the reverseOrder method of the
Collections class to sort a list into reverse natural order. The module also shows you how to use the
reverse method of the Collections class to reverse the order of the elements in a list.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
303 in
Oracle's Java Tutorials
304 . The modules in this collection are intended to supplement and not to replace
those tutorials.
302 This content is available online at <http://cnx.org/content/m46194/1.1/>.
303 http://docs.oracle.com/javase/tutorial/collections/index.html
304 http://docs.oracle.com/javase/tutorial/index.html
5.4.14.2.1.1 Listings
• Listing 1 (p. 1307) . The program named Comparator07.
• Listing 2 (p. 1308) . A new ArrayList object.
• Listing 3 (p. 1309) . The llIt method.
• Listing 4 (p. 1309) . The reverse method of the Collections class.
• Listing 5 (p. 1310) . The reverseOrder method.
• Listing 6 (p. 1311) . Sorting the list.
• Listing 7 (p. 1312) . Produce the output.
5.4.14.3 Preview
In this module, I will teach you how to use a Comparator created by the reverseOrder method of the
Collections class to sort a list into reverse natural order . I will also teach you how to use the reverse
method of the Collections class to reverse the order of the elements in a list.
5.4.14.4 Generics
The code in this series of modules is written with no thought given to Generics
305 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
• A. Compiler Error
• B. Runtime Error
• C. Joe Bill Tom JOE BILL TOM
• D. BILL Bill JOE Joe TOM Tom
• E. TOM BILL JOE Tom Bill Joe
• F. Joe Bill Tom JOE TOM BILL
• G. Tom TOM Joe JOE Bill BILL
• H. Joe Bill Tom
• I. None of the above.
305 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File Comparator07.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
class Worker{
public void doIt(){
Iterator iter;
Collection ref;
Collections.reverse((List)ref);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
System.out.println();
}//end doIt()
}// end class Worker
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
Available for free at Connexions <http://cnx.org/content/col11441/1.121>
note:
If that was your answer, you probably already understand most of the material covered in this module. In
that case, you might consider skipping this module and moving on to the next module. If that wasn't your
answer, you should probably continue with your study of this module.
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
class Populator{
public static void fillIt(Collection ref){
ref.add("Joe");
ref.add("Bill");
ref.add("Tom");
ref.add("JOE");
ref.add("BILL");
ref.add("TOM");
}//end fillIt()
}//end class Populator
"Resizable-array implementation of the List interface. Implements all optional list operations,
and permits all elements, including null. ... (This class is roughly equivalent to Vector, except
that it is unsynchronized.)"
Collections.reverse((List)ref);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
"This class consists exclusively of static methods that operate on or return collections. It contains
polymorphic algorithms that operate on collections, "wrappers", which return a new collection
backed by a specied collection, and a few other odds and ends."
You should recall that the Collections class is not the same as the Collection interface. Don't confuse
the two.
"Returns a comparator that imposes the reverse of the natural ordering on a collection of objects
that implement the Comparable interface. (The natural ordering is the ordering imposed by the
objects' own compareTo method.) This enables a simple idiom for sorting (or maintaining)
collections (or arrays) of objects that implement the Comparable interface in reverse-natural-
order."
Collections.sort((List)ref, aComparator);
iter = ref.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}//end while loop
The output produced by the code in Listing 7 (p. 1312) is shown below:
Tom TOM Joe JOE Bill BILL
You will recognize this as reverse natural order for the elements in the list.
5.4.14.7 Summary
In this module, I taught you how to use a Comparator reverseOrder method of the
created by the
Collections class to sort a list into Comparator object is generic, and
reverse natural order . The
can be used to sort any list of objects that implement the Comparable interface.
I also taught you how to use the reverse method of the Collections class to reverse the order of the
elements in a list.
5.4.14.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.15.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to use the simpler version of the overloaded toArray method that is
declared in the Collection interface. The module also explains why you need to exercise care when using
the elements stored in the resulting array to avoid corrupting the state of the objects referred to by the
elements in the collection.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
307 in
Oracle's Java Tutorials
308 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.15.2.1.1 Listings
• Listing 1 (p. 1316) . The program named ToArray01.
• Listing 2 (p. 1317) . A new LinkedList collection.
• Listing 3 (p. 1318) . Beginning of the llIt method.
• Listing 4 (p. 1319) . Making the objects distinguishable.
• Listing 5 (p. 1320) . The showCollection method.
• Listing 6 (p. 1321) . Copy collection elements into an array.
• Listing 7 (p. 1321) . Display the array contents.
• Listing 8 (p. 1322) . The showArray method.
• Listing 9 (p. 1323) . Modifying the state of an object.
• Listing 10 (p. 1324) . Display the contents of the collection again.
307 http://docs.oracle.com/javase/tutorial/collections/index.html
308 http://docs.oracle.com/javase/tutorial/index.html
5.4.15.3 Preview
In earlier modules, I used the toArray method, declared in the Collection interface, to copy elements
from a collection into an array. However, in those modules, I didn't take the time to fully explain how to use
the method. Also, I didn't fully explain the precautions that you need to take when you use the method.
The Collection interface declares the following two overloaded versions of the toArray method:
note:
In this module, will teach you how to use the rst (simpler) version of the toArray method. I will also
show why you need to exercise care when using the elements stored in the array to avoid corrupting the state
of the objects referred to by the elements in the collection.
I will teach you how to use the second (more complex) version of the toArray method in the next
module.
5.4.15.4 Generics
The code in this series of modules is written with no thought given to Generics
309 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
309 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File ToArray01.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import javax.swing.*;
class Worker{
public void doIt(){
Collection ref;
System.out.print("null ");
}else{
System.out.print(((JComponent)array[i]).
1317
note:
Collection contents
B0 B1 L2 B3 B4 L5
New array contents
B0 B1 L2 B3 B4 L5
Modified array contents
XX B1 L2 B3 B4 L5
Collection contents
XX B1 L2 B3 B4 L5
If that was your answer, you probably already understand most of the material covered in this module. In
that case, you might consider skipping this module and moving on to the next module. If that wasn't your
answer, you should probably continue with your study of this module.
Collection ref;
ref = new LinkedList();
Populator.fillIt(ref);
System.out.println("Collection contents");
showCollection(ref);
"Linked list implementation of the List interface. Implements all optional list operations, and
permits all elements (including null). In addition ..."
As shown in Listing 3 (p. 1318) , the llIt method begins by calling the add method six times in
succession, passing references to new anonymous objects as a parameter to the add method.
note:
String getToolTipText()
• Both classes subclass the class named JComponent (a common superclass below the Object class).
• Both classes inherit a property (toolTipText) that can be used to identify them later.
while(iter.hasNext()){
refVar = (JComponent)iter.next();
if(refVar instanceof JButton){
refVar.setToolTipText("B"+cnt++);
}else{
refVar.setToolTipText("L" + cnt++);
}//end else
}//end while loop
}//end fillIt()
By now, you should have no diculty understanding the code in Listing 5 (p. 1320) . This code gets an
iterator on the incoming reference of type Collection . The code then uses that iterator to gain access
to each element in succession, displaying the String value of the toolTipText property belonging to a
particular object during each iteration.
note:
Collection contents
B0 B1 L2 B3 B4 L5
By examining the "B" and "L" characters in this output, you can identify the JButton objects and the
JLabel objects.
"Returns an array containing all of the elements in this collection. If the collection makes any
guarantees as to what order its elements are returned by its iterator, this method must return
the elements in the same order.
The returned array will be "safe" in that no references to it are maintained by this collection.
... The caller is thus free to modify the returned array."
I will have some more to say about the safe aspects of the array shortly.
note:
As you can see, (except for the String that identies the type of output) this is an exact match to the
output produced when the contents of the collection were displayed.
The toolTipText property value for each of the objects referred to by the remaining elements is left
undisturbed.
note:
As you can see, except for the rst element, this is a match for the display of the array contents before the
state of the object referred by the rst element was modied. However, the toolTipText property for the
object referred to by the rst element now contains the string "XX", instead of the string "B0" as before.
System.out.println("Collection contents");
showCollection(ref);
Figure 5.528: Listing 10. Display the contents of the collection again.
note:
Collection contents
XX B1 L2 B3 B4 L5
As you can see, the state of the object referred to by the reference stored in the rst element of the collection
is also changed. The toolTipText property for that object now contains the string "XX" instead of "B0"
as before.
5.4.15.7 Summary
In this module, I taught you how to use the simpler version of the overloaded toArray method, declared
in the Collection interface, to copy the elements from a collection into an array of type Object .
I also showed why you need to exercise care when using the elements stored in the array, to avoid
corrupting the state of the objects referred to by the elements in the collection.
5.4.15.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.4.16.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
in general and the Java Collections framework in particular.
This module shows you how to use the more-complex version of the toArray method declared in the
Collection interface. The module discusses issues regarding the type of the array and the types of the
objects referred to by the elements in the collection. The module also discusses issues regarding the relative
sizes of the array and the collection. Finally, the module rearms that you need to exercise caution when
using the elements stored in the array, to avoid corrupting the state of the objects referred to by the elements
in the collection.
In addition to studying these modules, I strongly recommend that you study the Collections Trail
311 in
Oracle's Java Tutorials
312 . The modules in this collection are intended to supplement and not to replace
those tutorials.
5.4.16.2.1.1 Listings
• Listing 1 (p. 1328) . The program named ToArray02.
• Listing 2 (p. 1329) . A populated array.
311 http://docs.oracle.com/javase/tutorial/collections/index.html
312 http://docs.oracle.com/javase/tutorial/index.html
5.4.16.3 Preview
The Collection interface declares the following two overloaded versions of the toArray method:
note:
In the previous module, I taught you how to use the rst (simpler) of the two methods. I also discussed
the need to exercise care when using the elements stored in the returned array to avoid corrupting the state
of the objects referred to by elements in the collection.
In this module, I will teach you how to use the second (more-complex) version of the toArray method
declared in the Collection interface. I will discuss issues regarding the type of the array and the types of
the objects referred to by the elements in the collection. I will also discuss issues regarding the relative sizes
of the array and the collection.
Finally, I will rearm that you need to exercise care when using the elements stored in the array, to
avoid corrupting the state of the objects referred to by the elements in the collection.
5.4.16.4 Generics
The code in this series of modules is written with no thought given to Generics
313 . As a result, if you copy
and compile the code, you will probably get warnings about unchecked or unsafe operations .
While you will ultimately need to understand how to use Generics, that is a very complex topic. An
understanding of Generics is beyond the scope of this course. Therefore, for purposes of this course, you can
simply ignore those warnings.
313 http://docs.oracle.com/javase/tutorial/java/generics/index.html
//File ToArray02.java
//Copyright 2001, R.G.Baldwin
import java.util.*;
import javax.swing.*;
class Worker{
public void doIt(){
Collection ref;
note:
If that was your answer, you probably already understand most of the material covered in this module. In
that case, you might consider skipping this module and moving on to some more productive activity. If that
wasn't your answer, you should probably continue with your study of this module.
for(int cnt=0;cnt<8;cnt++){
array[cnt] = new JButton();
array[cnt].setToolTipText("" + (cnt+10));
}//end for loop
System.out.println();
showArray(array,"Original array contents");
The JButton class, the JLabel class, and the setToolTipText method were discussed in detail
in the previous module, so I won't repeat that discussion here.
note:
As you can see, each of the eight elements in the array was initialized with an easily-recognizable and unique
value, ( which may be overwritten by the toArray method later).
Except for a couple of minor changes to the showCollection method, the code to create, populate,
and display the collection is the same as the code in the previous module.
}//end fillIt()
The llIt method begins by calling the add method six times in succession, passing references to new
anonymous objects (of types JButton and JLabel) as a parameter to the add method.
note:
String getToolTipText()
• Both classes subclass the class named JComponent (a common superclass below the Object class).
• Both classes inherit a property (toolTipText) that can be used to identify them later.
note:
Collection contents
B0 B1 L2 B3 B4 L5
Each term in the output is the String value of the toolTipText property for a particular object. Hence,
there are six terms in the output, one for each element in the collection.
array = (JComponent[])ref.toArray(array);
showArray(array,"New array contents");
The code in Listing 5 (p. 1332) also causes the contents of the array to be displayed after it receives the
elements from the collection.
The rst statement in Listing 5 (p. 1332) causes the rst seven elements in the array to be overwritten
with element values from the collection (plus one null value).
The second statement in Listing 5 (p. 1332) causes the contents of the array to be displayed.
"Returns an array containing all of the elements in this list in the correct order. The runtime
type of the returned array is that of the specied array. ... Throws: ArrayStoreException - if the
runtime type of (the specied array) is not a supertype of the runtime type of every element in
this list.
In other words, the type of the array passed as a parameter to the toArray method must be a superclass
of the classes from which all of the objects being managed by the collection were instantiated.
"If the list ts in the specied array, it is returned therein. Otherwise, a new array is allocated
with the runtime type of the specied array and the size of this list. If the list ts in the specied
array with room to spare (i.e., the array has more elements than the list), the element in the
array immediately following the end of the collection is set to null. This is useful in determining
the length of the list only if the caller knows that the list does not contain any null elements."
(Had my array been smaller than the number of elements in the collection, the toArray method
would have created and populated a new array of type JComponent and would have returned a
reference to that new array object. In that case, my array would have been used by the toArray
method only for the purpose of determining the runtime type of my array.)
"If this collection makes any guarantees as to what order its elements are returned by its iterator,
this method must return the elements in the same order."
Because the iterator for a LinkedList object returns the elements in increasing index order, the toArray
method, in this case, copies the element at each index position in the collection into the element at the same
index position in the array. Thus, reference values are copied from each element in the collection into the
rst six elements in the array.
note:
note:
[Ljavax.swing.JComponent;@49ba38
[Ljavax.swing.JComponent;@49ba38
In other words, the reference variable named array referred to the same array object before and after the
call to the toArray method.
note:
[Ljavax.swing.JComponent;@506411
[Ljavax.swing.JComponent;@21807c
In this case, the reference to the array object returned by the toArray method was dierent from the
reference that was passed to the toArray method. In other words, the returned reference referred to a
dierent array object than was referred to by the reference that was passed to the toArray method.
((JComponent)array[0]).setToolTipText("XX");
showArray(array,"Modified array contents");
showCollection(ref,"Collection contents");
The code in Listing 6 (p. 1336) also displays the contents of the array and the contents of the collection
after the modication is made.
The output produced by the code in Listing 6 (p. 1336) is shown below:
note:
5.4.16.7 Summary
In this module, I taught you how to use the more-complex version of the two overloaded versions of the
toArray method, declared in the Collection interface, to copy the elements from a collection into an
array of type JComponent .
I discussed issues regarding the type of the array and the type of the objects referred to by the elements in
the container. I also discussed issues regarding the size of the array as compared to the number of elements
in the collection.
Finally, I rearmed that you need to exercise care when using the elements stored in the array, to avoid
corrupting the state of the objects referred to by the elements in the collection.
5.4.16.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.5.1.1.6 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click on the input image le link(s) and use the capabilities of your browser to download and save the
image le(s).
2. Click on the Java solution source code link(s) and use the capabilities of your browser to download
and save the source code le(s).
3. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
4. Write, compile, and execute a simple Java program that will display each input image le in a
PictureExplorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
In addition to the hints listed above, I will precede the detailed specications for each program with a
discussion that contains hints about the concepts and skills that you will probably need to successfully write
the program.
In order to write this or any other Java program of substance, you will need to know how to use
317 the
Java Platform, Standard Edition API Specication
318 as well as the documentation for the Guzdial-Ericson
Multimedia Class Library
319 .
You may nd other useful hints in my online tutorials and slides for this course as well as in the YouTube
video lectures for this course.
317 http://cnx.org/content/m45117/latest/
318 http://docs.oracle.com/javase/7/docs/api/index.html
319 http://cnx.org/content/m44148/latest/#Discussion_and_sample_code
320 http://cnx.org/content/m44148/latest/
321 http://cnx.org/content/m44252/latest/Prob01.java
322 http://cnx.org/content/m44252/latest/Prob01.jpg
323 http://cnx.org/content/m44148/latest/
324 http://cnx.org/content/m44150/latest/#Listing_9
325 http://cnx.org/content/m44148/latest/#Listing_2
326 http://cnx.org/content/m44148/latest/#Figure_4
327 http://cnx.org/content/m44150/latest/#Listing_5
328 http://cnx.org/content/m44190/latest/
329 http://cnx.org/content/m44149/latest/
330 http://cnx.org/content/m44149/latest/#Listing_1
331 http://cnx.org/content/m44149/latest/#Listing_2
332 http://cnx.org/content/m44149/latest/#Listing_1
333 http://cnx.org/content/m44204/latest/
334 http://cnx.org/content/m44150/latest/
335 http://cnx.org/content/m44153/latest/
336 http://cnx.org/content/m44150/latest/#Listing_2
337 http://cnx.org/content/m44149/latest/#Listing_1
338 http://cnx.org/content/m44149/
339 http://cnx.org/content/m44153/latest/
340 http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
341 http://cnx.org/content/m44149/
342 http://cnx.org/content/m44149/latest/
343 http://cnx.org/content/m44149/latest/
344 http://cnx.org/content/m44149/latest/#Figure_4
345 http://cnx.org/content/m44149/latest/#Listing_2
346 http://cnx.org/content/m44193/latest/
347 http://cnx.org/content/m44149/latest/#Listing_4
348 http://cnx.org/content/m44149/latest/
349 http://cnx.org/content/m44206/latest/
350 http://cnx.org/content/m44149/latest/#Listing_5
351 http://cnx.org/content/m44149/latest/#Listing_6
352 http://cnx.org/content/m44149/latest/#Listing_7
Listing 5.1:
/*File Prob01 Copyright 2012 R.G.Baldwin
Write a program named Prob01 that uses the class denition shown below and Ericson's media
library along with the image le named Prob01.jpg
353 to produce the graphic output image shown
in Figure 1 (p. 1343) below.
Click Prob01.java
354 to download a Java source le containing the solution to this program.
In addition to the output image, your program must display your name and the other three
lines of text shown below on the command-line screen:
System.out.println(obj.getMars());
System.out.println(obj.getJoe());
System.out.println(obj.getSue());
}//end main
}//end class Prob01nd program specifications.
353 http://cnx.org/content/m44252/latest/Prob01.jpg
354 http://cnx.org/content/m44252/latest/Prob01.java
5.5.1.1.8.2 Program 2
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob02.java
355 . Some of these items are general in nature and some are specic to the use of
Ericson's multimedia library. I won't repeat the items listed under Program 1 (p. 1340) above. Instead, I
will concentrate on new concepts, knowledge, and skills not included in the above list.
355 http://cnx.org/content/m44252/latest/Prob02.java
356 http://cnx.org/content/m44252/latest/Prob02.jpg
357 http://cnx.org/content/m44203/latest/#Listing_2
• How to conrm the validity of your algorithm by numerically comparing the color values in your output
with the color values produced by compiling and running the program solution
366 given below.
358 http://cnx.org/content/m44203/latest/#Listing_2
359 http://cnx.org/content/m44203/latest/#Listing_3
360 http://cnx.org/content/m44203/latest/#Listing_4
361 http://cnx.org/content/m44203/latest/#Listing_4
362 http://cnx.org/content/m44203/latest/#Listing_4
363 http://cnx.org/content/m44203/latest/#Listing_4
364 http://cnx.org/content/m44252/latest/Prob02.jpg
365 http://cnx.org/content/m44203/latest/#Listing_5
366 http://cnx.org/content/m44252/latest/Prob02.java
367 http://cnx.org/content/m44252/latest/Prob02.jpg
368 http://cnx.org/content/m44252/latest/Prob02.java
5.5.1.1.8.3 Program 3
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this programand/or understand the given
solution in Prob03.java
369 . Some of these items are general in nature and some are specic to the use
369 http://cnx.org/content/m44252/latest/Prob03.java
of Ericson's multimedia library. I won't repeat the items listed above. Instead, I will concentrate on new
concepts, knowledge, and skills not included in the above lists.
There are at least two alternative ways to write a program that will satisfy these requirements.
Both alternatives
• How to design and implement an algorithm that will transform Prob03.jpg
370 into the required output
image shown in Figure 3 (p. 1347) .
Alternative 1
• How to create a new one-dimensional array object
371 of type Pixel[] and populate it with references
to all of the Pixel objects encapsulated in a Picture object.
• How to use some complicated indexing arithmetic
372 in conjunction with the one-dimensional array
mentioned above to apply the required algorithm.
Alternative 2
• How to use a nested loop structure
373 to achieve the same result.
• How to use a cast operator
374 .
*********************************************************/
public class Prob03{
//DO NOT MODIFY THE CODE IN THIS CLASS DEFINITION.
public static void main(String[] args){
Prob03Runner obj = new Prob03Runner();
obj.run();
System.out.println(obj.getPicture());
}//end main
}//end class Prob03
//End program specifications.
370 http://cnx.org/content/m44252/latest/Prob03.jpg
371 http://cnx.org/content/m44204/latest/#Listing_3
372 http://cnx.org/content/m44204/latest/#Listing_5
373 http://cnx.org/content/m44207/latest/#Listing_5
374 http://cnx.org/content/m44168/
375 http://cnx.org/content/m44252/latest/Prob03.jpg
376 http://cnx.org/content/m44252/latest/Prob03.java
5.5.1.1.8.4 Program 4
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this programand/or understand the given
solution in Prob04.java
377 . Some of these items are general in nature and some are specic to the use
377 http://cnx.org/content/m44252/latest/Prob04.java
of Ericson's multimedia library. I won't repeat the items listed above. Instead, I will concentrate on new
concepts, knowledge, and skills not included in the above lists.
378 http://cnx.org/content/m44252/latest/Prob04.jpg
379 http://cnx.org/content/m44195/latest/
380 http://cnx.org/content/m44195/latest/?collection=col11441/latest
381 http://cnx.org/content/m44252/latest/Prob04.jpg
382 http://cnx.org/content/m44252/latest/Prob04.java
5.5.1.1.8.5 Program 5
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob05.java
383 . Some of these items are general in nature and some are specic to the use
of Ericson's multimedia library. I won't repeat the items listed above. Instead, I will concentrate on new
concepts, knowledge, and skills not included in the above lists.
383 http://cnx.org/content/m44252/latest/Prob05.java
384 http://cnx.org/content/m44252/latest/Prob05a.jpg
385 http://cnx.org/content/m44252/latest/Prob05b.jpg
386 http://cnx.org/content/m44198/latest/#Listing_1
System.out.println(digitalPictures[0]);
digitalPictures[0].show();
System.out.println(digitalPictures[1]);
digitalPictures[1].show();
}//end main
}//end class Prob05
//End program specifications.
387 http://cnx.org/content/m44252/latest/Prob05a.jpg
388 http://cnx.org/content/m44252/latest/Prob05b.jpg
389 http://cnx.org/content/m44252/latest/Prob05.java
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.5.2.1.6 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click on the input image le link(s) and use the capabilities of your browser to download and save the
image le(s).
2. Click on the Java solution source code link(s) and use the capabilities of your browser to download
and save the source code le(s).
3. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
4. Write, compile, and execute a simple Java program that will display each input image le in a
PictureExplorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
In addition to the hints listed above, I will precede the detailed specications for each program with a
discussion that contains hints about the concepts and skills that you will probably need to successfully write
the program.
In order to write this or any other Java program of substance, you will need to know how to use
393 the
Java Platform, Standard Edition API Specication
394 as well as the documentation for the Guzdial-Ericson
Multimedia Class Library
395 .
You may nd other useful hints in my online tutorials and slides for this course as well as in the YouTube
video lectures for this course.
• How to design and implement an algorithm that will transform the original image
399 into the image
shown in Figure 1 (p. 1357) .
• How to instantiate an object and call a method on that object in a single statement
400 .
393 http://cnx.org/content/m45117/latest/
394 http://docs.oracle.com/javase/7/docs/api/index.html
395 http://cnx.org/content/m44148/latest/#Discussion_and_sample_code
396 http://cnx.org/content/m44148/latest/
397 http://cnx.org/content/m44254/latest/Prob01.java
398 http://cnx.org/content/m44252/latest/
399 http://cnx.org/content/m44254/latest/Prob01.jpg
400 http://cnx.org/content/m44207/latest/#Listing_1
401 http://cnx.org/content/m44207/latest/#Listing_3
402 http://cnx.org/content/m44207/latest/#Listing_3
403 http://cnx.org/content/m44207/latest/#Listing_5
404 http://cnx.org/content/m44207/latest/#Listing_4
405 http://cnx.org/content/m44207/latest/#Listing_7
406 http://cnx.org/content/m44254/latest/Prob01.jpg
407 http://cnx.org/content/m44254/latest/Prob01.java
5.5.2.1.8.2 Program 2
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob02.java
408 . Some of these items are general in nature and some are specic to the use of
Ericson's multimedia library. I won't repeat the items that were listed with the programs in Practice Group
1
409 or earlier programs in this practice group. Instead, I will concentrate on new concepts, knowledge, and
408 http://cnx.org/content/m44254/latest/Prob02.java
409 http://cnx.org/content/m44252/latest/
410 http://cnx.org/content/m44254/latest/Prob02a.jpg
411 http://cnx.org/content/m44254/latest/Prob02b.jpg
412 http://cnx.org/content/m44238/latest/#Listing_4
413 http://cnx.org/content/m44238/latest/#Listing_4
414 http://cnx.org/content/m44238/latest/#Listing_7
415 http://cnx.org/content/m44254/latest/Prob02a.jpg
416 http://cnx.org/content/m44254/latest/Prob02b.jpg
417 http://cnx.org/content/m44254/latest/Prob02.java
5.5.2.1.8.3 Program 3
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob03.java
418 . Some of these items are general in nature and some are specic to the use of
Ericson's multimedia library. I won't repeat the items that were listed with the programs in Practice Group
1
419 or earlier programs in this practice group. Instead, I will concentrate on new concepts, knowledge, and
418 http://cnx.org/content/m44254/latest/Prob03.java
419 http://cnx.org/content/m44252/latest/
420 http://cnx.org/content/m44254/latest/Prob03a.bmp
421 http://cnx.org/content/m44254/latest/Prob03b.bmp
422 http://cnx.org/content/m44254/latest/Prob03c.bmp
423 http://cnx.org/content/m44254/latest/Prob03d.jpg
424 http://cnx.org/content/m44210/latest/
425 http://cnx.org/content/m44210/latest/#Discussion_and_sample_code
426 http://cnx.org/content/m44210/latest/#Listing_4
427 http://cnx.org/content/m44254/latest/Prob03a.bmp
428 http://cnx.org/content/m44254/latest/Prob03b.bmp
429 http://cnx.org/content/m44254/latest/Prob03c.bmp
430 http://cnx.org/content/m44254/latest/Prob03d.jpg
431 http://cnx.org/content/m44254/latest/Prob03.java
5.5.2.1.8.4 Program 4
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob04.java
432 . Some of these items are general in nature and some are specic to the use of
Ericson's multimedia library. I won't repeat the items that were listed with the programs in Practice Group
432 http://cnx.org/content/m44254/latest/Prob04.java
1
433 or earlier programs in this practice group. Instead, I will concentrate on new concepts, knowledge, and
skills not included in previous lists.
433 http://cnx.org/content/m44252/latest/
434 http://cnx.org/content/m44254/latest/Prob04a.bmp
435 http://cnx.org/content/m44254/latest/Prob04b.bmp
436 http://cnx.org/content/m44254/latest/Prob04c.jpg
437 http://cnx.org/content/m44234/latest/#Listing_5
438 http://cnx.org/content/m44234/latest/
439 http://cnx.org/content/m44234/latest/#Listing_8
440 http://cnx.org/content/m44254/latest/Prob04a.bmp
441 http://cnx.org/content/m44254/latest/Prob04b.bmp
442 http://cnx.org/content/m44254/latest/Prob04c.jpg
443 http://cnx.org/content/m44254/latest/Prob04.java
5.5.2.1.8.5 Program 5
Discussion
The following is a non-exhaustive list of concepts that you need to understand along with knowledge
and skills that you need to possess in order to successfully write this program and/or understand the given
solution in Prob05.java
444 . Some of these items are general in nature and some are specic to the use of
Ericson's multimedia library. I won't repeat the items that were listed with the programs in Practice Group
1
445 or earlier programs in this practice group. Instead, I will concentrate on new concepts, knowledge, and
skills not included in previous lists.
444 http://cnx.org/content/m44254/latest/Prob05.java
445 http://cnx.org/content/m44252/latest/
446 http://cnx.org/content/m44254/latest/Prob05.jpg
*********************************************************/
public class Prob05{
//DO NOT MODIFY THE CODE IN THIS CLASS DEFINITION.
public static void main(String[] args){
MyPicture pic = new Prob05Runner().run();
System.out.println(pic);
pic.addMessage("String",10,50);
pic.show();
}//end main method
}//end class Prob05
//End program specifications.
447 http://cnx.org/content/m44177/latest/
448 http://cnx.org/content/m44254/latest/Prob05.jpg
449 http://cnx.org/content/m44254/latest/Prob05.java
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
5.5.3.1.6 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click on the input image le link(s) and use the capabilities of your browser to download and save the
image le(s).
2. Click on the Java solution source code link(s) and use the capabilities of your browser to download
and save the source code le(s).
3. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
4. Write, compile, and execute a simple Java program that will display each input image le in a
PictureExplorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
You may nd other useful hints in my online tutorials and slides for this course as well as in the YouTube
video lectures for this course.
5.5.3.1.8.2 Program 2
Listing 5.12: Write the Java application described below.
/*File Prob02 Copyright 2012 R.G.Baldwin
Write a program named Prob02 that uses the class denition shown below and Ericson's media
library along with the image le named Prob02.jpg
456 to produce the graphic output image shown
in Figure 2 (p. 1370) below.
Click Prob02.java
457 to download a Java source le containing the solution to this program.
In addition to the output image, your program must display your name and the other text
shown below on the command-line screen:
new Prob02Runner().run();
}//end main method
}//end class Prob02//End program specifications.
5.5.3.1.8.3 Program 3
Listing 5.13: Write the Java application described below.
/*File Prob03 Copyright 2012 R.G.Baldwin
Write a program named Prob03 that uses the class denition shown below and Ericson's media
library to produce the graphic output image shown in Figure 3 (p. 1372) below.
Click Prob03.java
458 to download a Java source le containing the solution to this program.
In addition to the output, your program must display your name and the other text shown
below on the command-line screen:
458 http://cnx.org/content/m44255/latest/Prob03.java
5.5.3.1.8.4 Program 4
Listing 5.14: Write the Java application described below.
/*File Prob04 Copyright 2012 R.G.Baldwin
Write a program named Prob04 that uses the class denition shown below and Ericson's media
library along with the image le named Prob04a.jpg
459 to produce the graphic output image shown
in Figure 4 (p. 1373) below.
Click Prob04.java
460 to download a Java source le containing the solution to this program.
In addition to the output image, your program must display your name and the other text
shown below on the command-line screen:
459 http://cnx.org/content/m44255/latest/Prob04a.jpg
460 http://cnx.org/content/m44255/latest/Prob04.java
5.5.3.1.8.5 Program 5
Listing 5.15: Write the Java application described below.
/*File Prob05 Copyright 2012 R.G.Baldwin
Write a program named Prob05 that uses the class denition shown below and Ericson's media
library along with the image les named Prob05a.jpg
461 and Prob05b.jpg 462 to produce the graphic
output image shown in Figure 5 (p. 1375) below.
Click Prob05.java
463 to download a Java source le containing the solution to this program.
In addition to the output images mentioned above, your program must display your name and
the other text shown below on the command-line screen:
461 http://cnx.org/content/m44255/latest/Prob05a.jpg
462 http://cnx.org/content/m44255/latest/Prob05b.jpg
463 http://cnx.org/content/m44255/latest/Prob05.java
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.1.1 Welcome
Welcome to the course material for ITSE2317 - Java Programming (Intermediate) , which I teach
at Austin Community College
2 in Austin, TX.
Ocial information about the course
The college website for this course is: http://www.austincc.edu/baldwin/
3
As of November 2012, the description for this course reads:
"ITSE 2317 - Java Programming (Intermediate)
Introduction to JAVA programming with object-orientation. Emphasis on the fundamental syntax and
semantics of JAVA for applications and web applets."
The prerequisite for the course is ITSE 2321
4 or department approval.
Downloads
I encourage you to take advantage of all of the download options that cnx.org has to oer in order to
customize this material for use in your organized courses or for personal self study.
And if you nd the material useful, I would like to hear more about how you are using it.
6.1.2 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
1377
1378 CHAPTER 6. ITSE2317 - JAVA PROGRAMMING (INTERMEDIATE)
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.2.1.2 Preface
This module is part of a collection of modules designed to teach you about Object-Oriented Programming
(OOP) using Java.
(Editor's note: As you will see when you read this module, the original version was written about
fourteen years ago. However, despite numerous improvements that have occurred in Java since then, most
of what was true on this topic in 1998 is still true in 2012. A wise man once said, "If it ain't broke, don't x
it."
One of the changes that you will see in subsequent modules is that the name of the package that contains
the Swing classes has been changed to javax.swing .)
6.2.1.3 Discussion
This module provides a very brief preview of some of what you can expect to nd in subsequent modules
regarding the Abstract Windows Toolkit ( AWT ) and the Swing component set.
The user interface of a modern computer program often involves techniques to activate many of the
human senses. We use icons, text boxes, images, sound, boardroom graphics, etc.
We weren't too concerned with these aspects of programming in the prerequisite course (ITSE 2321)
because there was a lot that you needed to learn to prepare yourself for understanding material of this sort.
That is about to change.
Much of the actual programming that you will do with Java will involve those aspects of the interface
that we commonly refer to as the Graphical User Interface (GUI) .
As of 5/10/98, there are two primary packages that are used for GUI programming under JDK 1.1.6:
1. java. awt .*
2. com.sun.java. swing .*
There are, of course, numerous other packages that are used in support of these two packages.
The AWT material was made available to Java programmers early in the life of Java. This was the
original material that was used to create graphical user interfaces. Major improvements to the AWT were
introduced with the release of JDK 1.1.
The Swing components became available in released form for use with JDK 1.1 around the beginning
of 1998. These components added signicantly to the ability of the programmer to create GUIs, both in
terms of functionality and cosmetics.
The capability and cosmetics of the AWT were very limited but Swing made GUI programming in
Java competitive in the real world. A Java programmer no longer need apologize for the quality of the GUIs
that she can create.
We expect that these two packages may become more integrated (causing changes in your import
directives) with the release of JDK 1.2, (probably sometime in 1998) but hopefully the concepts involved
won't be greatly dierent.
As of 3/5/97, there were more than fty classes dened in package java.awt . We will discuss some of
the more important AWT classes in subsequent modules.
As of 5/10/98, the com.sun.java.swing package contains more than 75 classes and about 20 interfaces.
You might expect, therefore, that learning to use this material eectively won't be a trivial task.
It is very important to understand that Swing is an extension of, and not a replacement for the AWT
(for example a
. While it is true that there is some overlap Swing JButton component might be
viewed as an improved functional replacement for an AWT Button component, and once you begin
using Swing buttons you may choose to never again use an AWT button) , the basic functionality
of Swing is built upon the functionality of the AWT .
Therefore, as students, we cannot simply skip over an understanding of the AWT and move on to
Swing . The AWT is the foundation for Swing .
We must rst understand the AWT and then understand how Swing extends and improves on the
AWT . I will attempt to integrate an understanding of both the AWT and Swing in the remaining
modules in this collection.
We will begin by introducing you to a few simple components of each type and use these components to
teach you about such topics as event-driven programming, layout, graphics, etc. Then, time permitting, we
will dig a little deeper into the more complex aspects of both the AWT and Swing components and
other features.
What I won't do is show you a lot of pictures of various AWT and Swing components as is the
case with many books and other tutorials (although such pictures can be important for an appreciation of
GUI programming) . (Have you noticed how many Java books use copies of the JavaSoft documentation
as ller material to make the book appear to contain more information than it actually contains? At least
half of many of the books currently in print is nothing more than a reproduction of the documentation that
you can download for free from JavaSoft. Oh well, enough of that!)
If you want to see some pictures of AWT and Swing components (which would be only natural) ,
you can create them yourself on your own computer screen.
For examples of the AWT components, simply look in the folders in the software that you downloaded
from JavaSoft. When you install JDK 1.1.6, a folder named "demo" will be created that contains about
two-dozen sample programs. Many of these sample programs have graphical user interfaces that make use
of the AWT . Just run the programs to see examples of the use of the AWT .
When you download and install Swing 1.0.1, a folder named "examples" will be created. This folder
contains about nine folders, each of which contains a demonstration application or applet that makes use of
Swing . You can run these programs to see the examples on your computer screen.
A particularly interesting demonstration application is the one named SwingSet . One of the new
components in Swing is a tabbed pane that looks much like a common cardboard le folder with a labeled
tab on the top, bottom, left, or right. The AWT doesn't contain such a component.
This demonstration starts with about twenty such tabbed panes on the screen, each one of which demon-
strates one aspect of the use of Swing . By clicking on each of the labeled tabs, you can select and exercise
one aspect of Swing . In addition, there are ve menus that contain selections, some of which impact the
behavior of some aspect of the demonstration.
While you are there, pay attention to the fact that virtually all of the Swing components are also
containers, so it is possible to cause other items (such as images) to be contained in components such as
buttons and menus.
Take a look at the pane labeled RadioButtons and see how two dierent images of JavaSoft's little
creature named Duke can be made to function as a radio button. In this case, the selected Duke is waving
while the unselected Dukes aren't waving.
Duke shows up again under ToggleButtons where the button which has been toggled has Duke animated
in a child's swing.
The Checkboxes pane uses light bulbs that either are or are not illuminated to illustrate selection of
Checkbox items.
The examples on the Slider pane are truly impressive (the AWT doesn't have a slider component,
although it is possible to use a ScrollBar as a crude slider) .
Take a look at the ListBox pane to see another example of using images inside of a component.
The DebugGraphics pane demonstrates how to run your program in slow motion so that you can see
how the components are assembled for debugging purposes. Note that a Slider is used to control the speed
of assembly of the components.
And of course, every where you turn in this demo, you will see tool tips that are not a part of the
AWT . For a little comic relief, take a look at the ToolTips pane.
Don't forget to pull down the Options menu and select the "look and feel" of the dierent panes as you
view them.
Actually, words are inadequate to describe what you are going to nd when you install and run the
SwingSet demonstration. To use a corny phrase made famous by an old TV commercial (which many of
you are probably too young to remember) , "Try it, you'll like it."
6.2.1.5 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.2.2.2 Preface
This module is one in a series of three modules designed to teach you about callbacks in Object-Oriented
Programming (OOP) using Java. The other two modules are titled Callbacks - II and Callbacks - III. If
interested, you will nd those modules at http://www.dickbaldwin.com/toc.htm
7 .
6.2.2.2.1.1 Figures
• Figure 1 (p. 1390) . Documentation for the removeElement method.
• Figure 2 (p. 1394) . Output from Callback02.
6.2.2.2.1.2 Listings
• Listing 1 (p. 1383) . Dene the CallBack interface.
• Listing 2 (p. 1384) . Dene the Teacher class.
• Listing 3 (p. 1385) . Dene the Student class.
• Listing 4 (p. 1385) . A controlling class named Callback01.
• Listing 5 (p. 1386) . Complete listing of program named Callback01.
6.2.2.3 Preview
Many processes in the standard Java API make use of a mechanism that might be referred to as a callback
mechanism. Basically, this is a mechanism where a method in one object asks a method in another object
to "call me back" or "notify me" when an interesting event happens.
An interesting event
For example, an interesting event might be that the price of a specied stock goes above its previous high
value, or the toaster nishes toasting the bread.
Multicasting
In fact, many dierent objects may ask one object to notify them when the interesting event happens.
This is sometimes referred to as multicasting . (The one-to-one case is often referred to as unicasting.)
Going further, many dierent objects may ask one object to notify them when any interesting event in
a family of interesting events happens, and to identify the specic event that actually happened along with
the notication.
Many examples
For example, we see dierent forms of callback activity in conjunction with
You can nd examples of all of these in the pages of my online tutorial lessons.
Callback implementation
Callback capabilities are often implemented in other languages by passing a function pointer to another
function. The receiving function uses the passed function pointer to call another function when an interesting
event happens. However, Java doesn't support function pointers. In this module, we will learn how to
implement the callback mechanism using interfaces instead.
From the simple to the more complex
As usual, our approach will be to learn the material by reviewing programs that progress from very
simple to more complex. As mentioned earlier, this topic consumes all of this module and two additional
lessons on my website as well.
Meaningful scenarios
It is usually easier to understand abstract concepts if they are explained in terms of meaningful scenarios.
In this case, our scenario will consist of a teacher and some students . In the beginning there will only be
one student. Ultimately there will be many students and there will also be some animals in the classroom
as well.
Registration
The students (and the animals) register themselves on the teachers roll book to be notied of interesting
events. Initially the interesting event will simply be the teacher taking the roll. Ultimately the interesting
event will be notication that it is either time for recess, or it is time for lunch.
Unicast and multicast scenarios
Initially, only one student receives notication of the one type of event. Ultimately, all of the students
and all of the animals receive notication of both types of event (recess or lunch) but some of those who
are notied choose to ignore the notication.
We will refer to the case where only one student is on the list as the unicast program. We will refer to
the case where many students (and possibly animals as well) are on the list as the multicast program.
This terminology was selected because it matches the terminology used in the JDK 1.1 documentation for
the Delegation Event Model.
Without further discussion, let's look at some code.
• create and maintain a list of (only) one object of the interface type (multiple objects come later) ,
and
• to notify that object that something interesting has happened by calling its callBack method.
(As mentioned earlier, the size of the list was constrained to only one object in order to emphasize call-
back structure and avoid getting bogged down in list processing. A subsequent version will implement list
processing.)
A Student class
The program denes a class named Student that implements the CallBack interface. Objects of
the Student class can be registered on the list maintained by an object of the Teacher class, and
can be notied Teacher class whenever something interesting happens. Notication
by the object of the
takes the form of calling the callBack method on the object.
The method named callBack
The body of the callBack method can be designed to do anything, but in this case, to keep things
simple, it just announces that it has been called.
The controlling class
Finally, the program denes a controlling class named Callback01 that ties all the pieces together and
exercises them.
The program was originally tested using JDK 1.1.3 under Win95 and more recently tested using JDK
1.7 under Windows Vista.
The output from the program is shown in the complete program listing in a later section.
Interesting unicast code fragments
Listing 1 (p. 1383) denes an interface named CallBack that creates a new type and declares a generic
method named callBack that can be used to execute a callback on any object that is instantiated from a
class that implements the interface.
interface CallBack{
public void callBack();
}//end interface CallBack
class Teacher{
CallBack obj; //list of objects of type CallBack
//-----------------------------------------------------//
As we saw above, an object of the Teacher class will call the callBack method on all objects on its
list when the interesting event occurs. It is important to note that the callback mechanism is to call this
method.
The Student class is dened in Listing 3 (p. 1385) .
Student(String name){//constructor
this.name = name; //save the name to identify the obj
}//end constructor
//-----------------------------------------------------//
This is not too complicated once you break the process into its component parts.
The class named Callback01 is dened in Listing 4 (p. 1385) .
class Callback01{
public static void main(String[] args){
//Instantiate Teacher object
Teacher missJones = new Teacher();
//Instantiate and register a Student object with the
// Teacher object
missJones.register(new Student("Joe"));
//Cause the Teacher object to do a callBack on the
// Student object.
missJones.callTheRoll();
}//end main()
}//end class Callback01
There you have it. This simple program contains the sum and substance of one approach to callbacks in
Java.
It is critical to note that the objects registered on the list are of the interface type CallBack . This
guarantees that there cannot be an object on the list that does not have an instance method named callBack
.
Unicast Program Listing
A complete listing of the program is provided in Listing 5 (p. 1386) so that you can view the code
fragments in context.
Joe here.
**********************************************************/
//First we define an interface that will create a new type
// and declare a generic method that can be used to
// callback any object that is of a class that implements
// the interface.
interface CallBack{
public void callBack();
}//end interface CallBack
//=======================================================//
class Teacher{
CallBack obj; //list of objects of type CallBack
//-----------------------------------------------------//
Student(String name){//constructor
this.name = name; //save the name to identify the obj
}//end constructor
//-----------------------------------------------------//
The program was originally tested using JDK 1.1.3 under Win95 and more recently tested using JDK
1.7 under Windows Vista.
The output from the program is shown following a discussion of the controlling class at the end of the
next section.
Interesting multicast code fragments
Listing 6 (p. 1389) denes an interface that creates a new type and declares a generic method that can
be used to call back any object that is of a class that implements the interface. There is nothing new here.
interface CallBack{
public void callBack();
}//end interface CallBack
class Teacher{
Vector objList; //list of objects of type CallBack
//----------------------------------------------//
Teacher(){//constructor
objList = new Vector();
}//end constructor
This method removes the first occurrence of the argument from this
vector. Indices beyond that point are adjusted appropriately
void callTheRoll(){
Vector tempList;//save a temporary copy of list here
synchronized(this){
tempList = (Vector)objList.clone();
}//end synchronized block
Dog(String name){//constructor
this.name = name; //save the name to identify the obj
}//end constructor
//-----------------------------------------------------//
class Callback02{
public static void main(String[] args){
//Instantiate Teacher object
Teacher missJones = new Teacher();
System.out.println("Remove Peg");
missJones.unRegister(peg);
System.out.println();//blank line
Register Tom
Student@1cc73e added
Register Spot
Dog@1cc74e added
Register Sue
Student@1cc741 added
Register Fido
Dog@1cc751 added
Register Peg
Student@1cc744 added
Register Bob
Student@1cc747 added
Register Brownie
Dog@1cc754 added
Remove Peg
Student@1cc744 removed
Try to remove Joe
Student@1cc74a not in the list
Tom here
Woof, Woof Spot
Sue here
Woof, Woof Fido
Bob here
Woof, Woof Brownie
Note that the attempt to remove Joe from the list was not successful because he was never registered in
the rst place.
Finally, you see the output produced by calling callTheRoll which in turn calls the callBack method
on each of the objects on the list.
Note that Peg didn't appear in the roll call because she was rst added and then removed from the list
before the roll call was taken.
The sum and substance
So there you have it, the sum and substance of multicast callbacks in Java. Obviously improvements
could be made. You can see a couple of them in the remaining two tutorial lessons on callbacks that are
published on my website.
Multicast Program Listing
A complete listing of the multicast program named Callback02 is provided in Listing 13 (p. 1395) .
Register Tom
Student@1cc73e added
Register Spot
Dog@1cc74e added
Register Sue
Student@1cc741 added
Register Fido
Dog@1cc751 added
Register Peg
Student@1cc744 added
Register Bob
Student@1cc747 added
Register Brownie
Dog@1cc754 added
Remove Peg
Student@1cc744 removed
Try to remove Joe
Student@1cc74a not in the list
Tom here
Woof, Woof Spot
Sue here
Woof, Woof Fido
Bob here
Woof, Woof Brownie
class Teacher{
Vector objList; //list of objects of type CallBack
//-----------------------------------------------------//
Teacher(){//constructor
//Instantiate a Vector object to contain the list
// of registered objects.
objList = new Vector();
}//end constructor
//-----------------------------------------------------//
Student(String name){//constructor
this.name = name; //save the name to identify the obj
}//end constructor
//-----------------------------------------------------//
//=======================================================//
Dog(String name){//constructor
this.name = name; //save the name to identify the obj
}//end constructor
//-----------------------------------------------------//
missJones.register(tom);
System.out.println("Register Spot");
missJones.register(spot);
System.out.println("Register Sue");
missJones.register(sue);
System.out.println("Register Fido");
missJones.register(fido);
System.out.println("Register Peg");
missJones.register(peg);
System.out.println("Register Bob");
missJones.register(bob);
System.out.println("Register Brownie");
missJones.register(brownie);
System.out.println();//blank line
6.2.2.6 Summary
In this module, you learned the fundamentals of callbacks using interfaces in Java.
6.2.2.8 Miscellaneous
This section contains a variety of miscellaneous information.
8 http://cnx.org/content/m44333/latest/../../Part%201/Java3102/Java3102.htm#Listing_5
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.2.3 Java OOP: Event Handling in JDK 1.1, A First Look, Delegation Event
Model9
This is a placeholder for the CNXML version of this module, which is incomplete.
You will nd a copy of the original HTML version at
http://www.austincc.edu/baldwin/ITSE2317LectureNotesAndSlides/LectureNotes/Java080/Java080.htm
10
-end-
6.3 Multimedia
6.3.1 Part 1
6.3.1.1 Java OOP: Modifying the World and SimpleTurtle Classes19
6.3.1.1.1 Table of Contents
• Preface (p. 1401)
6.3.1.1.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
20 .
6.3.1.1.2.1.1 Figures
• Figure 1 (p. 1403) . The required graphic output image.
• Figure 2 (p. 1404) . Required output on the command line screen.
6.3.1.1.2.1.2 Listings
• Listing 1 (p. 1405) . Modication to load a jpg le by default.
• Listing 2 (p. 1405) . Original array containing turtle colors.
• Listing 3 (p. 1406) . Modied array of turtle colors.
• Listing 4 (p. 1406) . Change the initial heading.
• Listing 5 (p. 1407) . Source code for driver class named Prob01..
• Listing 6 (p. 1408) . Source code for the modied World class..
• Listing 7 (p. 1413) . Source code for the modied SimpleTurtle class..
6.3.1.1.3 Preview
Program specications
Write a program named Prob01 that uses the class denition shown in Listing 5 (p. 1407) and Ericson's
media library along with the image le named Prob01.jpg to produce the graphic output image shown
in Figure 1 (p. 1403) .
No new classes
You may not dene any new classes to cause your program to behave as required, and you may not
modify the class denition for the class named Prob01 given in Listing 5 (p. 1407) . You must copy and
modify (if necessary) the following media classes to cause your program to produce the required output:
• World.java
• Turtle.java
• SimpleTurtle.java
• Prob01.class
• Prob01.java
• Prob01.jpg
• SimpleTurtle.class
• SimpleTurtle.java
• Turtle.class
• Turtle.java
• World.class
• World.java
Output text
In addition to the output image described above, your program must produce the output text on the
command- line screen shown in Figure 2 (p. 1404) .
Dick Baldwin
Picture, filename Prob01.jpg height 274 width 365
Dick Baldwin
Dick Baldwin
Dick Baldwin
Dick Baldwin
You must substitute your name for mine wherever my name appears in the image and on the command-
line screen.
An analysis
As is often the case, the real challenge with this problem is to decide what needs to be done to satisfy
the specications.
Required modications
By comparing the default behavior of the World and SimpleTurtle classes with the requirements
of this program, it can be determined that the following modications to the World and SimpleTurtle
classes are required to meet the specications. (Modication of the Turtle class is not required) :
• Modify the World class to load a picture named Prob01.jpg as the default background for the
world in place of the all-white Picture object.
• Modify the World class to display the student's name near the top of the image.
• Modify the World class to display the student's name and information about the picture on the
command-line screen.
• Modify the SimpleTurtle class to change the initial heading for new turtle objects to northeast
instead of north.
• Modify the SimpleTurtle class to change the order in which colors are assigned to new turtles as
they are instantiated.
A complete listing of the modied World class is shown in Listing 6 (p. 1408) .
Modifying the code
The code used to accomplish the modications described above is shown in Listing 1 (p. 1405) .
Note that one original statement was disabled and replaced by three new statements.
In addition, several other println statements were added at strategic locations within the World and
SimpleTurtle classes (not shown here) to cause the student's name to appear multiple times in the text
output shown in Figure 2 (p. 1404) .
Meeting the requirements
World
These modications to the and SimpleTurtle classes met the following requirements estab-
lished earlier under Analysis
21 .
• Modify the World class to load a picture named Prob01.jpg as the default background for the
world in place of the all-white Picture object.
• Modify the World class to display the student's name near the top of the image.
• Modify the World class to display the student's name and information about the picture on the
command-line screen.
Listing 3 (p. 1406) declares and initializes a modied version of the array of color data that is used to assign
colors to the turtles as they are instantiated.
• Modify the SimpleTurtle class to change the order in which colors are assigned to new turtles as
they are instantiated.
The default direction in the original version of the class is due north or zero degrees. The modied default
direction is northeast or 45 degrees.
Meeting the requirements
This modication to theSimpleTurtle class accomplished the following requirement established earlier
under Analysis
23 .
• Modify the SimpleTurtle class to change the initial heading for new turtle objects to northeast
instead of north.
That completes the required modications that were established under Analysis
24 .
22 http://cnx.org/content/m44330/latest/Lecture01.htm#Analysis
23 http://cnx.org/content/m44330/latest/Lecture01.htm#Analysis
24 http://cnx.org/content/m44330/latest/Lecture01.htm#Analysis
6.3.1.1.6 Summary
You learned how to make simple modication to the World and SimpleTurtle classes that modify how
a program that uses Ericson's library behaves.
6.3.1.1.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
25 http://cnx.org/content/m44330/latest/Prob01.jpg
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observer;
import java.awt.*;
/**
* Class to represent a 2d world that can hold turtles and
* display them
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class World extends JComponent implements ModelDisplay
{
////////////////// fields ///////////////////////
/**
* Constructor that takes no arguments
*/
public World()
{
// set up the world and make it visible
initWorld(true);
}
/**
* Constructor that takes a boolean to
* say if this world should be visible
* or not
* @param visibleFlag if true will be visible
* else if false will not be visible
*/
public World(boolean visibleFlag)
{
initWorld(visibleFlag);
}
/**
* Constructor that takes a width and height for this
* world
* @param w the width for the world
* @param h the height for the world
*/
public World(int w, int h)
{
width = w;
height = h;
System.out.println("Dick Baldwin");
// set up the world and make it visible
initWorld(true);
}
/**
* Method to initialize the world
* @param visibleFlag the flag to make the world
* visible or not
*/
private void initWorld(boolean visibleFlag)
{
// set the preferred size
this.setPreferredSize(new Dimension(width,height));
/**
* Method to get the graphics context for drawing on
* @return the graphics context of the background picture
*/
public Graphics getGraphics() { return picture.getGraphics(); }
/**
* Method to clear the background picture
*/
public void clearBackground() { picture = new Picture(width,height); }
/**
* Method to get the background picture
* @return the background picture
*/
public Picture getPicture() { return picture; }
/**
* Method to set the background picture
* @param pict the background picture to use
*/
public void setPicture(Picture pict) { picture = pict; }
/**
/**
* Metod to get the last turtle in this world
* @return the last turtle added to this world
*/
public Turtle getLastTurtle()
{
return (Turtle) turtleList.get(turtleList.size() - 1);
}
/**
* Method to add a model to this model displayer
* @param model the model object to add
*/
public void addModel(Object model)
{
turtleList.add((Turtle) model);
if (autoRepaint)
repaint();
}
/**
* Method to check if this world contains the passed
* turtle
* @return true if there else false
*/
public boolean containsTurtle(Turtle turtle)
{
return (turtleList.contains(turtle));
}
/**
/**
* Method to get the width in pixels
* @return the width in pixels
*/
public int getWidth() { return width; }
/**
* Method to get the height in pixels
* @return the height in pixels
*/
public int getHeight() { return height; }
/**
* Method that allows the model to notify the display
*/
public void modelChanged()
{
if (autoRepaint)
repaint();
}
/**
* Method to set the automatically repaint flag
* @param value if true will auto repaint
*/
public void setAutoRepaint(boolean value) { autoRepaint = value; }
/**
* Method to hide the frame
*/
// public void hide()
// {
// frame.setVisible(false);
// }
/**
* Method to show the frame
*/
// public void show()
// {
// frame.setVisible(true);
// }
/**
* Method to set the visibility of the world
* @param value a boolean value to say if should show or hide
*/
public void setVisible(boolean value)
{
frame.setVisible(value);
}
/**
* Method to get the list of turtles in the world
* @return a list of turtles in the world
*/
public List getTurtleList()
{ return turtleList;}
/**
* Method to get an iterator on the list of turtles
* @return an iterator for the list of turtles
*/
public Iterator getTurtleIterator()
{ return turtleList.iterator();}
/**
* Method that returns information about this world
* in the form of a string
* @return a string of information about this world
*/
public String toString()
{
return "A " + getWidth() + " by " + getHeight() +
" world with " + turtleList.size() + " turtles in it.";
}
import javax.swing.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.util.Observer;
import java.util.Random;
/**
/**
* Constructor that takes the x and y position for the
* turtle
* @param x the x pos
* @param y the y pos
*/
public SimpleTurtle(int x, int y)
{
xPos = x;
yPos = y;
bodyColor = colorArray[numTurtles % colorArray.length];
setPenColor(bodyColor);
numTurtles++;
}
/**
* Constructor that takes the x and y position and the
* model displayer
* @param x the x pos
* @param y the y pos
* @param display the model display
*/
public SimpleTurtle(int x, int y, ModelDisplay display)
{
this(x,y); // invoke constructor that takes x and y
modelDisplay = display;
display.addModel(this);
}
/**
/**
* Constructor that takes the x and y position and the
* picture to draw on
* @param x the x pos
* @param y the y pos
* @param picture the picture to draw on
*/
public SimpleTurtle(int x, int y, Picture picture)
{
this(x,y); // invoke constructor that takes x and y
this.picture = picture;
this.visible = false; // default is not to see the turtle
}
/**
* Constructor that takes the
* picture to draw on and will appear in the middle
* @param picture the picture to draw on
*/
public SimpleTurtle(Picture picture)
{
// invoke constructor that takes x and y
this((int) (picture.getWidth() / 2),
(int) (picture.getHeight() / 2));
this.picture = picture;
this.visible = false; // default is not to see the turtle
}
/**
* Get the distance from the passed x and y location
* @param x the x location
* @param y the y location
*/
public double getDistance(int x, int y)
{
/**
* Method to turn to face another simple turtle
*/
public void turnToFace(SimpleTurtle turtle)
{
turnToFace(turtle.xPos,turtle.yPos);
}
/**
* Method to turn towards the given x and y
* @param x the x to turn towards
* @param y the y to turn towards
*/
public void turnToFace(int x, int y)
{
double dx = x - this.xPos;
double dy = y - this.yPos;
double arcTan = 0.0;
double angle = 0.0;
// avoid a divide by 0
if (dx == 0)
{
// if below the current turtle
if (dy > 0)
heading = 180;
/**
/**
* Method to set the picture for this simple turtle
* @param pict the picture to use
*/
public void setPicture(Picture pict) { this.picture = pict; }
/**
* Method to get the model display for this simple turtle
* @return the model display if there is one else null
*/
public ModelDisplay getModelDisplay() { return this.modelDisplay; }
/**
* Method to set the model display for this simple turtle
* @param theModelDisplay the model display to use
*/
public void setModelDisplay(ModelDisplay theModelDisplay)
{ this.modelDisplay = theModelDisplay; }
/**
* Method to get value of show info
* @return true if should show info, else false
*/
public boolean getShowInfo() { return this.showInfo; }
/**
* Method to show the turtle information string
* @param value the value to set showInfo to
*/
public void setShowInfo(boolean value) { this.showInfo = value; }
/**
* Method to get the shell color
* @return the shell color
*/
public Color getShellColor()
{
Color color = null;
if (this.shellColor == null && this.bodyColor != null)
color = bodyColor.darker();
else color = this.shellColor;
return color;
}
/**
* Method to set the shell color
/**
* Method to get the body color
* @return the body color
*/
public Color getBodyColor() { return this.bodyColor; }
/**
* Method to set the body color which
* will also set the pen color
* @param color the color to use
*/
public void setBodyColor(Color color)
{
this.bodyColor = color;
setPenColor(this.bodyColor);
}
/**
* Method to set the color of the turtle.
* This will set the body color
* @param color the color to use
*/
public void setColor(Color color) { this.setBodyColor(color); }
/**
* Method to get the information color
* @return the color of the information string
*/
public Color getInfoColor() { return this.infoColor; }
/**
* Method to set the information color
* @param color the new color to use
*/
public void setInfoColor(Color color) { this.infoColor = color; }
/**
* Method to return the width of this object
* @return the width in pixels
*/
public int getWidth() { return this.width; }
/**
* Method to return the height of this object
* @return the height in pixels
*/
public int getHeight() { return this.height; }
/**
* Method to set the width of this object
* @param theWidth in width in pixels
*/
public void setWidth(int theWidth) { this.width = theWidth; }
/**
* Method to set the height of this object
* @param theHeight the height in pixels
*/
public void setHeight(int theHeight) { this.height = theHeight; }
/**
* Method to get the current x position
* @return the x position (in pixels)
*/
public int getXPos() { return this.xPos; }
/**
* Method to get the current y position
* @return the y position (in pixels)
*/
public int getYPos() { return this.yPos; }
/**
* Method to get the pen
* @return the pen
*/
public Pen getPen() { return this.pen; }
/**
* Method to set the pen
* @param thePen the new pen to use
*/
public void setPen(Pen thePen) { this.pen = thePen; }
/**
* Method to check if the pen is down
* @return true if down else false
*/
public boolean isPenDown() { return this.pen.isPenDown(); }
/**
* Method to set the pen down boolean variable
* @param value the value to set it to
*/
public void setPenDown(boolean value) { this.pen.setPenDown(value); }
/**
* Method to lift the pen up
*/
public void penUp() { this.pen.setPenDown(false);}
/**
* Method to set the pen down
*/
public void penDown() { this.pen.setPenDown(true);}
/**
* Method to get the pen color
* @return the pen color
*/
public Color getPenColor() { return this.pen.getColor(); }
/**
* Method to set the pen color
* @param color the color for the pen ink
*/
public void setPenColor(Color color) { this.pen.setColor(color); }
/**
* Method to set the pen width
* @param width the width to use in pixels
*/
public void setPenWidth(int width) { this.pen.setWidth(width); }
/**
* Method to get the pen width
* @return the width of the pen in pixels
*/
public int getPenWidth() { return this.pen.getWidth(); }
/**
* Method to clear the path (history of
* where the turtle has been)
*/
public void clearPath()
{
this.pen.clearPath();
}
/**
* Method to get the current heading
* @return the heading in degrees
*/
public double getHeading() { return this.heading; }
/**
* Method to set the heading
* @param heading the new heading to use
*/
/**
* Method to get the name of the turtle
* @return the name of this turtle
*/
public String getName() { return this.name; }
/**
* Method to set the name of the turtle
* @param theName the new name to use
*/
public void setName(String theName)
{
this.name = theName;
}
/**
* Method to get the value of the visible flag
* @return true if visible else false
*/
public boolean isVisible() { return this.visible;}
/**
* Method to hide the turtle (stop showing it)
* This doesn't affect the pen status
*/
public void hide() { this.setVisible(false); }
/**
* Method to show the turtle (doesn't affect
* the pen status
*/
public void show() { this.setVisible(true); }
/**
* Method to set the visible flag
* @param value the value to set it to
*/
public void setVisible(boolean value)
{
// if the turtle wasn't visible and now is
if (visible == false && value == true)
{
// update the display
this.updateDisplay();
}
/**
* Method to update the display of this turtle and
* also check that the turtle is in the bounds
*/
public synchronized void updateDisplay()
{
// check that x and y are at least 0
if (xPos < 0)
xPos = 0;
if (yPos < 0)
yPos = 0;
// if picture
if (picture != null)
{
if (xPos >= picture.getWidth())
xPos = picture.getWidth() - 1;
if (yPos >= picture.getHeight())
yPos = picture.getHeight() - 1;
Graphics g = picture.getGraphics();
paintComponent(g);
}
else if (modelDisplay != null)
{
if (xPos >= modelDisplay.getWidth())
xPos = modelDisplay.getWidth() - 1;
if (yPos >= modelDisplay.getHeight())
yPos = modelDisplay.getHeight() - 1;
modelDisplay.modelChanged();
}
}
/**
* Method to move the turtle foward 100 pixels
*/
public void forward() { forward(100); }
/**
* Method to move the turtle forward the given number of pixels
* @param pixels the number of pixels to walk forward in the heading direction
*/
public void forward(int pixels)
{
int oldX = xPos;
int oldY = yPos;
// add a move from the old position to the new position to the pen
pen.addMove(oldX,oldY,xPos,yPos);
/**
* Method to go backward by 100 pixels
*/
public void backward()
{
backward(100);
}
/**
* Method to go backward a given number of pixels
* @param pixels the number of pixels to walk backward
*/
public void backward(int pixels)
{
forward(-pixels);
}
/**
* Method to move to turtle to the given x and y location
* @param x the x value to move to
* @param y the y value to move to
*/
public void moveTo(int x, int y)
{
this.pen.addMove(xPos,yPos,x,y);
this.xPos = x;
this.yPos = y;
this.updateDisplay();
}
/**
* Method to turn left
*/
public void turnLeft()
{
this.turn(-90);
}
/**
* Method to turn right
*/
/**
* Method to turn the turtle the passed degrees
* use negative to turn left and pos to turn right
* @param degrees the amount to turn in degrees
*/
public void turn(int degrees)
{
this.heading = (heading + degrees) % 360;
this.updateDisplay();
}
/**
* Method to draw a passed picture at the current turtle
* location and rotation in a picture or model display
* @param dropPicture the picture to drop
*/
public synchronized void drop(Picture dropPicture)
{
Graphics2D g2 = null;
// if g2 isn't null
if (g2 != null)
{
/**
* Method to paint the turtle
* @param g the graphics context to paint on
*/
public synchronized void paintComponent(Graphics g)
{
// cast to 2d object
Graphics2D g2 = (Graphics2D) g;
if (showInfo)
drawInfoString(g2);
/**
* Method to draw the information string
* @param g the graphics context
*/
public synchronized void drawInfoString(Graphics g)
{
g.setColor(infoColor);
g.drawString(this.toString(),xPos + (int) (width/2),yPos);
}
/**
* Method to return a string with informaiton
* about this turtle
* @return a string with information about this object
*/
public String toString()
{
return this.name + " turtle at " + this.xPos + ", " +
this.yPos + " heading " + this.heading + ".";
}
} // end of class
zz
zz
zz
zz
zz
TemplateForATable
PutTableDataHere
Table 6.1
zz
zz
-end-
6.3.1.2.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
27 .
6.3.1.2.2.1.1 Figures
• Figure 1 (p. 1429) . Required screen output.
• Figure 2 (p. 1430) . Required text output.
6.3.1.2.2.1.2 Listings
• Listing 1 (p. 1431) . Modied Turtle constructor. .
• Listing 2 (p. 1431) . Modied SimpleTurtle constructor.
• Listing 3 (p. 1432) . Modied toString method.
• Listing 4 (p. 1433) . Source code for the class named Prob02.
• Listing 5 (p. 1433) . Modied Turtle class.
• Listing 6 (p. 1435) . Modied SimpleTurtle class.
6.3.1.2.3 Preview
Program specications
Write a program named Prob02 that uses the class denition shown in Listing 4 (p. 1433) and Ericson's
media library to produce the graphic output image shown in Figure 1 (p. 1429) .
• Prob02.class
• Prob02.java
• SimpleTurtle.class
• SimpleTurtle.java
• Turtle.class
• Turtle.java
Output text
In addition to the output image described above, your program must produce the text output shown in
Figure 2 (p. 1430) on the command- line screen
Dick Baldwin
My name is Joe the turtle.
Required modications
By comparing the default behavior of the Turtle and SimpleTurtle classes with the requirements
of this program, it can be determined that the following modications to the Turtle and SimpleTurtle
classes are required to meet the specications.
1. Modify the Turtle class to cause the student's name to be displayed on the command line.
2. Modify the Turtle and SimpleTurtle classes to accept and save a String parameter in addition
to the World parameter when the Turtle object is constructed.
3. Modify the SimpleTurtle class to cause the default background of the world to be BLUE.
4. Modify the SimpleTurtle class to cause the student's name to be displayed near the top of the
World image.
5. Modify the toString method in the SimpleTurtle class to cause it to return the value of the
String parameter whenever the toString method is called. This causes the drawInfoString
method to display the string in place of its normal behavior. It also causes the last statement in Listing
4 (p. 1433) to display the turtle's name.
The Turtle class has several overloaded constructors. One of the constructors was modied to accept
a String parameter in addition to the World parameter and pass the new parameter along to the
superclass constructor. The code is shown in Listing 1 (p. 1431) .
A println statement was also added to the modied constructor to cause it to display the student's name
on the command line screen when the Turtle object is constructed as shown in Figure 2.
The modication is shown in the last four statements in Listing 2 (p. 1431) . This modication satises
items 2, 3, and 4 listed earlier under required modications
29 .
Modied toString method
29 http://cnx.org/content/m44348/latest/Lecture02.htm#Required_modications
Listing 3 (p. 1432) shows the modied toString method that satises item 5 listed above under
required modications
30 .
The original code was preserved as comments in Listing 3 (p. 1432) , and the new modied code is shown
below those comments.
6.3.1.2.6 Summary
You learned how to:
1. Modify the Turtle class to cause the student's name to be displayed on the command line.
2. Modify the Turtle and SimpleTurtle classes to accept and save a String parameter in addition
to the World parameter when the Turtle object is constructed.
3. Modify the SimpleTurtle class to cause the default background of the world to be BLUE.
4. Modify the SimpleTurtle class to cause the student's name to be displayed near the top of the
World image.
5. Modify the toString method in the SimpleTurtle class to cause it to return the value of the
String parameter whenever the toString method is called. This causes the drawInfoString
method to display the string in place of its normal behavior. It also causes the last statement in Listing
4 (p. 1433) to display the turtle's name.
6.3.1.2.8 Miscellaneous
This section contains a variety of miscellaneous information.
30 http://cnx.org/content/m44348/latest/Lecture02.htm#Required_modications
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import java.awt.Color;
/**
* Class that represents a turtle which is similar to a Logo turtle.
* This class inherts from SimpleTurtle and is for students
* to add methods to.
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class Turtle extends SimpleTurtle
{
////////////////// constructors ///////////////////////
//THIS IS A MODIFICATION
//The following constructor was modified to accept and
// save a String parameter and pass it to the superclass
// constructor.
/** Constructor that takes the model display
* @param modelDisplay the thing that displays the model
*/
public Turtle (ModelDisplay modelDisplay,
String turtleName){
// let the parent constructor handle it
super(modelDisplay,turtleName);
System.out.println("Dick Baldwin");
}
/**
* Constructor that takes a picture to draw on
* @param p the picture to draw on
*/
public Turtle (Picture p)
{
// let the parent constructor handle it
super(p);
}
} // this } is the end of class Turtle, put all new methods before this
import javax.swing.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.util.Observer;
import java.util.Random;
/**
* Class that represents a Logo-style turtle. The turtle
/**
* Constructor that takes the x and y position for the
* turtle
* @param x the x pos
* @param y the y pos
*/
public SimpleTurtle(int x, int y)
{
xPos = x;
yPos = y;
bodyColor = colorArray[numTurtles % colorArray.length];
setPenColor(bodyColor);
numTurtles++;
}
/**
* Constructor that takes the x and y position and the
* model displayer
* @param x the x pos
* @param y the y pos
* @param display the model display
*/
public SimpleTurtle(int x, int y, ModelDisplay display)
{
this(x,y); // call constructor that takes x and y
modelDisplay = display;
display.addModel(this);
}
//THIS IS A MODIFICATION
//The following constructor was modified to accept and
// save a String parameter.
String turtleName = null;
/**
* Constructor that takes a model display and adds
* a turtle in the middle of it
/**
* Constructor that takes the x and y position and the
* picture to draw on
* @param x the x pos
* @param y the y pos
* @param picture the picture to draw on
*/
public SimpleTurtle(int x, int y, Picture picture)
{
this(x,y); // call constructor that takes x and y
this.picture = picture;
this.visible = false; // default is not to see the turtle
}
/**
* Constructor that takes the
* picture to draw on and will appear in the middle
* @param picture the picture to draw on
*/
public SimpleTurtle(Picture picture)
{
// call constructor that takes x and y
this((int) (picture.getWidth() / 2),
(int) (picture.getHeight() / 2));
this.picture = picture;
this.visible = false; // default is not to see the turtle
}
/**
* Get the distance from the passed x and y location
* @param x the x location
* @param y the y location
*/
public double getDistance(int x, int y)
{
int xDiff = x - xPos;
int yDiff = y - yPos;
return (Math.sqrt((xDiff * xDiff) + (yDiff * yDiff)));
}
/**
* Method to turn to face another simple turtle
*/
public void turnToFace(SimpleTurtle turtle)
{
turnToFace(turtle.xPos,turtle.yPos);
}
/**
* Method to turn towards the given x and y
* @param x the x to turn towards
* @param y the y to turn towards
*/
public void turnToFace(int x, int y)
{
double dx = x - this.xPos;
double dy = y - this.yPos;
double arcTan = 0.0;
double angle = 0.0;
// avoid a divide by 0
if (dx == 0)
{
// if below the current turtle
if (dy > 0)
heading = 180;
/**
* Method to get the picture for this simple turtle
* @return the picture for this turtle (may be null)
*/
public Picture getPicture() { return this.picture; }
/**
* Method to set the picture for this simple turtle
* @param pict the picture to use
*/
public void setPicture(Picture pict) { this.picture = pict; }
/**
* Method to get the model display for this simple turtle
* @return the model display if there is one else null
*/
public ModelDisplay getModelDisplay() { return this.modelDisplay; }
/**
* Method to set the model display for this simple turtle
* @param theModelDisplay the model display to use
*/
public void setModelDisplay(ModelDisplay theModelDisplay)
{ this.modelDisplay = theModelDisplay; }
/**
* Method to get value of show info
* @return true if should show info, else false
*/
public boolean getShowInfo() { return this.showInfo; }
/**
* Method to show the turtle information string
* @param value the value to set showInfo to
*/
public void setShowInfo(boolean value) { this.showInfo = value; }
/**
* Method to get the shell color
* @return the shell color
*/
public Color getShellColor()
{
Color color = null;
if (this.shellColor == null && this.bodyColor != null)
color = bodyColor.darker();
else color = this.shellColor;
return color;
}
/**
* Method to set the shell color
* @param color the color to use
*/
public void setShellColor(Color color) { this.shellColor = color; }
/**
* Method to get the body color
* @return the body color
*/
public Color getBodyColor() { return this.bodyColor; }
/**
* Method to set the body color which
* will also set the pen color
* @param color the color to use
*/
public void setBodyColor(Color color)
{
this.bodyColor = color;
setPenColor(this.bodyColor);
}
/**
* Method to set the color of the turtle.
* This will set the body color
* @param color the color to use
*/
public void setColor(Color color) { this.setBodyColor(color); }
/**
* Method to get the information color
* @return the color of the information string
*/
public Color getInfoColor() { return this.infoColor; }
/**
* Method to set the information color
* @param color the new color to use
*/
public void setInfoColor(Color color) { this.infoColor = color; }
/**
* Method to return the width of this object
* @return the width in pixels
*/
public int getWidth() { return this.width; }
/**
* Method to return the height of this object
/**
* Method to set the width of this object
* @param theWidth in width in pixels
*/
public void setWidth(int theWidth) { this.width = theWidth; }
/**
* Method to set the height of this object
* @param theHeight the height in pixels
*/
public void setHeight(int theHeight) { this.height = theHeight; }
/**
* Method to get the current x position
* @return the x position (in pixels)
*/
public int getXPos() { return this.xPos; }
/**
* Method to get the current y position
* @return the y position (in pixels)
*/
public int getYPos() { return this.yPos; }
/**
* Method to get the pen
* @return the pen
*/
public Pen getPen() { return this.pen; }
/**
* Method to set the pen
* @param thePen the new pen to use
*/
public void setPen(Pen thePen) { this.pen = thePen; }
/**
* Method to check if the pen is down
* @return true if down else false
*/
public boolean isPenDown() { return this.pen.isPenDown(); }
/**
* Method to set the pen down boolean variable
* @param value the value to set it to
*/
public void setPenDown(boolean value) { this.pen.setPenDown(value); }
/**
* Method to lift the pen up
*/
public void penUp() { this.pen.setPenDown(false);}
/**
* Method to set the pen down
*/
public void penDown() { this.pen.setPenDown(true);}
/**
* Method to get the pen color
* @return the pen color
*/
public Color getPenColor() { return this.pen.getColor(); }
/**
* Method to set the pen color
* @param color the color for the pen ink
*/
public void setPenColor(Color color) { this.pen.setColor(color); }
/**
* Method to set the pen width
* @param width the width to use in pixels
*/
public void setPenWidth(int width) { this.pen.setWidth(width); }
/**
* Method to get the pen width
* @return the width of the pen in pixels
*/
public int getPenWidth() { return this.pen.getWidth(); }
/**
* Method to clear the path (history of
* where the turtle has been)
*/
public void clearPath()
{
this.pen.clearPath();
}
/**
* Method to get the current heading
* @return the heading in degrees
*/
public double getHeading() { return this.heading; }
/**
/**
* Method to get the name of the turtle
* @return the name of this turtle
*/
public String getName() { return this.name; }
/**
* Method to set the name of the turtle
* @param theName the new name to use
*/
public void setName(String theName)
{
this.name = theName;
}
/**
* Method to get the value of the visible flag
* @return true if visible else false
*/
public boolean isVisible() { return this.visible;}
/**
* Method to hide the turtle (stop showing it)
* This doesn't affect the pen status
*/
public void hide() { this.setVisible(false); }
/**
* Method to show the turtle (doesn't affect
* the pen status
*/
public void show() { this.setVisible(true); }
/**
* Method to set the visible flag
* @param value the value to set it to
*/
public void setVisible(boolean value)
{
// if the turtle wasn't visible and now is
if (visible == false && value == true)
{
// update the display
this.updateDisplay();
}
/**
* Method to update the display of this turtle and
* also check that the turtle is in the bounds
*/
public synchronized void updateDisplay()
{
// check that x and y are at least 0
if (xPos < 0)
xPos = 0;
if (yPos < 0)
yPos = 0;
// if picture
if (picture != null)
{
if (xPos >= picture.getWidth())
xPos = picture.getWidth() - 1;
if (yPos >= picture.getHeight())
yPos = picture.getHeight() - 1;
Graphics g = picture.getGraphics();
paintComponent(g);
}
else if (modelDisplay != null)
{
if (xPos >= modelDisplay.getWidth())
xPos = modelDisplay.getWidth() - 1;
if (yPos >= modelDisplay.getHeight())
yPos = modelDisplay.getHeight() - 1;
modelDisplay.modelChanged();
}
}
/**
* Method to move the turtle foward 100 pixels
*/
public void forward() { forward(100); }
/**
* Method to move the turtle forward the given number of pixels
* @param pixels the number of pixels to walk forward in the heading direction
*/
public void forward(int pixels)
{
int oldX = xPos;
// add a move from the old position to the new position to the pen
pen.addMove(oldX,oldY,xPos,yPos);
/**
* Method to go backward by 100 pixels
*/
public void backward()
{
backward(100);
}
/**
* Method to go backward a given number of pixels
* @param pixels the number of pixels to walk backward
*/
public void backward(int pixels)
{
forward(-pixels);
}
/**
* Method to move to turtle to the given x and y location
* @param x the x value to move to
* @param y the y value to move to
*/
public void moveTo(int x, int y)
{
this.pen.addMove(xPos,yPos,x,y);
this.xPos = x;
this.yPos = y;
this.updateDisplay();
}
/**
* Method to turn left
*/
public void turnLeft()
{
this.turn(-90);
}
/**
* Method to turn right
*/
public void turnRight()
{
this.turn(90);
}
/**
* Method to turn the turtle the passed degrees
* use negative to turn left and pos to turn right
* @param degrees the amount to turn in degrees
*/
public void turn(int degrees)
{
this.heading = (heading + degrees) % 360;
this.updateDisplay();
}
/**
* Method to draw a passed picture at the current turtle
* location and rotation in a picture or model display
* @param dropPicture the picture to drop
*/
public synchronized void drop(Picture dropPicture)
{
Graphics2D g2 = null;
// if g2 isn't null
if (g2 != null)
{
pen.paintComponent(g2);
}
}
/**
* Method to paint the turtle
* @param g the graphics context to paint on
*/
public synchronized void paintComponent(Graphics g)
{
// cast to 2d object
Graphics2D g2 = (Graphics2D) g;
/**
* Method to draw the information string
* @param g the graphics context
*/
public synchronized void drawInfoString(Graphics g)
{
g.setColor(infoColor);
g.drawString(this.toString(),xPos + (int) (width/2),yPos);
}
//This toString method was modified.
/**
* Method to return a string with informaiton
* about this turtle
* @return a string with information about this object
*/
//THIS IS A MODIFICATION
//MODIFIED toString METHOD
public String toString()
{
// return this.name + " turtle at " + this.xPos + ", " +
// this.yPos + " heading " + this.heading + ".";
return "My name is " + turtleName + " the turtle.";
}
} // end of class
-end-
6.3.1.3.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
32 .
6.3.1.3.2.1.1 Figures
• Figure 1 (p. 1451) . Initial screen output.
• Figure 2 (p. 1452) . Screen output after clicking the button.
• Figure 3 (p. 1453) . Required text output.
6.3.1.3.2.1.2 Listings
• Listing 1 (p. 1453) . The new getFrame method.
• Listing 2 (p. 1454) . Prob03 class denition.
• Listing 3 (p. 1454) . Beginning of the Prob03Runner class.
• Listing 4 (p. 1454) . Beginning of the run method.
• Listing 5 (p. 1456) . Register an action listener on the button.
• Listing 6 (p. 1456) . Set the picture background to blue.
• Listing 7 (p. 1456) . Display the student's name on the picture.
• Listing 8 (p. 1456) . Add a turtle to the world.
• Listing 9 (p. 1458) . Source code for the program named Prob03.
• Listing 10 (p. 1459) . The modied World class.
6.3.1.3.3 Preview
In this module, you will learn how to incorporate GUI components into a World object. In particular,
you will learn how to add a JButton object to a World object and register an action listener on the
button to control the behavior of the program.
Program specications
Write a program named Prob03 that uses the Prob03 class denition shown in Listing 2 (p. 1454)
and Ericson's media library to produce the graphic output images shown in Figure 1 (p. 1451) and Figure
2 (p. 1452) .
32 http://cnx.org/content/m44148/latest/
The image shown in Figure 1 (p. 1451) is the image that appears on the screen when the program starts
running.
In addition to the output images described above, your program must produce the text output shown in
Figure 3 (p. 1453) on the command- line screen
Dick Baldwin
Dick Baldwin
Picture, filename None height 300 width 200
Analysis
A World object is actually a specialized use of a standard Java JFrame object. However, by default,
the frame is not available to users of the World class. Therefore, in order to satisfy the requirements of
this program, the World class must be modied to provide access to the frame.
Add a getFrame method
This program adds a method named getFrame to the World class. The getFrame method returns
a reference to the JFrame object that is used to display the world. This makes it possible to treat World
objects in much the same way that other JFrame objects are treated.
Add a button and pack the frame
The program uses the JFrame object's reference to add a JButton object to the SOUTH location
of the JFrame . After adding the button, the program calls the pack method on the frame to cause the
size of the frame to be automatically adjusted to accommodate both the Picture object that constitutes
the background and the JButton object.
The new method also displays the student's name when the method is called, producing part of the text
output in Figure 3 (p. 1453) .
No other change to is required
This is the only change to Ericson's library that is required to write this program. Everything else in the
program makes use of existing library classes with no modications.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
class Prob03Runner{
public Prob03Runner(){
System.out.println("Dick Baldwin");
}//end constructor
As you can see, the constructor simply displays the student's name, providing some of the text output
shown in Figure 3 (p. 1454) .
Beginning of the run method
The beginning of therun method is shown in Listing 4 (p. 1454) . This is where things start to get
interesting.
frame.pack();//VERY IMPORTANT
button.addActionListener(new ActionListener()
{//Begin the class definition
picture.setAllPixelsToAColor(Color.BLUE);
As you might expect, this causes the background of the world to turn from white to blue as shown in Figure
2 (p. 1452) .
Display the student's name on the picture
addMessage method
Listing 7 (p. 1456) calls the on the picture to add the student's name near the
upper-left corner of the world. (See Figure 2 (p. 1452) .)
Listing 6.33: Display the student's name on the picture.
picture.addMessage("Dick Baldwin",10,20);
Finally, Listing 8 (p. 1456) instantiates a new Turtle object in the default color, with the default heading
(north) , located in the default position, which is the center of the picture that constitutes the background
image for the world.
);//end addActionListener
}//end run
//----------------------------------------------------//
}//end class Prob03Runner
Multiple clicks
If you click the button more than once, you will instantiate a new Turtle object and produce a line
of output text on the command line screen with each click. The turtles will all be in the same location but
they will cycle through four dierent color schemes.
Note that adding the turtle to the world causes the world to be repainted, eliminating the requirement
to purposely repaint the world.
End the run method
Finally, Listing 8 (p. 1456) signals the end of the run method, causing the run method to terminate
and return control to the main method in Listing 2 (p. 1454) . The main method terminates causing
the program to terminate.
6.3.1.3.6 Summary
In this module, you learned how to incorporate GUI components into a World object. In particular, you
learned how to add a JButton object to a World object and register an action listener on the button
to control the behavior of the program.
6.3.1.3.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
//======================================================//
class Prob03Runner{
public Prob03Runner(){
System.out.println("Dick Baldwin");
}//end constructor
//----------------------------------------------------//
public void run(){
//This reference must be final because it is
// referenced from within an anonymous class
// definition.
final World world = new World(200,300);
frame.pack();//VERY IMPORTANT
}//end run
//----------------------------------------------------//
}//end class Prob03Runner
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observer;
import java.awt.*;
/**
* Class to represent a 2d world that can hold turtles and
* display them
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class World extends JComponent implements ModelDisplay
{
////////////////// fields ///////////////////////
/**
* Constructor that takes no arguments
*/
public World()
{
// set up the world and make it visible
initWorld(true);
}
/**
* Constructor that takes a boolean to
* say if this world should be visible
* or not
* @param visibleFlag if true will be visible
* else if false will not be visible
*/
public World(boolean visibleFlag)
{
initWorld(visibleFlag);
}
/**
* Constructor that takes a width and height for this
* world
* @param w the width for the world
* @param h the height for the world
*/
public World(int w, int h)
{
width = w;
height = h;
/**
* Method to initialize the world
* @param visibleFlag the flag to make the world
* visible or not
*/
private void initWorld(boolean visibleFlag)
{
// set the preferred size
this.setPreferredSize(new Dimension(width,height));
/**
* Method to get the graphics context for drawing on
* @return the graphics context of the background picture
*/
public Graphics getGraphics() { return picture.getGraphics(); }
/**
* Method to clear the background picture
*/
public void clearBackground() { picture = new Picture(width,height); }
/**
/**
* Method to set the background picture
* @param pict the background picture to use
*/
public void setPicture(Picture pict) { picture = pict; }
/**
* Method to paint this component
* @param g the graphics context
*/
public synchronized void paintComponent(Graphics g)
{
Turtle turtle = null;
/**
* Metod to get the last turtle in this world
* @return the last turtle added to this world
*/
public Turtle getLastTurtle()
{
return (Turtle) turtleList.get(turtleList.size() - 1);
}
/**
* Method to add a model to this model displayer
* @param model the model object to add
*/
public void addModel(Object model)
{
turtleList.add((Turtle) model);
if (autoRepaint)
repaint();
}
/**
* Method to check if this world contains the passed
* turtle
* @return true if there else false
*/
public boolean containsTurtle(Turtle turtle)
{
return (turtleList.contains(turtle));
}
/**
* Method to remove the passed object from the world
* @param model the model object to remove
*/
public void remove(Object model)
{
turtleList.remove(model);
}
/**
* Method to get the width in pixels
* @return the width in pixels
*/
public int getWidth() { return width; }
/**
* Method to get the height in pixels
* @return the height in pixels
*/
public int getHeight() { return height; }
/**
* Method that allows the model to notify the display
*/
public void modelChanged()
{
if (autoRepaint)
repaint();
}
/**
* Method to set the automatically repaint flag
* @param value if true will auto repaint
*/
public void setAutoRepaint(boolean value) { autoRepaint = value; }
/**
* Method to hide the frame
*/
// public void hide()
// {
// frame.setVisible(false);
// }
/**
* Method to show the frame
*/
// public void show()
// {
// frame.setVisible(true);
// }
/**
* Method to set the visibility of the world
* @param value a boolean value to say if should show or hide
*/
public void setVisible(boolean value)
{
frame.setVisible(value);
}
/**
* Method to get the list of turtles in the world
* @return a list of turtles in the world
*/
public List getTurtleList()
{ return turtleList;}
/**
* Method to get an iterator on the list of turtles
* @return an iterator for the list of turtles
*/
public Iterator getTurtleIterator()
{ return turtleList.iterator();}
/**
* Method that returns information about this world
* in the form of a string
* @return a string of information about this world
*/
public String toString()
{
return "A " + getWidth() + " by " + getHeight() +
" world with " + turtleList.size() + " turtles in it.";
}
-end-
6.3.1.4 Java OOP: Background Color, Text Color, Mouse Clicks, etc.33
6.3.1.4.1 Table of Contents
• Preface (p. 1465)
6.3.1.4.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
34 .
6.3.1.4.2.1.1 Figures
• Figure 1 (p. 1466) . Output image at startup.
• Figure 2 (p. 1467) . Output image after ten mouse clicks.
• Figure 3 (p. 1468) . Output image after eleven mouse clicks.
6.3.1.4.2.1.2 Listings
• Listing 1 (p. 1469) . The new setMessageColor method.
• Listing 2 (p. 1470) . The modied addMessage method.
• Listing 3 (p. 1470) . Beginning of the Prob04Runner class.
• Listing 4 (p. 1471) . Beginning of the anonymous listener class.
• Listing 5 (p. 1472) . Add a turtle to the world.
• Listing 6 (p. 1472) . Not the rst click.
• Listing 7 (p. 1472) . Process odd or even clicks.
• Listing 8 (p. 1473) . Cause the program to terminate properly.
• Listing 9 (p. 1475) . Source code for the program named Prob04.
• Listing 10 (p. 1476) . Modied World class.
• Listing 11 (p. 1482) . Modied SimplePicture class.
6.3.1.4.3 Preview
The program that I will explain in this module requires you to modify both the World class and the
SimplePicture class from Ericson's media library.
Just as you did in an earlier module, you will modify the World class to make it possible to get access
to the JFrame object that is encapsulated in a World object.
You will modify theSimplePicture class to make it possible to control the color of the text that is
Picture object.
placed on the image in a
Program specications
Write a program named Prob04 that uses the class denition for the Prob04 class shown in Listing
9 (p. 1475) along with Ericson's media library to produce the graphic output images shown in Figure 1 (p.
1466) , Figure 2 (p. 1467) , and Figure 3 (p. 1468) .
Output image at startup
Figure 1 (p. 1466) shows the output image when you rst start the program.
Operational description
The program initially displays an empty white world with a button at the bottom as shown in Figure 1
(p. 1466) .
When the user clicks the button:
• The colors revert to the color scheme with the yellow background.
• The turtle turns 90 degrees left and moves forward 100 pixels plus the value of the click counter leaving
a red trail.
}//end addMessage
The original statement shown in Listing 2 (p. 1470) was disabled and replaced by the statement shown
following the modication comment. This causes the text to be displayed on the image using the color stored
in the new private instance variable named messageColor .
The Prob04Runner class
I will explain this program in fragments. A complete listing is shown in Listing 9 (p. 1475) near the end
of the module.
The driver class
The driver class for this program is named Prob04 . As I mentioned earlier, you can view the class
denition in its entirety near the beginning of Listing 9 (p. 1475) .
Beginning of the Prob04Runner class
The Prob04Runner class begins in Listing 3 (p. 1470) .
Listing 6.39: Beginning of the Prob04Runner class.
class Prob04Runner{
Turtle turtle = null;
Picture picture = null;
int counter = 0;
World world = new World(200,200);
JButton button = new JButton("Click Me.");
public Prob04Runner(){
System.out.println("Dick Baldwin");
System.out.println(world.getPicture());
frame.pack();
button.addActionListener(new ActionListener()
{//Begin the anonymous class definition
Listing 5 (p. 1472) tests to determine if the variable named turtle that was declared in Listing 3 (p.
1470) still contains null. If so, that means that this is the rst time that the button has been clicked and
the Turtle object has not yet been added to the world.
Listing 6.41: Add a turtle to the world.
if(turtle == null){
turtle = new Turtle(150,150,world);
turtle.setHeading(90);
turtle.setShellColor(Color.RED);
turtle.setBodyColor(Color.BLUE);
}else{
turtle.turnLeft();
turtle.forward(100+counter);
if(counter++ %2 != 0){
picture.setAllPixelsToAColor(Color.GREEN);
picture.setMessageColor(Color.RED);
picture.addMessage(
"Dick Baldwin",10,20);
turtle.setShellColor(Color.RED);
turtle.setBodyColor(Color.BLUE);
}else{
picture.setAllPixelsToAColor(Color.YELLOW);
picture.setMessageColor(Color.BLUE);
picture.addMessage(
"Dick Baldwin",10,20);
turtle.setShellColor(Color.BLUE);
turtle.setBodyColor(Color.RED);
}//end else
picture.addMessage(
"Dick Baldwin",10,20);
}//end else
}//end actionPerformed
}//end class definition
);//end addActionListener
}//end constructor
//----------------------------------------------------//
To understand why this is necessary to cause the program to terminate, I recommend that you visit the
standard Sun javadocs and examine the description of the method named setDefaultCloseOperation in
6.3.1.4.6 Summary
Just as you did in an earlier module, you modied theWorld class to make it possible to get access to the
JFrame World object.
object that is encapsulated in a
You learned how to modify the SimplePicture class to make it possible to control the color of the
text that is placed on the image in a Picture object.
Then you placed a turtle object in a world and performed a series of maneuvers causing the turtle to
draw a square spiral.
6.3.1.4.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
class Prob04Runner{
Turtle turtle = null;
Picture picture = null;
int counter = 0;
World world = new World(200,200);
JButton button = new JButton("Click Me.");
public Prob04Runner(){
System.out.println("Dick Baldwin");
System.out.println(world.getPicture());
frame.pack();
picture.addMessage(
"Dick Baldwin",10,20);
turtle.setShellColor(Color.RED);
turtle.setBodyColor(Color.BLUE);
}else{
picture.setAllPixelsToAColor(Color.YELLOW);
picture.setMessageColor(Color.BLUE);
picture.addMessage(
"Dick Baldwin",10,20);
turtle.setShellColor(Color.BLUE);
turtle.setBodyColor(Color.RED);
}//end else
picture.addMessage(
"Dick Baldwin",10,20);
}//end else
}//end actionPerformed
}//end class definition
);//end addActionListener
}//end constructor
//----------------------------------------------------//
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observer;
import java.awt.*;
/**
* Class to represent a 2d world that can hold turtles and
* display them
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class World extends JComponent implements ModelDisplay
{
////////////////// fields ///////////////////////
/**
* Constructor that takes no arguments
*/
public World()
{
// set up the world and make it visible
initWorld(true);
}
/**
* Constructor that takes a boolean to
* say if this world should be visible
* or not
* @param visibleFlag if true will be visible
* else if false will not be visible
*/
public World(boolean visibleFlag)
{
initWorld(visibleFlag);
}
/**
* Constructor that takes a width and height for this
* world
* @param w the width for the world
* @param h the height for the world
*/
public World(int w, int h)
{
width = w;
height = h;
/**
* Method to initialize the world
* @param visibleFlag the flag to make the world
* visible or not
*/
private void initWorld(boolean visibleFlag)
{
// set the preferred size
this.setPreferredSize(new Dimension(width,height));
/**
* Method to get the graphics context for drawing on
* @return the graphics context of the background picture
*/
public Graphics getGraphics() { return picture.getGraphics(); }
/**
* Method to clear the background picture
*/
public void clearBackground() { picture = new Picture(width,height); }
/**
* Method to get the background picture
* @return the background picture
*/
public Picture getPicture() { return picture; }
/**
* Method to set the background picture
* @param pict the background picture to use
*/
public void setPicture(Picture pict) { picture = pict; }
/**
* Method to paint this component
* @param g the graphics context
*/
public synchronized void paintComponent(Graphics g)
{
Turtle turtle = null;
}
}
/**
* Metod to get the last turtle in this world
* @return the last turtle added to this world
*/
public Turtle getLastTurtle()
{
return (Turtle) turtleList.get(turtleList.size() - 1);
}
/**
* Method to add a model to this model displayer
* @param model the model object to add
*/
public void addModel(Object model)
{
turtleList.add((Turtle) model);
if (autoRepaint)
repaint();
}
/**
* Method to check if this world contains the passed
* turtle
* @return true if there else false
*/
public boolean containsTurtle(Turtle turtle)
{
return (turtleList.contains(turtle));
}
/**
* Method to remove the passed object from the world
* @param model the model object to remove
*/
public void remove(Object model)
{
turtleList.remove(model);
}
/**
* Method to get the width in pixels
* @return the width in pixels
*/
public int getWidth() { return width; }
/**
* Method to get the height in pixels
/**
* Method that allows the model to notify the display
*/
public void modelChanged()
{
if (autoRepaint)
repaint();
}
/**
* Method to set the automatically repaint flag
* @param value if true will auto repaint
*/
public void setAutoRepaint(boolean value) { autoRepaint = value; }
/**
* Method to hide the frame
*/
// public void hide()
// {
// frame.setVisible(false);
// }
/**
* Method to show the frame
*/
// public void show()
// {
// frame.setVisible(true);
// }
/**
* Method to set the visibility of the world
* @param value a boolean value to say if should show or hide
*/
public void setVisible(boolean value)
{
frame.setVisible(value);
}
/**
* Method to get the list of turtles in the world
* @return a list of turtles in the world
*/
public List getTurtleList()
{ return turtleList;}
/**
* Method to get an iterator on the list of turtles
* @return an iterator for the list of turtles
*/
public Iterator getTurtleIterator()
{ return turtleList.iterator();}
/**
* Method that returns information about this world
* in the form of a string
* @return a string of information about this world
*/
public String toString()
{
return "A " + getWidth() + " by " + getHeight() +
" world with " + turtleList.size() + " turtles in it.";
}
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import java.awt.*;
import java.io.*;
import java.awt.geom.*;
/*
12/23/08 Modified the addMessage method to cause it to
use a color variable to set the color of the message.
Also provided a setMessageColor method to set the color
and a variable named messageColor to contain the color.
/*
/**
* A class that represents a simple picture. A simple picture may have
* an associated file name and a title. A simple picture has pixels,
* width, and height. A simple picture uses a BufferedImage to
* hold the pixels. You can show a simple picture in a
* PictureFrame (a JFrame).
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class SimplePicture implements DigitalPicture
{
/**
* the color of the message
*/
private Color messageColor = Color.WHITE;
/**
* the file name associated with the simple picture
*/
private String fileName;
/**
* the title of the simple picture
*/
private String title;
/**
* buffered image to hold pixels for the simple picture
*/
private BufferedImage bufferedImage;
/**
* frame used to display the simple picture
*/
private PictureFrame pictureFrame;
/**
* extension for this file (jpg or bmp)
*/
private String extension;
/**
* A Constructor that takes no arguments. All fields will be null.
* A no-argument constructor must be given in order for a class to
* be able to be subclassed. By default all subclasses will implicitly
* call this in their parent's no argument constructor unless a
* different call to super() is explicitly made as the first line
* of code in a constructor.
*/
public SimplePicture()
{this(200,100);}
/**
* A Constructor that takes a file name and uses the file to create
* a picture
* @param fileName the file name to use in creating the picture
*/
public SimplePicture(String fileName)
/**
* A constructor that takes the width and height desired for a picture and
* creates a buffered image of that size. This constructor doesn't
* show the picture.
* @param width the desired width
* @param height the desired height
*/
public SimplePicture(int width, int height)
{
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
title = "None";
fileName = "None";
extension = "jpg";
setAllPixelsToAColor(Color.white);
}
/**
* A constructor that takes the width and height desired for a picture and
* creates a buffered image of that size. It also takes the
* color to use for the background of the picture.
* @param width the desired width
* @param height the desired height
* @param theColor the background color for the picture
*/
public SimplePicture(int width, int height, Color theColor)
{
this(width,height);
setAllPixelsToAColor(theColor);
}
/**
* A Constructor that takes a picture to copy information from
* @param copyPicture the picture to copy from
*/
public SimplePicture(SimplePicture copyPicture)
{
if (copyPicture.fileName != null)
{
this.fileName = new String(copyPicture.fileName);
this.extension = copyPicture.extension;
}
if (copyPicture.title != null)
this.title = new String(copyPicture.title);
if (copyPicture.bufferedImage != null)
{
this.bufferedImage = new BufferedImage(copyPicture.getWidth(),
copyPicture.getHeight(), BufferedImage.TYPE_INT_RGB);
this.copyPicture(copyPicture);
}
}
/**
* A constructor that takes a buffered image
* @param image the buffered image
*/
public SimplePicture(BufferedImage image)
{
this.bufferedImage = image;
title = "None";
fileName = "None";
extension = "jpg";
}
/**
* Method to get the extension for this picture
* @return the extendsion (jpg or bmp)
*/
public String getExtension() { return extension; }
/**
* Method that will copy all of the passed source picture into
* the current picture object
* @param sourcePicture the picture object to copy
*/
public void copyPicture(SimplePicture sourcePicture)
{
Pixel sourcePixel = null;
Pixel targetPixel = null;
{
// loop through the rows
for (int sourceY = 0, targetY = 0;
sourceY < sourcePicture.getHeight() &&
targetY < this.getHeight();
sourceY++, targetY++)
{
sourcePixel = sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
/**
* Method to set the color in the picture to the passed color
* @param color the color to set to
*/
public void setAllPixelsToAColor(Color color)
{
// loop through all x
for (int x = 0; x < this.getWidth(); x++)
{
// loop through all y
for (int y = 0; y < this.getHeight(); y++)
{
getPixel(x,y).setColor(color);
}
}
}
/**
* Method to get the buffered image
* @return the buffered image
*/
public BufferedImage getBufferedImage()
{
return bufferedImage;
}
/**
* Method to get a graphics object for this picture to use to draw on
* @return a graphics object to use for drawing
*/
public Graphics getGraphics()
{
return bufferedImage.getGraphics();
}
/**
/**
* Method to get the file name associated with the picture
* @return the file name associated with the picture
*/
public String getFileName() { return fileName; }
/**
* Method to set the file name
* @param name the full pathname of the file
*/
public void setFileName(String name)
{
fileName = name;
}
/**
* Method to get the title of the picture
* @return the title of the picture
*/
public String getTitle()
{ return title; }
/**
* Method to set the title for the picture
* @param title the title to use for the picture
*/
public void setTitle(String title)
{
this.title = title;
if (pictureFrame != null)
pictureFrame.setTitle(title);
}
/**
* Method to get the width of the picture in pixels
* @return the width of the picture in pixels
*/
public int getWidth() { return bufferedImage.getWidth(); }
/**
* Method to get the height of the picture in pixels
* @return the height of the picture in pixels
*/
/**
* Method to get the picture frame for the picture
* @return the picture frame associated with this picture
* (it may be null)
*/
public PictureFrame getPictureFrame() { return pictureFrame; }
/**
* Method to set the picture frame for this picture
* @param pictureFrame the picture frame to use
*/
public void setPictureFrame(PictureFrame pictureFrame)
{
// set this picture objects' picture frame to the passed one
this.pictureFrame = pictureFrame;
}
/**
* Method to get an image from the picture
* @return the buffered image since it is an image
*/
public Image getImage()
{
return bufferedImage;
}
/**
* Method to return the pixel value as an int for the given x and y location
* @param x the x coordinate of the pixel
* @param y the y coordinate of the pixel
* @return the pixel value as an integer (alpha, red, green, blue)
*/
public int getBasicPixel(int x, int y)
{
return bufferedImage.getRGB(x,y);
}
/**
* Method to set the value of a pixel in the picture from an int
* @param x the x coordinate of the pixel
* @param y the y coordinate of the pixel
* @param rgb the new rgb value of the pixel (alpha, red, green, blue)
*/
public void setBasicPixel(int x, int y, int rgb)
{
bufferedImage.setRGB(x,y,rgb);
}
/**
/**
* Method to get a one-dimensional array of Pixels for this simple picture
* @return a one-dimensional array of Pixel objects starting with y=0
* to y=height-1 and x=0 to x=width-1.
*/
public Pixel[] getPixels()
{
int width = getWidth();
int height = getHeight();
Pixel[] pixelArray = new Pixel[width * height];
return pixelArray;
}
/**
* Method to load the buffered image with the passed image
* @param image the image to use
*/
public void load(Image image)
{
// get a graphics context to use to draw on the buffered image
Graphics2D graphics2d = bufferedImage.createGraphics();
/**
* Method to show the picture in a picture frame
*/
public void show()
{
// if there is a current picture frame then use it
if (pictureFrame != null)
pictureFrame.updateImageAndShowIt();
/**
* Method to hide the picture
*/
public void hide()
{
if (pictureFrame != null)
pictureFrame.setVisible(false);
}
/**
* Method to make this picture visible or not
* @param flag true if you want it visible else false
*/
public void setVisible(boolean flag)
{
if (flag)
this.show();
else
this.hide();
}
/**
* Method to open a picture explorer on a copy of this simple picture
*/
public void explore()
{
// create a copy of the current picture and explore it
new PictureExplorer(new SimplePicture(this));
}
/**
* Method to force the picture to redraw itself. This is very
* useful after you have changed the pixels in a picture.
*/
public void repaint()
{
// if there is a picture frame tell it to repaint
if (pictureFrame != null)
pictureFrame.repaint();
/**
* Method to load the picture from the passed file name
* @param fileName the file name to use to load the picture from
*/
public void loadOrFail(String fileName) throws IOException
{
// set the current picture's file name
this.fileName = fileName;
if (!file.canRead())
{
// try adding the media path
file = new File(FileChooser.getMediaPath(this.fileName));
if (!file.canRead())
{
throw new IOException(this.fileName +
" could not be opened. Check that you specified the path");
}
}
bufferedImage = ImageIO.read(file);
}
/**
* Method to write the contents of the picture to a file with
* the passed name without throwing errors
* @param fileName the name of the file to write the picture to
* @return true if success else false
*/
public boolean load(String fileName)
{
try {
this.loadOrFail(fileName);
return true;
/**
* Method to load the picture from the passed file name
* this just calls load(fileName) and is for name compatibility
* @param fileName the file name to use to load the picture from
* @return true if success else false
*/
public boolean loadImage(String fileName)
{
return load(fileName);
}
/**
* Method to draw a message as a string on the buffered image
* @param message the message to draw on the buffered image
* @param xPos the leftmost point of the string in x
* @param yPos the bottom of the string in y
*/
public void addMessage(String message, int xPos, int yPos)
{
// get a graphics context to use to draw on the buffered image
Graphics2D graphics2d = bufferedImage.createGraphics();
/**
* Method to draw a string at the given location on the picture
* @param text the text to draw
/**
* Method to create a new picture by scaling the current
* picture by the given x and y factors
* @param xFactor the amount to scale in x
* @param yFactor the amount to scale in y
* @return the resulting picture
*/
public Picture scale(double xFactor, double yFactor)
{
// set up the scale tranform
AffineTransform scaleTransform = new AffineTransform();
scaleTransform.scale(xFactor,yFactor);
return result;
}
/**
* Method to create a new picture of the passed width.
* The aspect ratio of the width and height will stay
* the same.
* @param width the desired width
* @return the resulting picture
*/
public Picture getPictureWithWidth(int width)
{
// set up the scale tranform
double xFactor = (double) width / this.getWidth();
Picture result = scale(xFactor,xFactor);
return result;
}
/**
/**
* Method to load a picture from a file name and show it in a picture frame
* @param fileName the file name to load the picture from
* @return true if success else false
*/
public boolean loadPictureAndShowIt(String fileName)
{
boolean result = true; // the default is that it worked
// try to load the picture into the buffered image from the file name
result = load(fileName);
return result;
}
/**
* Method to write the contents of the picture to a file with
* the passed name
* @param fileName the name of the file to write the picture to
*/
public void writeOrFail(String fileName) throws IOException
{
String extension = this.extension; // the default is current
/**
* Method to write the contents of the picture to a file with
* the passed name without throwing errors
* @param fileName the name of the file to write the picture to
* @return true if success else false
*/
public boolean write(String fileName)
{
try {
this.writeOrFail(fileName);
return true;
} catch (Exception ex) {
System.out.println("There was an error trying to write " + fileName);
return false;
}
/**
* Method to set the media path by setting the directory to use
* @param directory the directory to use for the media path
*/
public static void setMediaPath(String directory) {
FileChooser.setMediaPath(directory);
}
/**
* Method to get the directory for the media
* @param fileName the base file name to use
* @return the full path name by appending
* the file name to the media directory
*/
public static String getMediaPath(String fileName) {
return FileChooser.getMediaPath(fileName);
}
/**
* Method to get the coordinates of the enclosing rectangle after this
* transformation is applied to the current picture
* @return the enclosing rectangle
*/
public Rectangle2D getTransformEnclosingRect(AffineTransform trans)
{
int width = getWidth();
int height = getHeight();
double maxX = width - 1;
double maxY = height - 1;
double minX, minY;
Point2D.Double p1 = new Point2D.Double(0,0);
Point2D.Double p2 = new Point2D.Double(maxX,0);
Point2D.Double p3 = new Point2D.Double(maxX,maxY);
Point2D.Double p4 = new Point2D.Double(0,maxY);
Point2D.Double result = new Point2D.Double(0,0);
Rectangle2D.Double rect = null;
// get the new points and min x and y and max x and y
trans.deltaTransform(p1,result);
minX = result.getX();
maxX = result.getX();
minY = result.getY();
maxY = result.getY();
trans.deltaTransform(p2,result);
minX = Math.min(minX,result.getX());
maxX = Math.max(maxX,result.getX());
minY = Math.min(minY,result.getY());
maxY = Math.max(maxY,result.getY());
trans.deltaTransform(p3,result);
minX = Math.min(minX,result.getX());
maxX = Math.max(maxX,result.getX());
minY = Math.min(minY,result.getY());
maxY = Math.max(maxY,result.getY());
trans.deltaTransform(p4,result);
minX = Math.min(minX,result.getX());
maxX = Math.max(maxX,result.getX());
minY = Math.min(minY,result.getY());
maxY = Math.max(maxY,result.getY());
/**
* Method to return a string with information about this picture
* @return a string with information about the picture
*/
public String toString()
{
String output = "Simple Picture, filename " + fileName +
" height " + getHeight() + " width " + getWidth();
return output;
-end-
6.3.1.5.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
36 .
6.3.1.5.2.1.1 Figures
• Figure 1 (p. 1500) . Program output at startup.
• Figure 2 (p. 1501) . Program output after one click.
• Figure 3 (p. 1502) . Program output after several clicks.
6.3.1.5.2.1.2 Listings
• Listing 1 (p. 1503) . Beginning of the class named Prob05Runner.
• Listing 2 (p. 1503) . Instantiate GUI components.
• Listing 3 (p. 1504) . Beginning of the constructor.
• Listing 4 (p. 1504) . Add the six GUI components to the panel.
• Listing 5 (p. 1505) . Get the frame and add the panel to the frame.
• Listing 6 (p. 1505) . Set the background to blue and add a turtle.
• Listing 7 (p. 1506) . Dene, instantiate, and register a listener on the Move button.
• Listing 8 (p. 1506) . Action listener to terminate the program.
• Listing 9 (p. 1508) . Source code for Prob05.
6.3.1.5.3 Preview
In this module, you will learn how to create and service a graphical user interface containing panels, labels,
text elds, and buttons.
Just as you did in earlier modules, you will modify the World class to make it possible to get access
to the JFrame object that is encapsulated in a World object. However, because I explained those
modications to the World class in earlier modules, I won't repeat the explanation here. You can nd a
modied version of the World class in Java OOP: Background Color, Text Color, Mouse Clicks, etc.
37
Program specications
Write a program namedProb05 that uses the class denition named Prob05 shown in Listing 9 (p.
1508) along with Ericson's media library to produce the graphic output images shown in Figure 1 (p. 1500)
, Figure 2 (p. 1501) , and Figure 3 (p. 1502) .
Program output at startup
Figure 1 (p. 1500) shows the image that appears on the screen when the program rst starts running.
37 http://cnx.org/content/m44351/latest/#Listing_10
class Prob05Runner{
Turtle turtle = null;
Picture picture = null;
World world = new World(200,300);
There's nothing new in Listing 1 (p. 1503) . You have seen code like this in several earlier modules.
Instantiate GUI components
Listing 2 (p. 1503) instantiates the GUI components that are used to construct the GUI at the bottom
of Figure 1 (p. 1500) .
int angle = 0;
int distance = 0;
References to the GUI components are saved in instance variables with descriptive names.
GUI component initialization
Panel object, each
Except for the GUI component is initialized with information that is appropriate
to the type of component. Compare the initialization values in Listing 2 (p. 1503) with the image in Figure
1 (p. 1500) for a better understanding of what I mean by this.
Brief description of the GUI components
You are encouraged to visit the Sun Java documentation and read about the following AWT components:
Panel : A panel provides space in which an application can attach any other components, including
other panels.
• Label : A Label object is a component for placing text in a container. A label displays a single line
of read-only text. The text can be changed by the application, but a user cannot edit it directly.
• TextField : A text component that allows for the editing of a single line of text.
• Button : This class creates a labeled button. The application can cause some action to happen
when the button is pushed.
Figure 1 (p. 1500) contains a Panel object at the bottom. The panel contains two Label objects (shown
as orange) , two TextField objects (white) , and two Button objects (gray) . Those seven objects
are instantiated in Listing 2 (p. 1503) .
The angle and distance variables
Listing 2 (p. 1503) also declares and initializes two instance variables named angle and distance .
(Note that these two variables would be automatically initialized to zero if I didn't initialize them, but I
prefer to initialize them explicitly in order to make the code more self-documenting.)
Beginning of the constructor
The constructor for the class named Prob05Runner begins in Listing 3 (p. 1504) .
public Prob05Runner(){
System.out.println("Dick Baldwin");
mainPanel.setBackground(Color.ORANGE);
mainPanel.setLayout(new GridLayout(0,2));
The constructor begins by displaying my name on the command line screen. This is inconsequential insofar
as the overall operation of the program is concerned.
Set the panel background color to orange
Then Listing 3 (p. 1504) sets the background color of the panel to orange. This is what causes the two
labels in Figure 1 (p. 1500) to appear to be orange. They are actually transparent except for the text. The
orange color shows through causing the labels to appear to be orange.
Set the layout to GridLayout
Setting the layout manager controls how the components that are placed in the panel will be arranged.
A GridLayout causes all components to be the same size arranged in rows and columns.
Overloaded constructors
There are several overloaded versions of the GridLayout constructor. For the constructor used in
Listing 3 (p. 1504) , the parameters specify the number of rows and the number of columns in that order.
Specifying the number of rows as 0 and the number of columns as 2 means that the layout manager will
accept any number of rows but only two columns.
The order of component placement
The intersections of the rows and columns create cells . Components are placed in the cells in left to
right, top to bottom order as they are added to the panel.
Add the six GUI components to the panel
Listing 4 (p. 1504) adds the six GUI components to the panel in the left to right, top to bottom order
described above.
mainPanel.add(angleLabel);
mainPanel.add(angleField);
mainPanel.add(distanceLabel);
mainPanel.add(distanceField);
mainPanel.add(moveButton);
mainPanel.add(quitButton);
At this point, the panel has been populated with GUI components, but the panel itself has not been added
to the JFrame object that forms the World object. That is accomplished in Listing 5 (p. 1505) .
Get the frame and add the panel to the frame
Listing 5 (p. 1505) gets a reference to the World object's frame and adds the panel to the SOUTH
location in that frame.
Listing 6.52: Get the frame and add the panel to the frame.
frame.pack();
You can surmise from the word SOUTH that the panel is added to the bottom of the frame. To learn more
BorderLayout
about this, visit the class in Sun's Java documentation.
Pack the frame
As you learned in an earlier module, it is very important that you pack the frame at this point. Packing
the frame causes the frame to adjust its dimensions in order to accommodate all of the components that
Picture object (placed there when the World
have been added to it. In this case, the frame contains a
was constructed) Panel object placed there in Listing 5 (p. 1505) .
and a
What about the size of the panel?
Exactly how the panel decides what size it needs to be to accommodate the six GUI components is a
fairly complicated topic, so I won't go into it here. However, if you do much work developing GUIs, you
denitely need to understand the process. I have explained the automatic sizing process in several tutorials
on my website.
Set the background to blue and add a turtle
Listing 6 (p. 1505) sets the background color of the world to blue and adds a turtle to the world.
There is nothing new in Listing 6 (p. 1505) . I have explained code very similar to this code in earlier
modules.
Could stop at this point
If we were to stop programming at this point, the program would be executable, and would produce the
output shown in Figure 1 (p. 1500) when it is run. However it would be completely passive. By that, I
mean that entering values into the text elds and clicking the buttons at the bottom of Figure 1 (p. 1500)
would have no eect. However, the buttons would appear to be active from a visual viewpoint because the
animation behavior is built into objects of the Button class.
Register listener objects
In order to cause the buttons to impact the behavior of the program, we must instantiate and register
listener object on the buttons. I will do that using anonymous classes.
Dene, instantiate, and register a listener on the Move button
The code in Listing 7 (p. 1506) :
Listing 6.54: Dene, instantiate, and register a listener on the Move button.
moveButton.addActionListener(
new ActionListener(){
}//end newActionListener
);//end addActionListener
quitButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}//end constructor
//----------------------------------------------------//
As you can see in Listing 8 (p. 1506) , this code causes the exit method of the System class to be called
when the user clicks the Quit button. According to the Sun documentation, a call to the exit method
"Terminates the currently running Java Virtual Machine."
The end of the constructor and the end of the class
Listing 8 (p. 1506) also shows the end of the constructor for the Prob05Runner class and the end of
the class.
6.3.1.5.6 Summary
In this module, you learned how to create and service a graphical user interface containing panels, labels,
text elds, and buttons.
• Alpha transparency
• A buered image of type TYPE_INT_ARGB
• The ability to use the getBasicPixel and setBasicPixel methods,
• The use of the bitwise AND and OR operators,
• The use of the drawImage method of the Graphics class.
6.3.1.5.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JFrame;
*********************************************************/
class Prob05Runner{
Turtle turtle = null;
Picture picture = null;
World world = new World(200,300);
Panel mainPanel = new Panel();
Label angleLabel = new Label("Enter Angle");
TextField angleField = new TextField("000");
Label distanceLabel = new Label("Enter Distance");
TextField distanceField = new TextField("000");
Button moveButton = new Button("Move");
Button quitButton = new Button("Quit");
int angle = 0;
int distance = 0;
public Prob05Runner(){
System.out.println("Dick Baldwin");
frame.pack();
//--------------------------------------------------//
//Register anonymous listeners on the two buttons.
moveButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
angle = Integer.parseInt(angleField.getText());
distance = Integer.parseInt(
distanceField.getText());
turtle.turn(angle);
turtle.forward(distance);
}//end action performed
}//end newActionListener
);//end addActionListener
quitButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}//end action performed
}//end newActionListener
);//end addActionListener
}//end constructor
//----------------------------------------------------//
-end-
6.3.2 Part 2
6.3.2.1 Java OOP: Using Alpha Transparency with Ericson's Media Library38
6.3.2.1.1 Table of Contents
• Preface (p. 1510)
6.3.2.1.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
39 .
6.3.2.1.2.1.1 Figures
• Figure 1 (p. 1512) . Image from le named Prob06a.
• Figure 2 (p. 1513) . Image from le named Prob06b.
• Figure 3 (p. 1514) . Processed output image.
• Figure 4 (p. 1515) . Required text output.
6.3.2.1.2.1.2 Listings
• Listing 1 (p. 1515) . Modication of the SimplePicture class.
• Listing 2 (p. 1516) . Beginning of the class named Prob06Runner.
• Listing 3 (p. 1517) . The run method.
• Listing 4 (p. 1517) . Beginning of the cropAndFlip method.
• Listing 5 (p. 1518) . Make the pixels partially transparent.
• Listing 6 (p. 1519) . The copyPictureWithCrop method.
• Listing 7 (p. 1521) . Complete program listing.
6.3.2.1.3 Preview
The primary objective of this module is to incorporate alpha transparency into the use of Ericson's media
library.
Two approaches
There are at least two ways to incorporate alpha transparency into Ericson's media library, The easiest
way, which is not necessarily the best way, is to make a relatively simple modication to a constructor in
Ericson's SimplePicture class. That is the approach used in this module.
The second approach
The second approach is more complicated, but does not require the modication of the classes in Ericson's
library. That is probably a better approach due simply to the fact that modications to Ericson's library
are not required. However, that approach is not shown in this module.
Outside research
This program may require a signicant amount of outside research on the part of the student in order to
learn about:
• Alpha transparency
• A buered image of type TYPE_INT_ARGB
• The ability to use Ericson's getBasicPixel and setBasicPixel methods,
• The use of the bitwise AND and OR operators, and
• The use of the drawImage method of the Graphics class.
40 http://cnx.org/content/m44911/latest/Prob06a.jpg
41 http://cnx.org/content/m44911/latest/Prob06b.jpg
• Alpha transparency
Dick Baldwin.
Dick Baldwin
Picture, filename Prob06a.jpg height 118 width 100
Picture, filename Prob06b.jpg height 240 width 320
Picture, filename None height 101 width 77
You must substitute your name for my name wherever my name appears both in the images and on the
command-line screen.
/**
title = "None";
fileName = "None";
extension = "jpg";
setAllPixelsToAColor(Color.white);
}//end constructor
Future Picture objects will accommodate alpha transparency
Having made this modication, future objects instantiated from the SimplePicture class using this
constructor will accommodate alpha transparency. (The SimplePicture class is the superclass of the
Picture class.)
Display the student's name
Note that the constructor in Listing 1 (p. 1515) is also modied to cause it to display the student's name,
which is a requirement of the program.
No complete listing of SimplePicture provided
Because of the simplicity of this modication, a complete listing of the modied SimplePicture class
will not be provided in this module.
class Prob06Runner{
public Prob06Runner(){//constructor
System.out.println("Dick Baldwin.");
}//end constructor
The constructor simply displays the student's name to satisfy one of the requirements of the program.
The run method
The run method, which is called from the main method in Listing 7 (p. 1521) , is shown in its entirety
in Listing 3 (p. 1517) .
copyPictureWithCrop(picC,picB,122,70);
picB.show();
New material
The only thing in Listing 3 (p. 1517) that is new to this module is the pair of calls to the following
methods. I will explain these methods in the paragraphs that follow:
• cropAndFlip
• copyPictureWithCrop
Beginning of the cropAndFlip method
The cropAndFlip method begins in Listing 4 (p. 1517) . This method receives an incoming reference
to a Picture object. It crops the picture to a set of specied coordinate values and ips it around a vertical
line at its center.
width = output.getWidth();
int height = output.getHeight();
pixel = null;
color = null;
for(int col = 0;col < width;col++){
for(int row = 0;row < height;row++){
output.setBasicPixel(col,row,basicPixel);
return output;
}//end crop and flip
According to Ericson's documentation, the getBasicPixel method will "return the pixel value as an
int for the given x and y location." In other words, a call to the getBasicPixel method will return an
int value containing the red, green, blue, and alpha values for the pixel at the specied location.
A bitwise AND operation
Listing 5 (p. 1518) uses a bitwise AND operation (note the single ampersand) to force the eight
most signicant bits (the alpha byte) in the int representation of the current pixel to zero while preserving
the bit values stored in the least signicant 24 bits.
A bitwise OR operation
Then Listing 5 (p. 1518) uses a bitwise OR operation (|) to store the hexadecimal value 5F in the
eight most signicant bits (the alpha byte) without changing the values stored in the 24 least signicant
bits.
The alpha byte
The value of the alpha byte can range from 0 to 255. When rendered using a mechanism that supports
alpha transparency, an alpha value of zero causes the pixel to be totally transparent.
Similarly, an alpha value of 255 causes the pixel to be totally opaque.
Values between zero and 255 cause the pixel to be rendered as partially opaque or partially transparent,
whichever terminology you prefer.
Thirty-seven percent opaque
If I did the arithmetic correctly, a hexadecimal value of 5F represents a decimal value of 95. Therefore,
this value will cause the pixel to be about 37-percent opaque (or 63-percent transparent) .
The setBasicPixel method
As the name implies, the setBasicPixel method can be used to "set the value of a pixel in the picture
from an int."
Therefore, the last statement in the body of the inner loop in Listing 5 (p. 1518) replaces the value of
the current pixel with the modied value containing a value of 95 in the alpha byte.
The end of the cropAndFlip method
When the pair of nested for loops in Listing 5 (p. 1518) terminates, the cropAndFlip method
returns control to the run method in Listing 3 (p. 1517) , returning a copy of the reference from the
variable named output (see Listing 4 (p. 1517) ) in the process.
Save the Picture object's reference
The returned reference is stored in the reference variable named picC in Listing 3 (p. 1517) .
At this point, picC contains a reference to a buttery image that has been cropped, ipped, and
formatted into a buered image that contains alpha transparency information.
Call the copyPictureWithCrop method
Listing 3 (p. copyPictureWithCrop method passing
1517) immediately calls the copies of the
references stored in picC and picB along with a pair of integer coordinate values.
The copyPictureWithCrop method
The copyPictureWithCrop method is shown in its entirety in Listing 6 (p. 1519) .
The purpose of the copyPictureWithCrop method is to copy a source picture onto a destination picture
with an oset on each axis.
An exercise for the student
I won't attempt to explain the code in Listing 6 (p. 1519) in this module. Instead, I will simply suggest
that you go to Google and search for the following or similar keywords:
baldwin java drawImage
You will nd many tutorials that I have written that deal with topics in this area.
Modify the destination pixel colors
drawImage
I will tell you that the use of the method in Listing 6 (p. 1519) modies the destination
picture in such a way that the color of each pixel in the resulting image is a combination of the colors in the
original destination image and the corresponding pixel in the source image.
An illusion of transparency
If a source pixel is totally transparent, it has no eect on the color of the destination pixel.
If the source pixel is totally opaque, the color of the destination pixel is changed to the color of the source
pixel.
For alpha values between these two extremes, the nal color of the destination pixel produces the illusion
of a partially transparent image in front of the original destination image.
Termination of the copyPictureWithCrop method
When the copyPictureWithCrop method terminates in Listing 6 (p. 1519) , control returns to the
run method in Listing 3 (p. 1517) .
show method to display the image in the now-modied Picture object
Listing 3 (p. 1517) calls the
referred to by picB , as shown in Figure 3 (p. 1514) .
Return a reference to an array object
Then the run method encapsulates references to each of the three images in an array object and returns
control to the main method in Listing 7 (p. 1521) , returning a copy of the array object's reference in the
process.
The main method in Listing 7 (p. 1521) displays information about each of the three Picture objects,
producing the output shown in Figure 4 (p. 1515) . Then the main method terminates.
Images don't go away immediately
Because there are images belonging to the program still on the screen, the program doesn't return control
to the operating system. It will simply wait until it is forced to terminate by the user before returning control
to the operating system.
Clicking the X-buttons in the upper-right corners of the images will simply hide the frames and won't
terminate the program. Some extra work is required to deal with this issue.
6.3.2.1.7 Summary
In this module, you learned about:
• Alpha transparency
• A buered image of type TYPE_INT_ARGB
• The ability to use the getBasicPixel and setBasicPixel methods,
• The use of the bitwise AND and OR operators,
You modied the SimplePicture class to cause the buered image used to store the image to be
TYPE_INT_ARGB instead of TYPE_INT_RGB, which is its normal type.
You wrote a method that cropped and ipped an image of a buttery.
You used the getBasicPixel and setBasicPixel methods from Ericson's library along with bitwise
operations to set the alpha value for all the pixels in the cropped and ipped image of the buttery to a
hexadecimal value of 5F.
Finally, you used the standard drawImage method of the Graphics class to draw the image of the
buttery onto an image of a beach with transparency.
6.3.2.1.9 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import java.awt.Graphics;
import java.awt.Image;
class Prob06Runner{
public Prob06Runner(){//constructor
System.out.println("Dick Baldwin.");
}//end constructor
//----------------------------------------------------//
public Picture[] run(){
//Insert executable code here
Picture picA = new Picture("Prob06a.jpg");
picA.explore();
Picture picB = new Picture("Prob06b.jpg");
picB.addMessage("Dick Baldwin.",10,20);
picB.explore();
picB.show();
pixel = output.getPixel(width-col+x1-1,row-y1);
pixel.setColor(color);
}//end inner loop
}//end outer loop
width = output.getWidth();
int height = output.getHeight();
pixel = null;
color = null;
for(int col = 0;col < width;col++){
for(int row = 0;row < height;row++){
return output;
}//end crop and flip
//----------------------------------------------------//
-end-
6.3.2.2.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
43 .
6.3.2.2.2.1.1 Figures
• Figure 1 (p. 1526) . Screen output at startup.
• Figure 2 (p. 1527) . Twenty-percent opacity.
• Figure 3 (p. 1528) . Eighty-percent opacity.
6.3.2.2.2.1.2 Listings
• Listing 1 (p. 1529) . Modication of the SimplePicture class.
• Listing 2 (p. 1530) . Beginning of the class named Prob07Runner.
• Listing 3 (p. 1530) . Beginning of the constructor.
• Listing 4 (p. 1531) . Display the initial image.
• Listing 5 (p. 1531) . Display the buttery at 50-percent opacity.
• Listing 6 (p. 1532) . The setOpacity method.
• Listing 7 (p. 1533) . The drawPictureOnPicture method.
• Listing 8 (p. 1533) . Begin the registration of an event handler on the slider.
• Listing 9 (p. 1534) . Draw the buttery and repaint.
• Listing 10 (p. 1535) . Complete program listing.
6.3.2.2.3 Preview
The primary objective of this module is to illustrate how to use a slider to continuously change the opacity
of an image and to draw that image onto a background image.
Two approaches
This module builds on an earlier module involving transparency. In that module, you learned that there
are at least two ways to incorporate alpha transparency into Ericson's media library, The easiest way, which
is not necessarily the best way, is to make a relatively simple modication to a constructor in Ericson's
SimplePicture class. That is the approach used in this module.
43 http://cnx.org/content/m44148/latest/
• Alpha transparency
• A buered image of type TYPE_INT_ARGB
• The ability to use Ericson's getBasicPixel and setBasicPixel methods,
• The use of the bitwise AND, OR, and left-shift operators.
• The use of the drawImage method of the Graphics class.
• Instantiates a new visual object that extends the JFrame class and contains a JSlider object.
• Instantiates Picture objects from two image les (beach and buttery) along with some blank
Picture objects of the same size.
• Denes a method named setOpacity that can be called to set the opacity of every pixel in a picture
to a specied value.
• Denes a method named drawPictureOnPicture that can be called to draw one picture onto
another picture.
• Registers a ChangeEvent handler on the slider to:
· Extract a percent-opacity value from the slider based on the position of the thumb.
· Apply that opacity value to the buttery image.
· Draw the modied buttery image on the beach image and display it.
44 http://cnx.org/content/m44912/latest/Prob07a.jpg
45 http://cnx.org/content/m44912/latest/Prob07b.jpg
Twenty-percent opacity.
Eighty-percent opacity.
No alpha data
Some of those formats, including the way that information is stored in a SimplePicture object, don't
include an alpha value.
Modication of the SimplePicture class
One way to modify the SimplePicture class to force it to accommodate alpha transparency data is
to modify one of the constructors for the SimplePicture class as shown in Listing 1 (p. 1529) . Note the
change indicated by comments in Listing 1 . (There are probably other ways that you can modify the class
to achieve the same result as well.)
Listing 6.64: Modication of the SimplePicture class.
/**
* A constructor that takes the width and height desired
* for a picture and creates a buffered image of that
* size. This constructor doesn't show the picture.
*/
public SimplePicture(int width, int height){
//Disable the following statement
// bufferedImage = new BufferedImage(
// width, height, BufferedImage.
• background - The beach scene shown in the background in Figure 1 (p. 1526) .
• buttery - Contains an opaque image of the buttery shown in Figure 1 (p. 1526) .
• display - Empty picture the same size as the beach scene.
• tempPicture - Empty picture the same size as the buttery.
In addition, a pair of working variables named image and graphics of the types Image and Graphics
have been declared.
Finally, when the code in Listing 2 (p. 1530) has nished executing, two new JPanel objects and
one new JSlider object have been instantiated and referred to by the variables named mainPanel ,
titlePanel , and slider .
Beginning of the constructor
The beginning of the constructor is shown in Listing 3 (p. 1530) .
public Prob07Runner(){//constructor
//Do some initial setup.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Percent Opacity of Butterfly"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
setSize(backgroundWidth + 7,97);
setLocation(0,backgroundHeight + 25);
setVisible(true);
Although it may be necessary for you to go to Sun's Java documentation to learn about the detailed
behavior of some of the methods that are called in Listing 3 (p. 1530) , the code in Listing 3 (p. 1530) is
straightforward and should not require further explanation.
Display the initial background image
Listing 4 (p. 1531) displays the initial background image.
Instantiating and destroying a lot of new Picture objects as the user moves the slider to change the
opacity would be very inecient. To avoid this ineciency, this program gets images from existing Picture
Picture objects without modifying the originals.
objects and draws them on existing
graphics = display.getGraphics();
graphics.drawImage(background.getImage(),0,0,null);
butterfly = setOpacity(butterfly,50);
drawPictureOnPicture(
butterfly,
display,
backgroundWidth/2 - butterflyWidth/2,
backgroundHeight/2 - butterflyHeight/2);
display.show();
return tempPicture;
}//end setOpacity
This method copies an incoming picture into an existing temporary picture, setting the alpha value for
every pixel to a specied value in the process. Then it returns the modied picture object's reference where
it is saved in the reference variable named buttery in Listing 5 (p. 1531) ,
A bitwise left-shift operation
The only thing in Listing 6 (p. 1532) that is new to this module is the use of a bitwise left-shift operation.
A 24-bit left shift
Listing 6 (p. 1532) converts the incoming percentOpacity value to an integer value ranging from 0
to 255. This value resides in the least signicant eight bits of an int variable named opacity .
Then Listing 6 (p. 1532) applies the bitwise left-shift operator (two left angle brackets) to shift
those eight bits into the eight most signicant bits and stores the result in another int variable named
opacityMask .
Apply the opacityMask to the pixels
A pair of nested for loops is used to set the alpha value of every pixel to the value of opacityMask
using an overall bit-masking methodology that I explained in an earlier module.
The drawPictureOnPicture method
After the alpha value for every pixel in the buttery image has been set to the specied opacity, Listing
5 (p. 1531) calls the method named drawPictureOnPicture to draw the modied buttery image on
the beach scene as shown in Figure 1 (p. 1526) .
The drawPictureOnPicture method is shown in its entirety in Listing 7 (p. 1533) .
This method draws the source picture onto the destination picture with an oset on both axes. There is
nothing in Listing 7 (p. 1533) that I haven't explained in an earlier module.
Return to the explanation of the constructor
You are already familiar with the use of anonymous inner classes to create and register listener objects
on Java source objects. The slider is a source object.
ChangeEvent listener on the slider.
Listing 8 (p. 1533) begins the registration of an anonymous
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
//Draw a new copy of the background on the
// display.
graphics = display.getGraphics();
graphics.drawImage(
background.getImage(),0,0,null);
• Set the opacity of the buttery to the value currently represented by the position of the thumb on the
slider. This is the value returned by the slider's getValue method.
• Draw the buttery image on the background image.
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
//--------------------------------------------------//
}//end constructor
6.3.2.2.7 Summary
In this module, you learned how to use a slider to continuously change the opacity of an image and draw
that image onto a background image.
6.3.2.2.9 Miscellaneous
This section contains a variety of miscellaneous information.
• File: Java3114.htm
• Published: 05/13/12
• Revised: 09/06/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public Prob07Runner(){//constructor
//Do some initial setup.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Percent Opacity of Butterfly"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
setSize(backgroundWidth + 7,97);
setLocation(0,backgroundHeight + 25);
setVisible(true);
return tempPicture;
}//end setOpacity
//----------------------------------------------------//
-end-
6.3.2.3.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
47 .
6.3.2.3.2.1.1 Figures
• Figure 1 (p. 1540) . Contents of the le named Prob08.jpg.
• Figure 2 (p. 1541) . Output images.
6.3.2.3.2.1.2 Listings
• Listing 1 (p. 1542) . Beginning of the class named Prob08Runner.
• Listing 2 (p. 1543) . Beginning of the constructor.
• Listing 3 (p. 1544) . Beginning of the edgeDetector method.
• Listing 4 (p. 1544) . Detect using adjacent pixels in each column.
• Listing 5 (p. 1545) . Register a ChangeEvent listener on the slider.
• Listing 6 (p. 1546) . Complete program listing.
6.3.2.3.3 Preview
An earlier module (see 3D Displays, Color Distance, and Edge Detection 48 ) explained how to implement
an edge detection algorithm for a xed detection threshold.
The primary objective of this module is to illustrate how to use a slider to continuously change the
detection threshold of an edge detector and to draw the edge-detected image on the screen.
Brief program specications
Write a program named Prob08 that uses the class denition for the class named Prob08 shown in
Listing 6 (p. 1546) and Ericson's media library along with the image le named Prob08.jpg
49 (shown in
Figure 1 (p. 1540) ) to produce the two graphic output images shown in Figure 2 (p. 1541) .
47 http://cnx.org/content/m44148/latest/
48 http://www.developer.com/java/other/article.php/3798646/3D-Displays-Color-Distance-and-Edge-Detection.htm
49 http://cnx.org/content/m44913/latest/Prob08.jpg
Output images.
Note that Figure 2 (p. 1541) consists of two separate output images. The image containing the slider is
positioned directly below the image of the buttery.
New classes
You may dene new classes as necessary to cause your program to behave as required, but you may not
modify the class denition for the class named Prob08 given in Listing 6 (p. 1546) .
The output images
The top image shown in Figure 2 (p. 1541) is an image of a buttery to which an edge detection algorithm
has been applied.
The bottom image in Figure 2 (p. 1541) is a slider that is used to control the edge-detection threshold.
Detect by rows and by columns
The edge-detection algorithm performs edge detection on a Picture object by rows and also by columns.
All edges that are detected by processing adjacent pixels on a row are marked in red. All edges that are
detected by processing adjacent pixels on a column are marked in black.
If a pixel is determined to be on an edge using both approaches, it ends up being black. If an edge is not
detected, the corresponding pixel is marked in white.
Program behavior
At startup, the thumb on the slider is positioned at the 50-percent mark and the image has been edge-
detected using a threshold value of 50.
As you move the slider to the right, the threshold value increases up to a value of 100, which in turn
causes the amount of white area in the image to increase.
As you move the slider to the left, the threshold value decreases down to a value of zero, which in turn
causes the amount of white area in the image to decrease.
The program must terminate and return control to the operating system when you click the large X in
the upper-right corner of the GUI containing the slider.
In addition to the output images described above, your program must display your name on the command-
line screen.
There is nothing in Listing 1 (p. 1542) that I haven't explained in earlier modules, so I won't repeat those
explanations here.
Beginning of the constructor
The constructor begins in Listing 2 (p. 1543) .
public Prob08Runner(){//constructor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Edge Detection Threshold"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
setSize(butterflyWidth + 7,97);
setLocation(0,butterflyHeight + 25);
setVisible(true);
display.show();
50 http://www.developer.com/java/other/article.php/3798646/3D-Displays-Color-Distance-and-Edge-Detection.htm
return display;
}//end edgeDetector
If an edge is detected in Listing 4 (p. 1544) , the color of the corresponding pixel in the output picture is
set to black.
Return the output picture and terminate
The edgeDetector method returns a reference to the output picture and terminates in Listing 4 (p.
1544) .
(While writing this, I realized that because the variable named display is an instance variable, the
program would also work properly if the edgeDetector method were to return void.)
Returning to the constructor...
show method is called on the output picture
Returning to where we left o in Listing 2 (p. 1543) , the
display causing an image similar to that shown in Figure 2 (p. 1541) to be displayed.
referred to by
Register a ChangeEvent listener on the slider
Listing 5 (p. 1545) registers an anonymous listener object on the slider. Each time the slider res a
ChangeEvent , the method named stateChanged is executed.
Listing 6.78: Register a ChangeEvent listener on the slider.
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
display = edgeDetector(
butterfly,slider.getValue());
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
//----------------------------------------------//
}//end constructor
//------------------------------------------------//
}//end class Prob08Runner
6.3.2.3.6 Summary
In this module, you learned how to use a slider to continuously change the threshold detection level of an
edge detector and to draw the edge-detected image on the screen.
6.3.2.3.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
*********************************************************/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.BorderLayout;
import java.awt.Color;
public Prob08Runner(){//constructor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
getContentPane().add(mainPanel);
setSize(butterflyWidth + 7,97);
setLocation(0,butterflyHeight + 25);
setVisible(true);
display.show();
//--------------------------------------------------//
//Register an anonymous listener object on the slider.
//Each time the slider fires a ChangeEvent, this event
// handler calls the edgeDetector method to get a new
// edge-detected image for which the threshold is the
// current value of the slider. Then the display is
// repainted showing the new image.
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
display = edgeDetector(
butterfly,slider.getValue());
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
//--------------------------------------------------//
}//end constructor
//----------------------------------------------------//
/*This method performs edge detection on a Picture
*object by rows and also by columns.
*All edges that are detected by processing adjacent
*pixels on a row are marked in red.
*All edges that are detected by processing adjacent
*pixels on a column are marked in black.
*If a pixel is determined to be on an edge using both
*approaches, it ends up being black.
*/
pix1 = picture.getPixel(col,row);
displayPixel = display.getPixel(col,row);
return display;
}//end edgeDetector
}//end class Prob08Runner
-end-
6.3.2.4.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
52 .
6.3.2.4.2.1.1 Figures
• Figure 1 (p. 1551) . Prob09a.jpg.
• Figure 2 (p. 1552) . Prob09b.jpg.
• Figure 3 (p. 1553) . Output images.
6.3.2.4.2.1.2 Listings
• Listing 1 (p. 1554) . Register a listener object on the slider.
• Listing 2 (p. 1554) . The method named drawScaledPictureOnPicture.
• Listing 3 (p. 1556) . Complete program listing.
6.3.2.4.3 Preview
The primary objective of this module is to illustrate how to use a slider to continuously change the size of
an image and to draw the scaled image onto a background image.
Brief program specications
Write a program named Prob09 that uses the class denition for the class named Prob09 shown in
Listing 3 (p. 1556) and Ericson's media library along with the image les named Prob09a.jpg
53 (see Figure
1 (p. 1551) ) and Prob09b.jpg
54 (see Figure 2 (p. 1552) ) to produce the graphic output images shown
in Figure 3 (p. 1553) .
52 http://cnx.org/content/m44148/latest/
53 http://cnx.org/content/m44914/latest/Prob09a.jpg
54 http://cnx.org/content/m44914/latest/Prob09b.jpg
Prob09a.jpg.
Prob09b.jpg.
Output images.
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
drawScaledPictureOnPicture(beach,
display,
slider.getValue());
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
null
6.3.2.4.7 Summary
In this module, you learned how to use a slider to continuously change the size of an image and to draw the
scaled image onto a background image.
6.3.2.4.9 Miscellaneous
This section contains a variety of miscellaneous information.
56 http://www.dickbaldwin.com/java/Java358.htm
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
*********************************************************/
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
/*------------------------------------------------------//
*********************************************************/
class Prob09Runner extends JFrame{
public Prob09Runner(){//constructor
System.out.println("Dick Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
beach.addMessage("Dick Baldwin",10,20);
butterfly.addMessage("Dick Baldwin",10,20);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Percent Size of Beach Image"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
//pack();
setSize(beachWidth + 7,97);
setTitle("Dick Baldwin");
setLocation(0,beachHeight + 25);
setVisible(true);
graphics.drawImage(butterfly.getImage(),0,0,null);
display.show();
//--------------------------------------------------//
//Register an anonymous listener object on the slider.
//Each time the slider fires a ChangeEvent, this event
// handler restores the background image of the
// butterfly. Then it draws a scaled version of the
// beach on top of the background image using the
// slider value, which ranges from 0 to 100 as the
// scale factor as a percent of 1.0. The image of the
// beach is always aligned with the center
// of the contentPane of the JFrame.
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
drawScaledPictureOnPicture(beach,
display,
slider.getValue());
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
//--------------------------------------------------//
}//end constructor
//----------------------------------------------------//
g2 = (Graphics2D)dest.getGraphics();
-end-
6.3.2.5 Java OOP: Controlling Image Rotation with a Slider and Ane Transforms57
6.3.2.5.1 Table of Contents
• Preface (p. 1559)
6.3.2.5.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
58 .
6.3.2.5.2.1.1 Figures
• Figure 1 (p. 1561) . Program output at startup.
• Figure 2 (p. 1563) . Program output for slider at zero.
• Figure 3 (p. 1565) . Program output for slider at 240.
6.3.2.5.2.1.2 Listings
• Listing 1 (p. 1566) . Beginning of the class named Prob10Runner.
• Listing 2 (p. 1567) . Beginning of the constructor for the Prob10Runner class.
• Listing 3 (p. 1567) . Construct the GUI for the slider.
• Listing 4 (p. 1568) . Rotate and display the buttery.
• Listing 5 (p. 1568) . Register a ChangeListener on the slider.
• Listing 6 (p. 1569) . Beginning of the rotatePicture method.
• Listing 7 (p. 1570) . Set up the translation transform.
• Listing 8 (p. 1570) . Concatenate the transforms.
• Listing 9 (p. 1570) . Transform and draw the buttery image.
• Listing 10 (p. 1571) . Complete program listing.
6.3.2.5.3 Preview
In this lecture, I will explain a program that uses Ane Transforms to rotate an image by a specied
angle around a specied anchor point.
Then the program translates the image so as to center it in a JFrame object.
Specication of the rotation angle
A JSlider is used to specify the rotation angle.
The range of the slider is from 0 to 360 degrees.
The position of the thumb on the slider species a counter-clockwise rotation angle in degrees.
Program output at startup
The thumb on the slider is at 45 degrees when the program starts running.
This causes the initial rotation angle of the buttery image to be 45 degrees counter-clockwise as shown
in Figure 1 (p. 1561) .
public Prob10Runner(){//constructor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Rotation Angle in Degrees"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
pack();//Adjust the size of the slider GUI.
rotatePicture(slider.getValue());
display.show();
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
//Restore the background image of the display
// to all white.
graphics = display.getGraphics();
graphics.drawImage(
background.getImage(),0,0,null);
Each time the slider res a ChangeEvent , the stateChanged method in Listing 5 (p. 1568) is
executed.
The stateChanged method begins by restoring the background image of thedisplay.
Then the stateChanged method calls the rotatePicture method to draw a rotated version of
thebuttery on top of the background image using theslider value, (which ranges from 0 to +360) , asthe
rotation angle in degrees.
The image of thebuttery (see Figure 1 (p. 1561) ) is always centered in the displaypicture.
Finally, the stateChanged method causes the display to be repainted to force the rotated image to
appear on the screen.
End of the constructor
Listing 5 (p. 1568) signals the end of the constructor for the class named Prob10Runner .
Beginning of the rotatePicture method
The rotatePicture method begins in Listing 6 (p. 1569) .
The code in Listing 6 (p. 1569) applies a minus sign to convert the angle from a positive value to a
negative value forcounter-clockwise rotation, and passes that value as the rotation parameter.
Specify the rotation anchor point
Listing 6 (p. 1569) also species the center of the buttery image as the anchor point.
Set up the translation transform
Listing 7 (p. 1570) sets up the translation transform that will be used to translate the rotated image to
the center of the new Picture object.
Listing 6.89: Set up the translation transform.
translateTransform.concatenate(rotateTransform);
Graphics2D g2 = (Graphics2D)display.getGraphics();
g2.drawImage(butterfly.getImage(),
translateTransform,
null);
}//end rotatePicture
6.3.2.5.6 Summary
In this lecture, you learned how to use a JSlider object along with Ane Transforms to control the
rotation of an image.
6.3.2.5.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
*********************************************************/
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public Prob10Runner(){//constructor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel.setLayout(new BorderLayout());
titlePanel.add(new JLabel(
"Rotation Angle in Degrees"));
mainPanel.add(titlePanel,BorderLayout.NORTH);
mainPanel.add(slider,BorderLayout.CENTER);
getContentPane().add(mainPanel);
pack();//Adjust the size of the slider GUI.
rotatePicture(slider.getValue());
display.show();
//--------------------------------------------------//
//Register an anonymous listener object on the slider.
//Each time the slider fires a ChangeEvent, this event
// handler restores the background image of the
// display. Then it draws a rotated version of the
// butterfly on top of the background image using the
// slider value, which ranges from 0 to +360, as
// the rotation angle in degrees. The image of the
// butterfly is always centered in the display
// picture.
slider.addChangeListener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
//Restore the background image of the display
// to all white.
graphics = display.getGraphics();
graphics.drawImage(
background.getImage(),0,0,null);
//Rotate the butterfly image, draw it on the
// display, and repaint the display on the
// screen..
rotatePicture(slider.getValue());
display.repaint();
}//end stateChanged
}//end new ChangeListener
);//end addChangeListener
//--------------------------------------------------//
}//end constructor
//----------------------------------------------------//
translateTransform.translate(
(displayWidth - butterflyWidth)/2,
(displayHeight - butterflyHeight)/2);
}//end rotatePicture
-end-
6.3.3 Part 3
6.3.3.1 Java OOP: Opening an Image File in a PictureExplorer Object62
6.3.3.1.1 Table of Contents
• Preface (p. 1575)
6.3.3.1.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
63 .
6.3.3.1.2.1.1 Figures
• Figure 1 (p. 1576) . Program output at startup.
• Figure 2 (p. 1577) . Screen shot after the image is loaded.
6.3.3.1.2.1.2 Listings
• Listing 1 (p. 1578) . Complete program listing.
• Listing 2 (p. 1579) . The driver class.
• Listing 3 (p. 1580) . Beginning of the Prob11Runner class.
• Listing 4 (p. 1580) . Beginning of the constructor.
• Listing 5 (p. 1581) . Beginning of anonymous listener class.
• Listing 6 (p. 1581) . Completion of the anonymous listener class.
6.3.3.1.3 Preview
This program demonstrates how to specify an image le in a text eld, and open the image in a new
PictureExplorer object.
Program output at startup
Figure 1 (p. 1576) shows the program output at startup.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.WindowConstants;
public Prob11Runner(){//constructor
fileNamePanel.add(new JLabel("File name: "));
fileNamePanel.add(inputFileNameField);
//--------------------------------------------------//
//Register listeners on the user input field.
//--------------------------------------------------//
inputFileNameField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
fileName = inputFileNameField.getText();
public Prob11Runner(){//constructor
fileNamePanel.add(new JLabel("File name: "));
fileNamePanel.add(inputFileNameField);
inputFileNameField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
fileName = inputFileNameField.getText();
setLocation(0,pix.getHeight() + 128);
jFrameObj.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
}//end action performed
}//end newActionListener
);//end addActionListener
//--------------------------------------------------//
}//end constructor
//----------------------------------------------------//
}//end class Prob11Runner
Relocate the GUI
Listing 6 (p. 1581) begins by setting the location of the GUI to a location that is immediately below the
PictureExplorer object.
Relocate the GUI (cont'd)
Note that the value of 128 pixels was experimentally determined to be the approximate dierence between
the height of the PictureExplorer object and the height of the Picture object that it encapsulates.
(This dierence may not be correct for dierent display options on dierent operating systems.)
Set the default close operation
Listing 6 (p. 1581) ends by setting the behavior of the X-button in the GUI to a value that will cause it
to terminate the program when the button is clicked.
6.3.3.1.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.3.3.2 Java OOP: Extracting pixel color data from a PictureExplorer object65
6.3.3.2.1 Table of Contents
• Preface (p. 1583)
64 http://cnx.org/content/m44916/latest/Prob11a.jpg
65 This content is available online at <http://cnx.org/content/m44917/1.2/>.
6.3.3.2.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
66 .
6.3.3.2.2.1.1 Figures
• Figure 1 (p. 1584) . Program output at startup.
• Figure 2 (p. 1586) . Program output after clicking the button.
6.3.3.2.2.1.2 Listings
• Listing 1 (p. 1587) . Addition of getter methods.
• Listing 2 (p. 1587) . Disabled the call to setDefaultCloseOperation method.
• Listing 3 (p. 1588) . The driver class for Prob12.
• Listing 4 (p. 1588) . Beginning of the class named Prob12Runner.
• Listing 5 (p. 1588) . Beginning of the constructor.
• Listing 6 (p. 1589) . Construct a Picture object.
• Listing 7 (p. 1589) . Construct a PictureExplorer object.
• Listing 8 (p. 1589) . Set the size and location of the GUI control panel.
• Listing 9 (p. 1590) . Register a listener object on the button.
• Listing 10 (p. 1591) . Prob12.java.
• Listing 11 (p. 1594) . Modied PictureExplorer.java.
6.3.3.2.3 Preview
In this module, I will show you how to extract color data from a selected pixel in a PictureExplorer
object, and how to display the value in a text eld.
I will also show you how to disable the X-button in the PictureExplorer object, and how to get
JFrame
and use a reference to the PictureExplorer object.
object that serves as a container for the
Program output at startup
Figure 1 (p. 1584) shows a screen shot of the program output at startup.
Note that the text eld in the red panel near the bottom contains all zeros.
66 http://cnx.org/content/m44148/latest/
• I added a getter method to cause the red color value to be accessible from outside the PictureEx-
plorer object.
• I added a getter method that returns a reference to the JFrame object containing the Picture-
Explorer object.
• I disabled the call to the setDefaultCloseOperation method for the PictureExplorer object.
No more modications
That concludes the discussion of modications to Ericson's PictureExplorer source code.
The driver class named Prob12
The driver class is shown in Listing 3 (p. 1588) .
There is nothing new here.
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.RED);
colorPanel.add(new JLabel(
"Red pixel Color at Cursor: "));
colorPanel.add(redField);
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(getDataButton);
getContentPane().add(controlPanel);
setTitle("Dick Baldwin");
setVisible(true);
explorerFrame = explorer.getFrame();
explorerFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
Listing 6.106: Set the size and location of the GUI control panel.
JFrame
Note that it isn't necessary to guess about the actual height of the as was the case in an earlier
module. The reference to the JFrame object provides that information.
Set the default close operation for the control GUI
Finally, Listing 8 (p. 1589) sets the default close operation on the control GUI to cause the program to
terminate when the user clicks the X-button on the GUI.
Register a listener object on the button
ActionListener object on the button to cause it to call the Pic-
Listing 9 (p. 1590) registers an
tureExplorer object's new getRValue method to get the red color value for the pixel at the current
PictureExplorer crosshair cursor position, and to display that value in the text eld as shown in Figure
2 (p. 1586) when the user clicks the button.
getDataButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
redField.setText(explorer.getRValue());
}//end constructor
}//end class Prob12Runner
67 http://cnx.org/content/m44917/latest/Prob12.jpg
6.3.3.2.6 Summary
You learned how to extract color data from a selected pixel in a PictureExplorer object, and to display
the value in a text eld.
You also learned how to disable the X-button in the PictureExplorer object, and how to use a
reference to the JFrame object that serves as a container for the PictureExplorer object.
6.3.3.2.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import java.awt.Color;
public Prob12Runner(){//constructor
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.RED);
colorPanel.add(new JLabel(
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(getDataButton);
getContentPane().add(controlPanel);
setTitle("Dick Baldwin");
setVisible(true);
//--------------------------------------------------//
//Register a listener object on the button.
//--------------------------------------------------//
getDataButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
redField.setText(explorer.getRValue());
}//end constructor
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
import javax.swing.border.*;
/*
05/15/12
Modified by Baldwin to add getter methods to cause
the following values to be accessible from outside the
PictureExplorer object:
/**
* Displays a picture and lets you explore the picture by displaying the x, y, red,
* green, and blue values of the pixel at the cursor when you click a mouse button or
* press and hold a mouse button while moving the cursor. It also lets you zoom in or
* out. You can also type in a x and y value to see the color at that location.
*
* Originally created for the Jython Environment for Students (JES).
* Modified to work with DrJava by Barbara Ericson
*
* Copyright Georgia Institute of Technology 2004
* @author Keith McDermottt, gte047w@cc.gatech.edu
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class PictureExplorer implements MouseMotionListener, ActionListener, MouseListener
{
// menu components
private JMenuBar menuBar;
private JMenu zoomMenu;
private JMenuItem twentyFive;
private JMenuItem fifty;
private JMenuItem seventyFive;
private JMenuItem hundred;
private JMenuItem hundredFifty;
private JMenuItem twoHundred;
private JMenuItem fiveHundred;
/**
* Public constructor
* @param picture the picture to explore
*/
public PictureExplorer(DigitalPicture picture)
{
// set the fields
this.picture=picture;
zoomFactor=1;
/**
* Changes the number system to start at one
*/
public void changeToBaseOne()
{
numberBase=1;
}
/**
* Set the title of the frame
*@param title the title to use in the JFrame
*/
public void setTitle(String title)
{
pictureFrame.setTitle(title);
}
/**
* Method to create and initialize the picture frame
*/
private void createAndInitPictureFrame()
{
pictureFrame = new JFrame(); // create the JFrame
pictureFrame.setResizable(true); // allow the user to resize it
pictureFrame.getContentPane().setLayout(new BorderLayout()); // use border layout
pictureFrame.setTitle(picture.getTitle());
PictureExplorerFocusTraversalPolicy newPolicy = new PictureExplorerFocusTraversalPolicy();
pictureFrame.setFocusTraversalPolicy(newPolicy);
/**
* Method to create the menu bar, menus, and menu items
*/
private void setUpMenuBar()
{
//create menu
menuBar = new JMenuBar();
zoomMenu = new JMenu("Zoom");
twentyFive = new JMenuItem("25%");
fifty = new JMenuItem("50%");
seventyFive = new JMenuItem("75%");
hundred = new JMenuItem("100%");
hundred.setEnabled(false);
hundredFifty = new JMenuItem("150%");
twoHundred = new JMenuItem("200%");
fiveHundred = new JMenuItem("500%");
/**
* Create and initialize the scrolling image
*/
private void createAndInitScrollingImage()
{
/**
* Creates the JFrame and sets everything up
*/
private void createWindow()
{
// create the picture frame and initialize it
createAndInitPictureFrame();
/**
* Method to set up the next and previous buttons for the
* pixel location information
*/
private void setUpNextAndPreviousButtons()
{
// create the image icons for the buttons
Icon prevIcon = new ImageIcon(SoundExplorer.class.getResource("leftArrow.gif"),
"previous index");
Icon nextIcon = new ImageIcon(SoundExplorer.class.getResource("rightArrow.gif"),
"next index");
// create the arrow buttons
xPrevButton = new JButton(prevIcon);
xNextButton = new JButton(nextIcon);
yPrevButton = new JButton(prevIcon);
yNextButton = new JButton(nextIcon);
/**
* Create the pixel location panel
* @param labelFont the font for the labels
* @return the location panel
*/
public JPanel createLocationPanel(Font labelFont) {
// add the items to the vertical box and the box to the panel
hBox.add(Box.createHorizontalGlue());
hBox.add(xLabel);
hBox.add(xPrevButton);
hBox.add(xValue);
hBox.add(xNextButton);
hBox.add(Box.createHorizontalStrut(10));
hBox.add(yLabel);
hBox.add(yPrevButton);
hBox.add(yValue);
hBox.add(yNextButton);
locationPanel.add(hBox);
hBox.add(Box.createHorizontalGlue());
return locationPanel;
}
/**
* Create the color information panel
* @param labelFont the font to use for labels
* @return the color information panel
*/
colorInfoPanel.add(colorLabel);
colorInfoPanel.add(colorPanel);
return colorInfoPanel;
}
/**
* Creates the North JPanel with all the pixel location
* and color information
*/
private void createInfoPanel()
{
// create the info panel and set the layout
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BorderLayout());
/**
* Method to check that the current position is in the viewing area and if
* not scroll to center the current position if possible
*/
public void checkScroll()
{
// get the x and y position in pixels
int xPos = (int) (xIndex * zoomFactor);
int yPos = (int) (yIndex * zoomFactor);
// calculate how to position the current position in the middle of the viewing
// area
int viewX = xPos - (int) (rectWidth / 2);
int viewY = yPos - (int) (rectHeight / 2);
/**
* Zooms in the on picture by scaling the image.
* It is extremely memory intensive.
* @param factor the amount to zoom by
*/
public void zoom(double factor)
{
// save the current zoom factor
zoomFactor = factor;
// calculate the new width and height and get an image that size
int width = (int) (picture.getWidth()*zoomFactor);
int height = (int) (picture.getHeight()*zoomFactor);
BufferedImage bimg = picture.getBufferedImage();
/**
* Repaints the image on the scrollpane.
*/
public void repaint()
{
pictureFrame.repaint();
}
//****************************************//
// Event Listeners //
//****************************************//
/**
* Called when the mouse is dragged (button held down and moved)
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method to check if the given x and y are in the picture
* @param x the horiztonal value
* @param y the vertical value
* @return true if the x and y are in the picture and false otherwise
*/
private boolean isLocationInPicture(int x, int y)
{
boolean result = false; // the default is false
if (x >= 0 && x < picture.getWidth() &&
y >= 0 && y < picture.getHeight())
result = true;
return result;
}
/**
* Method to display the pixel information from the passed x and y but
* also converts x and y from strings
* @param xString the x value as a string from the user
* @param yString the y value as a string from the user
*/
public void displayPixelInformation(String xString, String yString)
{
int x = -1;
int y = -1;
try {
x = Integer.parseInt(xString);
x = x - numberBase;
y = Integer.parseInt(yString);
y = y - numberBase;
} catch (Exception ex) {
}
/**
* Method to display pixel information for the passed x and y
* @param pictureX the x value in the picture
* @param pictureY the y value in the picture
*/
private void displayPixelInformation(int pictureX, int pictureY)
{
// check that this x and y is in range
if (isLocationInPicture(pictureX, pictureY))
{
// save the current x and y index
xIndex = pictureX;
yIndex = pictureY;
}
else
{
clearInformation();
}
/**
* Method to display pixel information based on a mouse event
* @param e a mouse event
*/
/**
* Method to clear the labels and current color and reset the
* current index to -1
*/
private void clearInformation()
{
xValue.setText("N/A");
yValue.setText("N/A");
rValue.setText("R: N/A");
gValue.setText("G: N/A");
bValue.setText("B: N/A");
colorPanel.setBackground(Color.black);
xIndex = -1;
yIndex = -1;
}
/**
* Method called when the mouse is moved with no buttons down
* @param e the mouse event
*/
public void mouseMoved(MouseEvent e)
{}
/**
* Method called when the mouse is clicked
* @param e the mouse event
*/
public void mouseClicked(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method called when the mouse button is pushed down
* @param e the mouse event
*/
public void mousePressed(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method called when the mouse button is released
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e)
{
}
/**
* Method called when the component is entered (mouse moves over it)
* @param e the mouse event
*/
public void mouseEntered(MouseEvent e)
{
}
/**
* Method called when the mouse moves over the component
* @param e the mouse event
*/
public void mouseExited(MouseEvent e)
{
}
/**
* Method to enable all menu commands
*/
private void enableZoomItems()
{
twentyFive.setEnabled(true);
fifty.setEnabled(true);
seventyFive.setEnabled(true);
hundred.setEnabled(true);
hundredFifty.setEnabled(true);
twoHundred.setEnabled(true);
fiveHundred.setEnabled(true);
}
/**
* Controls the zoom menu bar
*
* @param a the ActionEvent
*/
public void actionPerformed(ActionEvent a)
{
if(a.getActionCommand().equals("Update"))
{
this.repaint();
}
if(a.getActionCommand().equals("25%"))
{
this.zoom(.25);
enableZoomItems();
twentyFive.setEnabled(false);
}
if(a.getActionCommand().equals("50%"))
{
this.zoom(.50);
enableZoomItems();
fifty.setEnabled(false);
}
if(a.getActionCommand().equals("75%"))
{
this.zoom(.75);
enableZoomItems();
seventyFive.setEnabled(false);
}
if(a.getActionCommand().equals("100%"))
{
this.zoom(1.0);
enableZoomItems();
hundred.setEnabled(false);
}
if(a.getActionCommand().equals("150%"))
{
this.zoom(1.5);
enableZoomItems();
hundredFifty.setEnabled(false);
}
if(a.getActionCommand().equals("200%"))
{
this.zoom(2.0);
enableZoomItems();
twoHundred.setEnabled(false);
}
if(a.getActionCommand().equals("500%"))
{
this.zoom(5.0);
enableZoomItems();
fiveHundred.setEnabled(false);
}
}
/**
* Test Main. It will ask you to pick a file and then show it
*/
public static void main( String args[])
{
Picture p = new Picture(FileChooser.pickAFile());
PictureExplorer test = new PictureExplorer(p);
/**
* Class for establishing the focus for the textfields
*/
private class PictureExplorerFocusTraversalPolicy
extends FocusTraversalPolicy {
/**
* Method to get the next component for focus
*/
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(xValue))
return yValue;
else
return xValue;
}
/**
* Method to get the previous component for focus
*/
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(xValue))
return yValue;
else
return xValue;
}
-end-
6.3.3.3 Java OOP: Handling document events on a text eld and creating a color swatch68
6.3.3.3.1 Table of Contents
• Preface (p. 1610)
6.3.3.3.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
6.3.3.3.2.1.1 Figures
• Figure 1 (p. 1611) . Program output at startup.
• Figure 2 (p. 1612) . Program output after clicking the button.
• Figure 3 (p. 1612) . Program output after entering color values.
6.3.3.3.2.1.2 Listings
• Listing 1 (p. 1613) . The driver class.
• Listing 2 (p. 1613) . Beginning of the class named Prob13Runner.
• Listing 3 (p. 1614) . Beginning of constructor for Prob13Runner.
• Listing 4 (p. 1614) . Continue the constructor.
• Listing 5 (p. 1615) . Register a listener object on the button.
• Listing 6 (p. 1616) . Beginning of DocumentListener on Red text eld.
• Listing 7 (p. 1616) . The removeUpdate method.
6.3.3.3.3 Preview
In this module, I will show you how to handle document events on text elds containing color values.
I will also show you how to create a color swatch that displays the color indicated by the color values in
the Red, Green, and Blue text elds.
Program output at startup
Figure 1 (p. 1611) shows the program output at startup.
Note that the color values in the Red, Green, and Blue text elds are all zero, the color of the square at
the right end of the Green panel is black.
Recall that black is represented by Red, Green, and Blue color values of zero.
• the color values in the Red and Blue text elds are zero,
• the color value in the Green text eld is 255,
• the square (color swatch) at the right end of the green panel is green with a black outline
• the square is not transparent.
Recall that pure green is represented by Red and Blue color values of zero, with a Green color value of 255.
Program output after entering color values
Figure 3 (p. 1612) shows the program output after manually entering a value of 255 in the Red text eld.
Note that
• the color values in the Red and Green text elds are 255,
• the color value in the Blue text eld is 0, and
• the square at the right end of the green panel is yellow with a black outline.
Recall that pure yellow is represented by Red and Green color values of 255, with a Blue color value of zero.
Color of square tracks color values in text elds
The square (color swatch) always has a black outline as shown in Figure 3 (p. 1612) .
The color in the swatch always tracks the color values in the text elds regardless of whether those values
are changed manually, or they are changed by program code.
The last two statements in Listing 3 (p. 1614) control the border color, and the size of the JPanel
(color swatch) object.
public Prob13Runner(){//constructor
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(setColorButton);
One component is the button at the bottom of Figure 3 (p. 1612) labeled Set Green Color.
The other three components are the three text elds labeled Red , Green , and Blue shown in
Figure 3 (p. 1612) .
The three event listeners that are registered on the text elds are very similar. Therefore, I will explain
only one of them. You can view the code for the other two in Listing 10 (p. 1618) .
Register a listener object on the button
Listing 5 (p. 1615) registers an ActionListener object on the JButton object referred to by setCol-
orButton .
You have seen code like this in numerous previous modules. Therefore, a detailed explanation of Listing
5 (p. 1615) should not be required here.
setColorButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set the color to green.
redInt = 0;
greenInt = 255;
blueInt = 0;
• changedUpdate
· Gives notication that an attribute or set of attributes changed.
• insertUpdate
· Gives notication that there was an insert into the document.
• removeUpdate
· Gives notication that a portion of the document has been removed.
Only theinsertUpdate and removeUpdate methods are of interest in this program. Therefore, the
changedUpdate method will be implemented as an empty method.
Beginning of DocumentListener
Listing 6 (p. 1616) shows the beginning of the denition, instantiation, and registration of a Doc-
umentListener object on the object of type Document that is encapsulated in the Red text eld.
redField.getDocument().addDocumentListener(
new DocumentListener(){
Note that registration of the listener object in this case has an additional level of indirection (getDocument)
as compared to the registration of the listener on the JButton in Listing 5 (p. 1615) . In other words, the
listener is not registered on the text eld. Instead, it is registered on the document encapsulated in the text
eld.
This listener will respond when the contents of the text eld are modied, either by the program, or by
the user.
(As explained earlier, the changedUpdate method is dened as an empty method.)
The removeUpdate method
Listing 7 (p. 1616) shows the removeUpdate method in its entirety.
The paintColorSwatch method sets the background color for the JPanel object that represents the
color swatch, using values of red, green, and blue that are computed elsewhere in the program.
The end of the program
Listing 9 (p. 1617) also signals the end of the class named Prob13Runner and the end of the program.
6.3.3.3.6 Summary
In this lesson, you learned how to handle document events on text elds containing color values. You also
learned how to create a color swatch.
6.3.3.3.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
public Prob13Runner(){//constructor
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(setColorButton);
//--------------------------------------------------//
//Register listeners on the user input components.
//--------------------------------------------------//
setColorButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set the color to green.
redInt = 0;
greenInt = 255;
blueInt = 0;
greenField.getText());
if((greenInt >= 0) && (greenInt <= 255))
{
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end removeUpdate
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
-end-
6.3.3.4.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
6.3.3.4.2.1.1 Figures
• Figure 1 (p. 1625) . Program output at startup.
• Figure 2 (p. 1626) . Program output after clicking the Choose Color button.
• Figure 3 (p. 1627) . Program output after selecting a reddish color and clicking the OK button.
• Figure 4 (p. 1627) . Program output after clicking the Darker button.
• Figure 5 (p. 1629) . The showDialog method.
6.3.3.4.2.1.2 Listings
• Listing 1 (p. 1628) . Event handler for the Choose Color button.
• Listing 2 (p. 1628) . Show the JColorChooser object.
• Listing 3 (p. 1630) . Darkening the color.
• Listing 4 (p. 1631) . Complete program listing.
6.3.3.4.3 Preview
In this module, you will learn how to use a JColorChooser object to specify a color in any one of ve
dierent ways:
• Swatches
• HSV
• HSL
• RGB
• CMYK
The details regarding the ve dierent ways are not explained. Instead, an understanding of the ve ways
for specifying a color is left as an exercise for the student.
This module concentrates on the programming aspects of the color chooser as opposed to the aesthetic
aspects of the color chooser.
You will also learn how to create brighter and darker shades of a given color.
What is a JColorChooser object?
According to the Java documentation,
"JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color."
Program output at startup
A complete listing of the program discussed in this module is provided in Listing 4 (p. 1631) near the
end of the module.
Figure 1 (p. 1625) shows the program output at startup.
The program output is a GUI containing
• three text elds, one each for red, green, and blue color values
• three labels that identify the contents of each text eld
• a button labeled Choose Color
• two buttons labeled Brighter and Darker
• a square color swatch whose color reects the color specied by the color component values in
the text elds
Figure 6.39: Program output after clicking the Choose Color button.
Program output after selecting a reddish color and clicking the OK button.
Figure 6.40: Program output after selecting a reddish color and clicking the OK button.
• the color selected in the color chooser now appears in the square color swatch in Figure 3 (p. 1627)
• the color swatch in Figure 3 (p. 1627) has a black border
• the color values in the three text elds describe the color showing in the swatch
(The color in the swatch is based on the three color values in the text elds.)
Program output after clicking the Darker button.
Darker
Figure 4 (p. 1627) shows the result of clicking the button once.
A darker color
The color swatch in Figure 4 (p. 1627) shows a darker version of the color swatch shown in Figure 3 (p.
1627) .
The numeric color values in Figure 4 (p. 1627) describe the color in the color swatch, and are lower than
the corresponding color values in Figure 3 (p. 1627)
A brighter color
Although not demonstrated here, the color in the swatch could be made brighter by clicking the Brighter
button.
If you click the Darker button enough times, the color will go to black. Similarly, if you click the
Brighter button enough times, the color will go to white.
chooseButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Color selColor = JColorChooser.showDialog(
chooseButton,"Choose color",new Color(
redInt,greenInt,blueInt));
if(selColor != null){
//Don't change the color if the user cancels
// out.
redField.setText("" + selColor.getRed());
greenField.setText("" + selColor.getGreen());
blueField.setText("" + selColor.getBlue());
}//end if
Parameters:
component - the parent Component for the dialog
title - the String containing the dialog's title
initialColor - the initial Color set when the
color-chooser is shown
Returns:
the selected color or null if the user opted out
A straightforward explanation
The behavior of the dialog is explained in Figure 5 (p. 1629) and shouldn't require further explanation.
Parameters to the showDialog method
A comparison of Listing 2 (p. 1628) and Figure 5 (p. 1629) shows how the color chooser is integrated
into the program.
Perhaps the most important aspects of that integration are the third parameter and the return value
.
The third parameter
The third parameter is an anonymous Color object that matches the color specied by the text elds
in the GUI, which determine the color of the swatch.
Thus, the initial color for the color chooser matches the color of the swatch in the GUI when the color
chooser rst appears.
The return value
The return value from the color chooser is a reference to an object of type Color , which is saved in a
variable named selColor .
Processing the return value
darkerButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Color color = new Color(
redInt,greenInt,blueInt).darker();
redField.setText("" + color.getRed());
greenField.setText("" + color.getGreen());
blueField.setText("" + color.getBlue());
}//end action performed
}//end newActionListener
);//end addActionListener
The darkening action listener
This code creates a new Color object that matches the color values in the three text elds.
Then it calls the darker method on that Color object causing its color to be darkened.
Then it extracts the color components from the darker Color object and stores those values in the text
elds.
This, in turn, causes the color swatch to change to match the new color values.
A brightening event handler
A similar event handler is registered on the button labeled Brighter in Figure 1 (p. 1625) .
This code, which you can view in Listing 4 (p. 1631) calls the brighter method instead of the darker
method on the Color object.
End of story
That concludes the explanation of material that is new and dierent in this program.
6.3.3.4.6 Summary
In this module, you will learned how to use a JColorChooser object to specify a color in any one of ve
dierent ways.
You also learned how to create brighter and darker shades of a given color.
6.3.3.4.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
Old material:
This program services document events on the contents of
text fields containing color values.
New material:
Demonstrates how to create and use a JColorChooser dialog.
Also demonstrates use of the darker and brighter methods.
Also demonstrates how to cause JTextField objects to be
non-editable.
*********************************************************/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Dimension;
import javax.swing.JColorChooser;
public Prob14Runner(){//constructor
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
redField.setEditable(false);
greenField.setEditable(false);
blueField.setEditable(false);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(chooseButton);
buttonPanel.add(brighterButton);
buttonPanel.add(darkerButton);
//--------------------------------------------------//
//Register listeners on the user input components.
//--------------------------------------------------//
chooseButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Color selColor = JColorChooser.showDialog(
chooseButton,"Choose color",new Color(
redInt,greenInt,blueInt));
if(selColor != null){
//Don't change the color if the user cancels
// out.
redField.setText("" + selColor.getRed());
greenField.setText(
"" + selColor.getGreen());
blueField.setText("" + selColor.getBlue());
}//end if
darkerButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Color color = new Color(
redInt,greenInt,blueInt).darker();
redField.setText("" + color.getRed());
greenField.setText("" + color.getGreen());
blueField.setText("" + color.getBlue());
}//end action performed
}//end newActionListener
);//end addActionListener
//--------------------------------------------------//
brighterButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Color color = new Color(
redInt,greenInt,blueInt).brighter();
redField.setText("" + color.getRed());
greenField.setText("" + color.getGreen());
blueField.setText("" + color.getBlue());
}//end action performed
}//end newActionListener
);//end addActionListener
//--------------------------------------------------//
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
//----------------------------------------------------//
//----------------------------------------------------//
-end-
6.3.3.5.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
The program described in this module requires the use of the Guzdial-Ericson multimedia class library.
You will nd download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson
Multimedia Class Library
71 .
6.3.3.5.2.1.1 Figures
• Figure 1 (p. 1639) . Program output at startup.
• Figure 2 (p. 1641) . Program output after zooming the image.
• Figure 3 (p. 1643) . Program output after changing the pixel color to yellow.
6.3.3.5.2.1.2 Listings
• Listing 1 (p. 1644) . Code for methods that were added.
• Listing 2 (p. 1644) . Modied setDefaultCloseOperation method.
• Listing 3 (p. 1645) . Beginning of ActionListener registered on update button.
• Listing 4 (p. 1645) . Convert zoom factor to type String.
• Listing 5 (p. 1646) . Set pixel color in original image.
• Listing 6 (p. 1646) . Create and populate a new PictureExplorer object.
• Listing 7 (p. 1646) . Call the mousePressed method.
• Listing 8 (p. 1647) . Set the zoom state.
• Listing 9 (p. 1648) . Complete listing of Prob15.
• Listing 10 (p. 1655) . Complete listing of modied PictureExplorer class.
6.3.3.5.3 Preview
In this module, you will learn how to write an editor program that you can use to modify the colors in an
image on a pixel-by-pixel basis.
Such a program could be useful, for example, for manually correcting "red eye" problems in digital
images.
Program output at startup
Figure 1 (p. 1639) shows the program output at startup.
The output consists of
Figure 2 (p. 1641) shows the program output after placing the PictureExplorer cursor on the
penguin's nose, and zooming the PictureExplorer image by 500%
If you look carefully, you should be able to see the crosshair cursor on the penguin's nose.
Figure 6.45: Program output after changing the pixel color to yellow.
• int xIndex
• int yIndex
• double zoomFactor
• JFrame pictureFrame
setDefaultCloseOperation
Also the call to the method was disabled.
Code for methods that were added
Listing 1 (p. 1644) shows the code for the methods that were added to the PictureExplorer class.
explorerFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
I will skip down to the event handler registered on the button labeled Update Pixel Color in Figure
1 (p. 1639) . That code begins in Listing 3 (p. 1645) .
updateButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
• creates a new Color object based on the values in the text elds of Figure 3 (p. 1643) , and
• changes the color of the corresponding pixel in the original image to the new color.
At this point, the color of the pixel in the original image has been modied.
0,
xIndex,
yIndex,
0,
false));
}//end actionPerformed
}//end newActionListener
);//end addActionListener
Conclusion of discussion
That concludes the discussion of the ActionListener object registered on the button labeled Update
Pixel Color in Figure 1 (p. 1639) .
It also concludes the discussion of the program.
6.3.3.5.6 Summary
In this module, you learned how to write an editor program that you can use to modify the colors in an
image on a pixel-by-pixel basis.
72 http://cnx.org/content/m44926/latest/Prob15.jpg
6.3.3.5.7 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
import javax.swing.event.DocumentEvent;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Dimension;
import javax.swing.JColorChooser;
public Prob15Runner(){//constructor
explorerFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
redField.setEditable(false);
greenField.setEditable(false);
blueField.setEditable(false);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(chooseButton);
buttonPanel.add(updateButton);
// buttonPanel.add(darkerButton);
//--------------------------------------------------//
updateButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
}//end actionPerformed
}//end newActionListener
);//end addActionListener
//--------------------------------------------------//
//----------------------------------------------------//
//----------------------------------------------------//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
import javax.swing.border.*;
/*
05/16/12 Modified by Baldwin to add getter methods to
cause the following values to be accessible from
outside the object:
int xIndex
int yIndex
double zoomFactor
JFrame pictureFrame
*/
/**
* Displays a picture and lets you explore the picture by displaying the x, y, red,
* green, and blue values of the pixel at the cursor when you click a mouse button or
* press and hold a mouse button while moving the cursor. It also lets you zoom in or
* out. You can also type in a x and y value to see the color at that location.
*
* Originally created for the Jython Environment for Students (JES).
* Modified to work with DrJava by Barbara Ericson
*
* Copyright Georgia Institute of Technology 2004
* @author Keith McDermottt, gte047w@cc.gatech.edu
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class PictureExplorer implements MouseMotionListener, ActionListener, MouseListener
{
// menu components
private JMenuBar menuBar;
private JMenu zoomMenu;
private JMenuItem twentyFive;
private JMenuItem fifty;
private JMenuItem seventyFive;
private JMenuItem hundred;
private JMenuItem hundredFifty;
private JMenuItem twoHundred;
private JMenuItem fiveHundred;
/**
* Public constructor
* @param picture the picture to explore
*/
public PictureExplorer(DigitalPicture picture)
{
// set the fields
this.picture=picture;
zoomFactor=1;
/**
* Changes the number system to start at one
*/
public void changeToBaseOne()
{
numberBase=1;
}
/**
* Set the title of the frame
*@param title the title to use in the JFrame
*/
public void setTitle(String title)
{
pictureFrame.setTitle(title);
}
/**
* Method to create and initialize the picture frame
*/
private void createAndInitPictureFrame()
{
pictureFrame = new JFrame(); // create the JFrame
pictureFrame.setResizable(true); // allow the user to resize it
pictureFrame.getContentPane().setLayout(new BorderLayout()); // use border layout
pictureFrame.setTitle(picture.getTitle());
PictureExplorerFocusTraversalPolicy newPolicy = new PictureExplorerFocusTraversalPolicy();
pictureFrame.setFocusTraversalPolicy(newPolicy);
/**
* Method to create the menu bar, menus, and menu items
*/
private void setUpMenuBar()
{
//create menu
menuBar = new JMenuBar();
zoomMenu = new JMenu("Zoom");
twentyFive = new JMenuItem("25%");
fifty = new JMenuItem("50%");
/**
* Create and initialize the scrolling image
*/
private void createAndInitScrollingImage()
{
scrollPane = new JScrollPane();
/**
* Creates the JFrame and sets everything up
*/
private void createWindow()
{
/**
* Method to set up the next and previous buttons for the
* pixel location information
*/
private void setUpNextAndPreviousButtons()
{
// create the image icons for the buttons
Icon prevIcon = new ImageIcon(SoundExplorer.class.getResource("leftArrow.gif"),
"previous index");
Icon nextIcon = new ImageIcon(SoundExplorer.class.getResource("rightArrow.gif"),
"next index");
// create the arrow buttons
xPrevButton = new JButton(prevIcon);
xNextButton = new JButton(nextIcon);
yPrevButton = new JButton(prevIcon);
yNextButton = new JButton(nextIcon);
/**
* Create the pixel location panel
* @param labelFont the font for the labels
* @return the location panel
*/
public JPanel createLocationPanel(Font labelFont) {
locationPanel.setLayout(new FlowLayout());
Box hBox = Box.createHorizontalBox();
// add the items to the vertical box and the box to the panel
hBox.add(Box.createHorizontalGlue());
hBox.add(xLabel);
hBox.add(xPrevButton);
hBox.add(xValue);
hBox.add(xNextButton);
hBox.add(Box.createHorizontalStrut(10));
hBox.add(yLabel);
hBox.add(yPrevButton);
hBox.add(yValue);
hBox.add(yNextButton);
locationPanel.add(hBox);
hBox.add(Box.createHorizontalGlue());
return locationPanel;
}
/**
* Create the color information panel
* @param labelFont the font to use for labels
* @return the color information panel
*/
private JPanel createColorInfoPanel(Font labelFont)
{
// create a color info panel
JPanel colorInfoPanel = new JPanel();
colorInfoPanel.setLayout(new FlowLayout());
return colorInfoPanel;
}
/**
* Creates the North JPanel with all the pixel location
* and color information
*/
private void createInfoPanel()
{
// create the info panel and set the layout
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BorderLayout());
/**
* Method to check that the current position is in the viewing area and if
* not scroll to center the current position if possible
*/
public void checkScroll()
{
// get the x and y position in pixels
int xPos = (int) (xIndex * zoomFactor);
int yPos = (int) (yIndex * zoomFactor);
// calculate how to position the current position in the middle of the viewing
// area
int viewX = xPos - (int) (rectWidth / 2);
int viewY = yPos - (int) (rectHeight / 2);
viewX = 0;
else if (viewX > maxIndexX)
viewX = maxIndexX;
if (viewY < 0)
viewY = 0;
else if (viewY > maxIndexY)
viewY = maxIndexY;
/**
* Zooms in the on picture by scaling the image.
* It is extremely memory intensive.
* @param factor the amount to zoom by
*/
public void zoom(double factor)
{
// save the current zoom factor
zoomFactor = factor;
// calculate the new width and height and get an image that size
int width = (int) (picture.getWidth()*zoomFactor);
int height = (int) (picture.getHeight()*zoomFactor);
BufferedImage bimg = picture.getBufferedImage();
/**
* Repaints the image on the scrollpane.
*/
public void repaint()
{
pictureFrame.repaint();
}
//****************************************//
// Event Listeners //
//****************************************//
/**
* Called when the mouse is dragged (button held down and moved)
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method to check if the given x and y are in the picture
* @param x the horiztonal value
* @param y the vertical value
* @return true if the x and y are in the picture and false otherwise
*/
private boolean isLocationInPicture(int x, int y)
{
boolean result = false; // the default is false
if (x >= 0 && x < picture.getWidth() &&
y >= 0 && y < picture.getHeight())
result = true;
return result;
}
/**
* Method to display the pixel information from the passed x and y but
* also converts x and y from strings
* @param xString the x value as a string from the user
* @param yString the y value as a string from the user
*/
public void displayPixelInformation(String xString, String yString)
{
int x = -1;
int y = -1;
try {
x = Integer.parseInt(xString);
x = x - numberBase;
y = Integer.parseInt(yString);
y = y - numberBase;
} catch (Exception ex) {
}
/**
* Method to display pixel information for the passed x and y
* @param pictureX the x value in the picture
* @param pictureY the y value in the picture
*/
private void displayPixelInformation(int pictureX, int pictureY)
{
// check that this x and y is in range
if (isLocationInPicture(pictureX, pictureY))
{
// save the current x and y index
xIndex = pictureX;
yIndex = pictureY;
}
else
{
clearInformation();
}
/**
* Method to display pixel information based on a mouse event
* @param e a mouse event
*/
private void displayPixelInformation(MouseEvent e)
{
/**
* Method to clear the labels and current color and reset the
* current index to -1
*/
private void clearInformation()
{
xValue.setText("N/A");
yValue.setText("N/A");
rValue.setText("R: N/A");
gValue.setText("G: N/A");
bValue.setText("B: N/A");
colorPanel.setBackground(Color.black);
xIndex = -1;
yIndex = -1;
}
/**
* Method called when the mouse is moved with no buttons down
* @param e the mouse event
*/
public void mouseMoved(MouseEvent e)
{}
/**
* Method called when the mouse is clicked
* @param e the mouse event
*/
public void mouseClicked(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method called when the mouse button is pushed down
* @param e the mouse event
*/
public void mousePressed(MouseEvent e)
{
displayPixelInformation(e);
}
/**
* Method called when the mouse button is released
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e)
{
}
/**
* Method called when the component is entered (mouse moves over it)
* @param e the mouse event
*/
public void mouseEntered(MouseEvent e)
{
}
/**
* Method called when the mouse moves over the component
* @param e the mouse event
*/
public void mouseExited(MouseEvent e)
{
}
/**
* Method to enable all menu commands
*/
private void enableZoomItems()
{
twentyFive.setEnabled(true);
fifty.setEnabled(true);
seventyFive.setEnabled(true);
hundred.setEnabled(true);
hundredFifty.setEnabled(true);
twoHundred.setEnabled(true);
fiveHundred.setEnabled(true);
}
/**
* Controls the zoom menu bar
*
* @param a the ActionEvent
*/
public void actionPerformed(ActionEvent a)
{
if(a.getActionCommand().equals("Update"))
{
this.repaint();
}
if(a.getActionCommand().equals("25%"))
{
this.zoom(.25);
enableZoomItems();
twentyFive.setEnabled(false);
}
if(a.getActionCommand().equals("50%"))
{
this.zoom(.50);
enableZoomItems();
fifty.setEnabled(false);
}
if(a.getActionCommand().equals("75%"))
{
this.zoom(.75);
enableZoomItems();
seventyFive.setEnabled(false);
}
if(a.getActionCommand().equals("100%"))
{
this.zoom(1.0);
enableZoomItems();
hundred.setEnabled(false);
}
if(a.getActionCommand().equals("150%"))
{
this.zoom(1.5);
enableZoomItems();
hundredFifty.setEnabled(false);
}
if(a.getActionCommand().equals("200%"))
{
this.zoom(2.0);
enableZoomItems();
twoHundred.setEnabled(false);
}
if(a.getActionCommand().equals("500%"))
{
this.zoom(5.0);
enableZoomItems();
fiveHundred.setEnabled(false);
}
}
/**
* Test Main. It will ask you to pick a file and then show it
*/
public static void main( String args[])
{
Picture p = new Picture(FileChooser.pickAFile());
PictureExplorer test = new PictureExplorer(p);
/**
* Class for establishing the focus for the textfields
*/
private class PictureExplorerFocusTraversalPolicy
extends FocusTraversalPolicy {
/**
* Method to get the next component for focus
*/
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(xValue))
return yValue;
else
return xValue;
}
/**
* Method to get the previous component for focus
*/
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(xValue))
return yValue;
else
return xValue;
}
-end-
6.4.1.1.6 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click the download link for the zip les that contain input image les and solution source code les.
Use the capabilities of your browser to download and save the contents of those zip les.
2. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
3. Compile and run the source code.
4. Write, compile, and run a simple Java program that will display each input image le in a Picture-
Explorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
You may nd other useful hints in my online tutorials and slides for this course.
Dick Baldwin
Picture, filename Prob01.jpg height 274 width 365
Dick Baldwin
Dick Baldwin
Dick Baldwin
Dick Baldwin
*********************************************************/
76 http://cnx.org/content/m44148/latest/
77 http://cnx.org/content/m44264/latest/Prob01solution.zip
6.4.1.1.8.2 Program 2
Listing 6.135: Write the Java application described below.
/*File Prob02 Copyright 2012 R.G.Baldwin
Write a program named Prob02 that uses the class denition shown below and Ericson's media
library to produce the graphic output image shown in Figure 2 (p. 1677) below.
Click here
78 to download a zip le containing source code for a solution.
Contrary to the general instructions given above, you may not dene any new classes to cause
your program to behave as required.
You must copy and modify (if necessary) the media classes named Turtle.java, and SimpleTur-
tle.java to cause your program to produce the required output. Don't forget to compile these classes
after you modify them.
In addition to the output image, your program must produce the following output on the
command- line screen, and must substitute your name for mine wherever my name appears both
in the image and on the command-line screen:
Dick Baldwin
My name is Joe the turtle.
*********************************************************/
import java.awt.Color;
78 http://cnx.org/content/m44264/latest/Prob02solution.zip
6.4.1.1.8.3 Program 3
Listing 6.136: Write the Java application described below.
/*File Prob03 Copyright 2012 R.G.Baldwin
Write a program named Prob03 that uses Ericson's media library to produce the graphic output
images shown in Figure 3 (p. 1678) and Figure 4 (p. 1679) below.
Click here
79 to download a zip le containing the source code for a solution.
The image shown in Figure 3 (p. 1678) is the image that appears on the screen when the
program starts running. The image shown in Figure 4 (p. 1679) is what you should see when you
click the button at the bottom of the world.
You must copy and modify (if necessary) the media class named World.java, to cause your
program to produce the required output with the required behavior. Don't forget to compile that
class after you modify it.
79 http://cnx.org/content/m44264/latest/Prob03solution.zip
This program adds a JButton object to the SOUTH location of the World object as shown in
Figure 3 (p. 1678) .
The program initially displays an empty white world. When the user clicks the button, the
world's background color changes to blue, a turtle appears in the center of the World, and the
student's name appears near the top of the world.
Figure 6.48: The rst of two required output images for Prob03.
Figure 6.49: The second of two required output images for Prob03.
6.4.1.1.8.4 Program 4
Listing 6.137: Write the Java application described below.
/*File Prob04 Copyright 2012 R.G.Baldwin
Write a program named Prob04 that uses Ericson's media library to produce the graphic output
images shown in Figure 5 (p. 1680) , Figure 6 (p. 1681) , and Figure 7 (p. 1682) below.
Click here
80 to download a zip le containing the source code for a solution.
Figure 5 (p. 1680) shows the image that appears on the screen when the program starts running.
Figure 6 (p. 1681) shows what you should see after you have clicked the button at the bottom of
the world one time. Figure 6 (p. 1681) shows what you should see after you have clicked the button
sixteen times.
80 http://cnx.org/content/m44264/latest/Prob04solution.zip
You must copy and modify the media classes named World.java and SimplePicture.java, to cause
your program to produce the required output with the required behavior. Don't forget to compile
those classes after you modify them.
This program adds a JButton object to the SOUTH location of the World object as shown in
Figure 5 (p. 1680) .
The following description is intended to guide you in writing your program. However, you must
run my version of the program and replicate it exactly. I recommend that you run the two programs
side-by-side and compare their appearance and behavior each time you click both programs.
The program initially displays an empty white world with a button at the bottom. When the
user clicks the button, the world's background color changes to green, a turtle appears in the bottom
right of the World, and the student's name appears near the top of the world in blue. The turtle
has a blue body and a red shell.
When you click the button again, the background changes to yellow, the student's name changes
to red, and the turtle changes to a red body with a blue shell. The turtle turns 90 degrees left and
moves forward 100 pixels plus the value of a click counter. As a result, the turtle leaves a blue trail.
On the next click, the colors revert to the same as before, the turtle turns 90 degrees left and
moves forward 100 pixels plus the value of the click counter leaving a red trail.
This cycle repeats on each click with the turtle's trail drawing a square spiral of increasing size
with red lines on the top and bottom of the spiral and blue lines on the right and left of the spiral.
6.4.1.1.8.5 Program 5
Listing 6.138: Write the Java application described below.
/*File Prob05 Copyright 2012 R.G.Baldwin
Write a program named Prob05 that uses Ericson's media library to produce the graphic output
image shown in Figure 8 (p. 1683) , Figure 9 (p. 1684) , and Figure 10 (p. 1685) below.
Click here
81 to download a zip le containing the source code for a solution.
Figure 8 (p. 1683) shows the image that appears on the screen when the program starts running.
Figure 9 (p. 1684) shows what you should see after you have entered numeric values into the angle
and distance elds and have clicked the Move button. Figure 10 (p. 1685) is similar to what you
should see after doing the above several times for dierent numeric values.
You must copy and modify the media class named World.java to cause your program to produce
the required output with the required behavior. Don't forget to compile World.java after you modify
it.
This program adds two buttons, two labels, and two text elds to form a GUI at the bottom of
the World object.
If you enter numeric values into the angle and distance elds and then click the Move button,
the turtle will turn by that angle in degrees and move by that distance in pixels.
81 http://cnx.org/content/m44264/latest/Prob05solution.zip
The program must terminate and return control to the operating system when you click the
Quit button.
Note that the GUI at the bottom of the World object is comprised of AWT components instead
of Swing components.
• Revised:
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.4.2.1.6 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click the download link for the zip les that contain input image les and solution source code les.
Use the capabilities of your browser to download and save the contents of those zip les.
2. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
3. Compile and run the source code.
4. Write, compile, and run a simple Java program that will display each input image le in a Picture-
Explorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
You may nd other useful hints in my online tutorials and slides for this course.
• Alpha transparency
• BueredImage objects of TYPE_INT_ARGB
• The representation of a pixel as type int.
• Bit manipulation of pixels.
85 http://cnx.org/content/m44148/latest/
86 http://cnx.org/content/m44265/latest/Prob01solution.zip
In addition to the output images described above, your program must produce the following output
on the command-line screen, and must substitute your name for mine wherever my name appears
both in the images and on the command-line screen:
Dick Baldwin.
Dick Baldwin
Picture, filename Prob01a.jpg height 118 width 100
Picture, filename Prob01b.jpg height 240 width 320
Picture, filename None height 101 width 77
*********************************************************/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
Figure 6.56: The rst of three required output images for Prob01.
Figure 6.57: The second of three required output images for Prob01.
Figure 6.58: The third of three required output images for Prob01.
6.4.2.1.8.2 Program 2
Listing 6.140: Write the Java application described below.
/*File Prob02 Copyright 2012 R.G.Baldwin
Write a program named Prob02 that uses Ericson's media library along with the image les
named Prob02a.jpg and Prob02b.jpg to produce the graphic output images shown in Figure 4 (p.
1693) below.
Click here
87 to download a zip le containing the required image les along with the source
code for a solution.
The top image shown in Figure 4 (p. 1693) is a beach scene with a partially opaque buttery
superimposed on the beach scene. The bottom image is a slider that is used to control the percent
opacity of the buttery image.
At startup, the slider is positioned at the 50-percent mark and the opacity of the buttery is
50 percent.
As you move the slider to the right, the buttery becomes more opaque, becoming totally opaque
when the slider is positioned at 100 percent. As you move the slider to the left, the buttery becomes
less opaque, becoming totally transparent when the slider is positioned at 0 percent.
87 http://cnx.org/content/m44265/latest/Prob02solution.zip
In order to write this program, you must modify the class from Ericson's media library named
SimplePicture. Your modications must make it possible for you to display a partially transparent
image on top of another image with the background image showing through.
Your modication must also make it possible to display your name in the dark blue banner at
the top of the image of the beach scene.
The program must terminate and return control to the operating system when you click the
large X in the upper- right corner of the GUI containing the slider.
In order to improve the responsiveness and memory utilization of the program, you should
instantiate all of the Picture objects that the program needs at startup, and should not instantiate
additional Picture objects when handling events red by the slider.
6.4.2.1.8.3 Program 3
Listing 6.141: Write the Java application described below.
/*File Prob03 Copyright 2012 R.G.Baldwin
Write a program named Prob03 that uses Ericson's media library along with the image le
named Prob3.jpg to produce the graphic output images shown in Figure 5 (p. 1695) below.
Click here
88 to download a zip le containing the required image le along with the source code
for a solution.
The top image shown in Figure 5 (p. 1695) is an image of a buttery to which an edge detection
algorithm has been applied. The bottom image is a slider that is used to control the edge-detection
threshold.
The edge-detection algorithm performs edge detection on a Picture object by rows and also by
columns. All edges that are detected by processing adjacent pixels on a row are marked in red. All
edges that are detected by processing adjacent pixels on a column are marked in black. If a pixel
is determined to be on an edge using both approaches, it ends up being black. If an edge is not
detected, the corresponding pixel is marked in white.
At startup, the slider is positioned at the 50-percent mark and the image has been edge-detected
using a threshold value of 50. As you move the slider to the right, the threshold increases up to
a value of 100, which in turn causes the amount of white area in the image to increase. As you
move the slider to the left, the threshold decreases down to a value of zero, which in turn causes
the amount of white area in the image to decrease.
The program must terminate and return control to the operating system when you click the
large X in the upper- right corner of the GUI containing the slider.
88 http://cnx.org/content/m44265/latest/Prob03solution.zip
6.4.2.1.8.4 Program 4
Listing 6.142: Write the Java application described below.
/*File Prob04 Copyright 2012 R.G.Baldwin
Write a program named Prob04 that uses Ericson's media library along with the image les
named Prob04a.jpg and Prob04b.jpg to produce the graphic output images shown in Figure 6 (p.
1697) and Figure 7 (p. 1698) below.
Click here
89 to download a zip le containing the required image les along with the source
code for a solution.
89 http://cnx.org/content/m44265/latest/Prob04solution.zip
The top image shown in Figure 6 (p. 1697) is a buttery image. The image immediately below
that one is a slider that is used to control a scale factor that is applied to an image of a beach.
At startup, the slider is positioned at the zero-percent mark (at the far left) and the beach
image is too small to be seen in the upper-left corner of the buttery image.
As you move the slider to the right, an image of a beach emerges from the upper-left corner
covering the image of the buttery.
Figure 7 (p. 1698) shows the result of moving the slider to the 50-percent mark.
The size of the beach image increases and decreases smoothly as you move the slider back and
forth. The upper- left corner of the beach image is always in the upper- left corner of the buttery
image. The buttery becomes completely covered by the beach image when the slider is positioned
at 100 percent (the far right) .
The program must terminate and return control to the operating system when you click the
large X in the upper- right corner of the GUI containing the slider.
6.4.2.1.8.5 Program 5
Listing 6.143: Write the Java application described below.
/*File Prob05 Copyright 2012 R.G.Baldwin
Write a program named Prob05 that uses Ericson's media library along with the image le
named Prob05.jpg to produce the graphic output images shown in Figure 8 (p. 1700) and Figure
9 (p. 1701) below.
Click here
90 to download a zip le containing the required image le along with the source code
for a solution.
90 http://cnx.org/content/m44265/latest/Prob05solution.zip
The top image in Figure 8 (p. 1700) is a buttery image. The image of the buttery can be
rotated in its picture by any angle ranging from -360 degrees to +360 degrees.
The image immediately below that one is a slider that is used to control the rotation angle that
is applied to the buttery image.
At startup, the slider is positioned at the zero-degrees mark (in the center) and the buttery
image is displayed with no rotation. As you move the slider to the right, the buttery image rotates
clockwise around its center through an angle that can be as large as 360 degrees.
Figure 9 (p. 1701) shows the result of moving the slider to the +120-degree mark.
As you move the slider to the left, the buttery image rotates counter-clockwise around its
center through an angle that can be as large as -360 degrees.
The buttery image rotates smoothly around its center as you move the slider back and forth.
The program must terminate and return control to the operating system when you click the
large X in the upper- right corner of the GUI containing the slider.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
6.4.3.1.5 Hints
For some of the programs, you may rst need to deduce the algorithm used to transform the input image
into the output image, and then write a working program that implements that algorithm. In some cases,
you may need to compare numeric color values for corresponding pixels in the input and output images in
order to deduce the algorithm.
You can obtain those color values using the following procedure:
1. Click the download link for the zip les that contain input image les and solution source code les.
Use the capabilities of your browser to download and save the contents of those zip les.
2. If necessary, replace calls to the show method in my source code with calls to the explore method
to force the program to display the output images in a PictureExplorer window.
3. Compile and run the source code.
4. Write, compile, and run a simple Java program that will display each input image le in a Picture-
Explorer window.
5. Use the input and output PictureExplorer windows to compare the input and output color values
on a pixel by pixel basis.
You may nd other useful hints in my online tutorials and slides for this course.
94 http://cnx.org/content/m44148/latest/
95 http://cnx.org/content/m44262/latest/Prob01solution.zip
6.4.3.1.7.2 Program 2
Listing 6.145: Write the Java application described below.
/*File Prob02 Copyright 2012 R.G.Baldwin
Write a program named Prob02 that uses Ericson's media library along with the image le
named Prob02.jpg to produce the graphic output images shown in Figure 2 (p. 1707) below.
Click here
96 to download a zip le containing the required image le along with the source code
for a solution.
Whenever you click the button in the GUI in the lower image, the green color component value
at the location of the crosshair cursor in the upper image is displayed in the text eld in the GUI.
96 http://cnx.org/content/m44262/latest/Prob02solution.zip
6.4.3.1.7.3 Program 3
Listing 6.146: Write the Java application described below.
/*File Prob03 Copyright 2012 R.G.Baldwin
Write a program named Prob03 that uses Ericson's media library to produce the graphic output
image shown in Figure 3 (p. 1708) below.
Click here
97 to download a zip le containing the source code for a solution.
Whenever you click the button in the GUI, the square in the upper right turns from black to
yellow with a black border and the RGB color values for the color yellow appear in the three text
elds.
6.4.3.1.7.4 Program 4
Listing 6.147: Write the Java application described below.
/*File Prob04 Copyright 2012 R.G.Baldwin
Write a program named Prob04 that uses Ericson's media library to produce the graphic output
images shown in Figure 4 (p. 1709) below.
Click here
98 to download a zip le containing the source code for a solution.
Whenever you click the "Choose Color" button in the GUI in the upper image, the color chooser
dialog shown in the lower image appears. When you select a color and click the OK button, the
color chooser dialog disappears and that color appears in the square in the upper right portion of
the GUI. In addition, the red, green, and blue color component values for that color appear in the
corresponding text elds.
Whenever you click the "Brighter" and "Darker" buttons, the color displayed in the square
becomes brighter or darker and the color values in the text elds change accordingly.
97 http://cnx.org/content/m44262/latest/Prob03solution.zip
98 http://cnx.org/content/m44262/latest/Prob04solution.zip
6.4.3.1.7.5 Program 5
Listing 6.148: Write the Java application described below.
/*File Prob05 Copyright 2012 R.G.Baldwin
Write a program named Prob05 that uses Ericson's media library along with the image le
named Prob05.jpg to produce the graphic output images shown in Figure 5 (p. 1711) below.
Click here
99 to download a zip le containing the required image le along with the source code
for a solution.
The color in the square in the upper right of the GUI in the lower image is governed by the
color values in the red, green, and blue text elds.
Whenever you click the button in the GUI, the pixel at the crosshair cursor in the upper image
is changed to reect the color in the square in the GUI. This can best be seen when the upper
99 http://cnx.org/content/m44262/latest/Prob05solution.zip
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
7.1.2 Welcome
Click the link to view the course material for GAME 2302 Mathematical Applications for Game Development
2 , which I teach at Austin Community College in Austin, TX.
Ocial information about the course
The college website for this course is: http://www.austincc.edu/baldwin/
3 .
As of December 2012, the description for this course reads:
"GAME 2302 - Mathematical Applications for Game Development
Presents applications of mathematics and science in game and simulation programming. Includes the
utilization of matrix and vector operations, kinematics, and Newtonian principles in games and simulations.
Also covers code optimization."
7.1.3 Miscellaneous
This section contains a variety of miscellaneous information.
1713
CHAPTER 7. GAME 2302 - MATHEMATICAL APPLICATIONS FOR GAME
1714
DEVELOPMENT
note: Disclaimers:: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
8.1.2 Welcome
Click the link to view the material for Anatomy of a Game Engine
2 , which I use in some of the courses
that I teach at Austin Community College in Austin, TX.
This is a collection of modules designed to teach students about the anatomy of a typical game or
simulation engine (sometimes called a game or simulation framework) .
The collection is built around the Slick2D Game library.
The Slick2D library
I chose to concentrate on the free game library named Slick2D
3 ,(which is written in Java) for several
reasons including the following:
• Java is the language with which I am the most comfortable. Hence, I can probably do a better job of
explaining the anatomy of a game engine that uses Slick2D than would be the case for a game engine
written in C++, C#, Python, or some other programming language.
• Java has proven in recent years to be a commercially successful game programming language. For
example, I cite the commercial game named Minecraft
4 , written in Java, for which apparently millions
of copies have been sold. Also, knowing Java is very benecial for those who might want to develop
apps for Android.
• Slick2D is free and the source code for Slick2D is readily available.
• The overall structure of a basic Slick2D game engine is very similar to Dark GDK and XNA, and is
probably similar to other game engines as well.
• Java is platform independent.
1715
1716 CHAPTER 8. ANATOMY OF A GAME ENGINE
8.1.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers:: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
Principles of Object-Oriented
Programming
9.1.2 Welcome
Click the following title to view Principles of Object-Oriented Programming
2 (current as of 02/20/13) :
9.1.3 Miscellaneous
This section contains a variety of miscellaneous information.
1717
1718 CHAPTER 9. PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING
note: Disclaimers:: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
10.1.2 Welcome
Over the years, I have published a large number of tutorials in the areas of computer programming and
DSP. As I have the time to do so, I am converting the more signicant of those tutorials into cnxml code
and re-publishing them at cnx.org. In the meantime, the collection titled Programming Oldies But Goodies
2 , which is a work in process, gathers many of the tutorials in their original HTML format into a common
location to make them readily available for Connexions users.
10.1.3 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers:: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
1719
1720 CHAPTER 10. PROGRAMMING OLDIES BUT GOODIES
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
Appendices
11.1.2 Preface
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP)
using Java.
I cannot overemphasize the importance of Oracle's Java documentation
2 to aspiring Java programmers.
The documentation package, which can be downloaded for installation and local access or accessed online,
contains a wealth of information.
In my opinion, it is not possible to write Java programs of any substance without frequent reference
to the documentation. No one can memorize everything that they need to know to be a successful Java
programmer.
(Note that each time Oracle releases a new version of the Java Development Kit (JDK), they also release
a new version of the documentation. Therefore, as new versions are released, the links provided in this
document may become outdated and may not take you to the latest version of the documentation. However,
you should be able to nd the latest documentation via an online search.)
1721
1722 CHAPTER 11. APPENDICES
11.1.2.1.1 Figures
• Figure 1 (p. 1723) . Screen shot of the API specication at startup.
• Figure 2 (p. 1725) . Screen shot of the API documentation after selecting the JButton class.
11.1.3 Discussion
Small core language, large class library
The Java Platform Standard Edition programming environment consists of a small core programming
language and a large class library.
(As of the date of this writing, you can view The Java Language Specication 3 online. This specication
will tell you just about everything that most programmers need to know about the core language.)
The size of the class library grows with the release of each new version of the JDK, because each new
version provides capabilities that didn't exist in the previous version. New capabilities are added through
the addition of new classes and new interfaces to the library.
The true power of Java resides in the class libraries
Once you understand how OOP is implemented in Java and you get beyond while loops, if statements,
and other fundamental programming concepts, virtually all the power of Java resides in:
• Classes, interfaces, and methods in the various class libraries that you use directly.
• Classes, interfaces, and methods in the various class libraries that you extend.
• New classes, interfaces, and methods that you and others dene.
You will always use material from Oracle's standard class libraries. You will often use material from other
libraries that you create yourself, or that you obtain from sources outside of Oracle (such as Barb Ericson's
multimedia library 4 , for example) .
Top-level online documentation
As of the date of this writing, you can view the top-level page of the documentation for Java Platform
Standard Edition 7 at http://docs.oracle.com/javase/7/docs/
5 .
A complicated page
When you rst view that documentation page, it may appear to be very complicated. Of all the material
on the page, the most important is probably the Application Programming Interface (API) , which is
currently available via a link on the right side of the page labeled Java SE API
6 .
However, you should not ignore the links to other information available on the top-level page
7 . Those
links will often contain information that you need, and that information can make you more ecient in using
the API documentation.
Search
If you follow the Search link at the top of the page, you will arrive at a search engine page
8 that gives
you the ability to do a keyword search on the online documentation.
Downloading and installing Java
Of particular interest to most newcomers should be the links titled Installation Instructions
9 and Java
SE Downloads
10 .
The Java Tutorials
3 http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html
4 http://coweb.cc.gatech.edu/mediaComp-plan/101
5 http://docs.oracle.com/javase/7/docs/
6 http://docs.oracle.com/javase/7/docs/api/index.html
7 http://docs.oracle.com/javase/7/docs/
8 http://docs.oracle.com/javase/search.html
9 http://docs.oracle.com/javase/7/docs/webnotes/install/index.html
10 http://www.oracle.com/technetwork/java/javase/downloads/index.html
11 http://docs.oracle.com/javase/tutorial/
12 http://docs.oracle.com/javase/tutorial/essential/environment/paths.html
13 http://docs.oracle.com/javase/7/docs/api/index.html
Screen layout
The purpose of providing this screen shot is to give you an idea of the general layout of the material as
it appears on your screen. As you can see, the layout consists of three frames when viewed in your HTML
browser.
(A version without frames is also available by selecting the "No Frames" link at the top of the page.
The version without frames is particularly useful for using the "page search" capability of your browser to
nd something on the page.)
The two leftmost frames
The upper-left frame contains a list of packages . The lower-left frame contains a list of the classes
and interfaces that are contained in the package that is selected in the top-left frame.
(The default package selection in the upper-left frame is "All Classes".)
You make selections in these two frames (or in the link bar at the top of the page) to control the contents
of the rightmost frame.
The rightmost frame
When you rst access the API documentation (and when you select Overview at the top of the page),
the rightmost frame contains summary information about all of the packages.
When you select a class in the lower-left frame (such as the JButton class for example) , the rightmost
frame contains hyperlinked information about that class, including:
Figure 2 (p. 1725) shows a screen shot of the browser window after selecting the class named JButton in
the lower-left frame. If you pull down the thumb in the scroll bar on the right side of the browser window,
you will expose all of the information in the above list.
Screen shot of the API documentation after selecting the JButton class.
Figure 11.2: Screen shot of the API documentation after selecting the JButton class.
• Overview - provides summary information about packages (shown in Figure 1 (p. 1723) ).
• Package - provides a description of the package that contains the class selected in the lower-left
frame.
• Class - provides a description of the class selected in the lower-left frame.
• Use - describes how the class selected in the lower-left frame is used in various packages.
• Tree - provides detailed inheritance hierarchy information for a selected package.
• Deprecated - provides a list of material that has been deprecated (may not be supported in future
versions)
• Index - provides a hyperlinked alphabetized index of interfaces, classes, constructors, variables, and
methods.
• Help - Describes how the API document is organized.
The various pages that are displayed by selecting these links can often help you to nd what you are looking
for. Probably the most useful and frequently consulted item in the above list is the Index.
The alphabetical index
The alphabetical index can be extremely useful if you know the full or partial spelling of what you are
looking for, beginning with the rst character.
For example, assume that you remember (or you can surmise from what you know about Java properties)
that there is a method whose name begins with getSystemLookAndFeel , which returns the name of
the LookAndFeel class that implements the native look and feel for a particular operating system. You
can easily look this up under G in the alphabetical index.
What you will nd when you look it up is a brief description of a method named getSystemLookAnd-
FeelClassName that matches what you are looking for. The name of the method is also a hyperlink
to the detailed description of the same method as it appears in the documentation for the class named
UIManager .
11.1.7 Summary
There are several ways to search for useful information in the Oracle documentation. There is no single
approach that will serve all of your needs to nd information in the documentation. You simply need to
become familiar with the dierent ways to search for information in the documentation and be prepared to
use the approach that does the best job in each situation.
11.1.8 Miscellaneous
This section contains a variety of miscellaneous information.
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, you should be aware that some of the HTML elements in this
module may not translate well into PDF.
I also want you to know that, I receive no nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle
books, and placed them for sale on Amazon.com showing me as the author. I neither receive
compensation for those sales nor do I know who does receive compensation. If you purchase such
a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it
was made and published without my prior knowledge.
-end-
B
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
behavior, 5.2.1(612), 5.2.2(619),
6.3.1.4(1464), 6.3.1.5(1498),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.3.2.1(1510), 6.3.2.2(1523),
5.2.6(656), 5.2.7(667), 5.2.8(676),
6.3.2.3(1538), 6.3.2.4(1549),
5.2.9(685), 5.2.10(696), 5.2.11(709),
6.3.2.5(1559), 6.3.3.1(1575),
5.2.12(727), 5.2.13(739), 5.2.14(762),
6.3.3.2(1582), 6.3.3.3(1610),
5.2.15(775), 5.2.16(790), 5.3.7(872),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.3.8(886), 5.3.9(895), 5.3.10(896),
6.4.2(1687), 6.4.3(1703)
5.3.11(909), 5.3.12(916), 5.3.13(917),
class, 5.2.1(612), 5.2.2(619), 5.2.3(631),
5.3.14(927), 5.3.15(933), 5.3.16(934),
5.2.4(641), 5.2.5(649), 5.2.6(656),
5.3.17(945), 5.3.18(954), 5.3.19(955),
5.2.7(667), 5.2.8(676), 5.2.9(685),
5.3.20(967), 5.3.21(974), 5.3.22(975),
5.2.10(696), 5.2.11(709), 5.2.12(727),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
5.2.13(739), 5.2.14(762), 5.2.15(775),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
5.2.16(790), 5.3.7(872), 5.3.8(886),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
5.3.9(895), 5.3.10(896), 5.3.11(909),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
5.3.12(916), 5.3.13(917), 5.3.14(927),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
5.3.15(933), 5.3.16(934), 5.3.17(945),
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
5.3.18(954), 5.3.19(955), 5.3.20(967),
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
5.3.21(974), 5.3.22(975), 5.3.24(1002),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.3.25(1003), 5.3.27(1031), 5.3.28(1031),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.3.30(1060), 5.3.31(1061), 5.3.32(1075),
6.3.1.4(1464), 6.3.1.5(1498),
5.3.33(1075), 5.3.35(1099), 5.3.36(1100),
6.3.2.1(1510), 6.3.2.2(1523),
5.3.38(1122), 5.3.39(1122), 5.3.41(1146),
6.3.2.3(1538), 6.3.2.4(1549),
5.3.42(1147), 5.3.44(1166), 5.3.45(1166),
6.3.2.5(1559), 6.3.3.1(1575),
5.3.47(1187), 6.2.1(1378), 6.2.2(1381),
6.3.3.2(1582), 6.3.3.3(1610),
6.2.3(1400), 6.2.4(1400), 6.2.5(1400),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
6.2.6(1400), 6.2.7(1401), 6.3.1.1(1401),
6.4.2(1687), 6.4.3(1703)
6.3.1.2(1427), 6.3.1.3(1449),
bookClasses, 5.3.4(832), 5.3.5(854),
6.3.1.4(1464), 6.3.1.5(1498),
5.3.6(871)
6.3.2.1(1510), 6.3.2.2(1523),
Brightening, 5.3.29(1051)
6.3.2.3(1538), 6.3.2.4(1549),
C case, 5.4.11(1277)
6.3.2.5(1559), 6.3.3.1(1575),
6.3.3.2(1582), 6.3.3.3(1610),
casting, 3.15(320), 5.2.1(612), 5.2.2(619),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.4.2(1687), 6.4.3(1703)
5.2.6(656), 5.2.7(667), 5.2.8(676),
class method, 5.2.1(612), 5.2.2(619),
5.2.9(685), 5.2.10(696), 5.2.11(709),
5.2.3(631), 5.2.4(641), 5.2.5(649),
5.2.12(727), 5.2.13(739), 5.2.14(762),
5.2.6(656), 5.2.7(667), 5.2.8(676),
5.2.15(775), 5.2.16(790), 5.3.7(872),
5.2.9(685), 5.2.10(696), 5.2.11(709),
5.3.8(886), 5.3.9(895), 5.3.10(896),
5.2.12(727), 5.2.13(739), 5.2.14(762),
5.3.11(909), 5.3.12(916), 5.3.13(917),
D
5.3.20(967), 5.3.21(974), 5.3.22(975),
Darkening, 5.3.29(1051)
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
data structures, 5.4.1(1188), 5.4.2(1198)
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
data types, 4.12(396), 4.13(410)
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
descending order, 5.4.11(1277)
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
documentation, 11.1(1721)
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
Duplicate Elements, 5.4.6(1227)
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
E elements, 5.4.14(1304)
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
encapsulation, 5.2.1(612), 5.2.2(619),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.3.1.4(1464), 6.3.1.5(1498),
5.2.6(656), 5.2.7(667), 5.2.8(676),
6.3.2.1(1510), 6.3.2.2(1523),
5.2.9(685), 5.2.10(696), 5.2.11(709),
6.3.2.3(1538), 6.3.2.4(1549),
5.2.12(727), 5.2.13(739), 5.2.14(762),
6.3.2.5(1559), 6.3.3.1(1575),
5.2.15(775), 5.2.16(790), 5.3.7(872),
6.3.3.2(1582), 6.3.3.3(1610),
5.3.8(886), 5.3.9(895), 5.3.10(896),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.3.11(909), 5.3.12(916), 5.3.13(917),
6.4.2(1687), 6.4.3(1703)
5.3.14(927), 5.3.15(933), 5.3.16(934),
extract, 5.4.12(1284)
5.3.17(945), 5.3.18(954), 5.3.19(955),
5.3.20(967), 5.3.21(974), 5.3.22(975),
F nal, 5.2.1(612), 5.2.2(619), 5.2.3(631),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
5.2.4(641), 5.2.5(649), 5.2.6(656),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
5.2.7(667), 5.2.8(676), 5.2.9(685),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
5.2.10(696), 5.2.11(709), 5.2.12(727),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
5.2.13(739), 5.2.14(762), 5.2.15(775),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
5.2.16(790), 5.3.7(872), 5.3.8(886),
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
5.3.9(895), 5.3.10(896), 5.3.11(909),
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
5.3.12(916), 5.3.13(917), 5.3.14(927),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.3.15(933), 5.3.16(934), 5.3.17(945),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.3.18(954), 5.3.19(955), 5.3.20(967),
6.3.1.4(1464), 6.3.1.5(1498),
5.3.21(974), 5.3.22(975), 5.3.24(1002),
6.3.2.1(1510), 6.3.2.2(1523),
5.3.25(1003), 5.3.27(1031), 5.3.28(1031),
6.3.2.3(1538), 6.3.2.4(1549),
5.3.30(1060), 5.3.31(1061), 5.3.32(1075),
6.3.2.5(1559), 6.3.3.1(1575),
5.3.33(1075), 5.3.35(1099), 5.3.36(1100),
6.3.3.2(1582), 6.3.3.3(1610),
5.3.38(1122), 5.3.39(1122), 5.3.41(1146),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.3.42(1147), 5.3.44(1166), 5.3.45(1166),
6.4.2(1687), 6.4.3(1703)
5.3.47(1187), 6.2.1(1378), 6.2.2(1381),
Ericson, 5.3.4(832), 5.3.5(854), 5.3.6(871)
6.2.3(1400), 6.2.4(1400), 6.2.5(1400),
escape characters, 3.6(112)
6.2.6(1400), 6.2.7(1401), 6.3.1.1(1401),
exception handling, 4.32(568)
6.3.1.2(1427), 6.3.1.3(1449),
exceptions, 3.14(300)
6.3.1.4(1464), 6.3.1.5(1498),
expressions, 4.26(511), 4.27(514)
6.3.2.1(1510), 6.3.2.2(1523),
extending classes, 3.12(245)
6.3.2.3(1538), 6.3.2.4(1549),
extends, 5.2.1(612), 5.2.2(619),
6.3.2.5(1559), 6.3.3.1(1575),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.3.3.2(1582), 6.3.3.3(1610),
G
5.2.12(727), 5.2.13(739), 5.2.14(762),
general behavior, 5.4.3(1203)
5.2.15(775), 5.2.16(790), 5.3.7(872),
getPicture, 5.3.4(832), 5.3.5(854),
5.3.8(886), 5.3.9(895), 5.3.10(896),
5.3.6(871)
5.3.11(909), 5.3.12(916), 5.3.13(917),
getter method, 5.3.4(832), 5.3.5(854),
5.3.14(927), 5.3.15(933), 5.3.16(934),
5.3.6(871)
5.3.17(945), 5.3.18(954), 5.3.19(955),
GradientPaint, 5.3.40(1140)
5.3.20(967), 5.3.21(974), 5.3.22(975),
Green-Screen, 5.3.26(1021)
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
Greenfoot, 2.1(5)
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
Guzdial, 5.3.4(832), 5.3.5(854), 5.3.6(871)
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
Guzdial-Ericson Multimedia Class Library,
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
5.3.1(815), 5.3.2(824), 5.3.3(831)
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
J
Java2D, 5.3.40(1140)
Java, 1.1(1), 2.1(5), 3.1(11), 3.2(12),
javadoc, 11.1(1721)
3.3(37), 3.4(69), 3.5(93), 3.6(112),
javadoc comments and directives, 3.15(320)
3.7(140), 3.8(167), 3.9(183), 3.10(203),
3.11(223), 3.12(245), 3.13(266), L List, 5.4.7(1233), 5.4.13(1296),
3.14(300), 3.15(320), 4.2(342), 4.3(346), 5.4.14(1304)
4.4(352), 4.5(356), 4.6(361), 4.7(368), List object, 5.4.6(1227)
O
5.3.22(975), 5.3.24(1002), 5.3.25(1003),
object, 5.2.1(612), 5.2.2(619), 5.2.3(631),
5.3.27(1031), 5.3.28(1031), 5.3.30(1060),
5.2.4(641), 5.2.5(649), 5.2.6(656),
5.3.31(1061), 5.3.32(1075), 5.3.33(1075),
P
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
packages, 3.14(300), 4.35(580)
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
Picture, 5.3.29(1051)
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
Picture class, 5.3.4(832), 5.3.5(854),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.3.6(871)
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
Pictures, 5.3.23(994)
6.3.1.4(1464), 6.3.1.5(1498),
polymorphic behavior, 3.12(245), 3.13(266)
6.3.2.1(1510), 6.3.2.2(1523),
polymorphic methods, 5.4.5(1218)
6.3.2.3(1538), 6.3.2.4(1549),
polymorphism, 5.2.1(612), 5.2.2(619),
6.3.2.5(1559), 6.3.3.1(1575),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.3.3.2(1582), 6.3.3.3(1610),
5.2.6(656), 5.2.7(667), 5.2.8(676),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.2.9(685), 5.2.10(696), 5.2.11(709),
6.4.2(1687), 6.4.3(1703)
5.2.12(727), 5.2.13(739), 5.2.14(762),
primitive types, 3.2(12)
5.2.15(775), 5.2.16(790), 5.3.7(872),
Principles of Object-Oriented Programming,
5.3.8(886), 5.3.9(895), 5.3.10(896),
9.1(1717)
5.3.11(909), 5.3.12(916), 5.3.13(917),
println method, 5.3.4(832), 5.3.5(854),
5.3.14(927), 5.3.15(933), 5.3.16(934),
5.3.6(871)
5.3.17(945), 5.3.18(954), 5.3.19(955),
PrintStream class, 4.20(445), 4.21(449)
5.3.20(967), 5.3.21(974), 5.3.22(975),
Prob01 class, 5.3.4(832), 5.3.5(854),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
5.3.6(871)
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
Prob01Runner class, 5.3.4(832), 5.3.5(854),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
5.3.6(871)
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
programming fundamentals, 4.1(341)
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
Programming Oldies But Goodies,
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
10.1(1719)
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
public, 5.2.1(612), 5.2.2(619), 5.2.3(631),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.2.4(641), 5.2.5(649), 5.2.6(656),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.2.7(667), 5.2.8(676), 5.2.9(685),
6.3.1.4(1464), 6.3.1.5(1498),
5.2.10(696), 5.2.11(709), 5.2.12(727),
6.3.2.1(1510), 6.3.2.2(1523),
5.2.13(739), 5.2.14(762), 5.2.15(775),
6.3.2.3(1538), 6.3.2.4(1549),
5.2.16(790), 5.3.7(872), 5.3.8(886),
6.3.2.5(1559), 6.3.3.1(1575),
5.3.9(895), 5.3.10(896), 5.3.11(909),
6.3.3.2(1582), 6.3.3.3(1610),
5.3.12(916), 5.3.13(917), 5.3.14(927),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.3.15(933), 5.3.16(934), 5.3.17(945),
6.4.2(1687), 6.4.3(1703)
5.3.18(954), 5.3.19(955), 5.3.20(967),
practice programs, 5.5.1(1339), 5.5.2(1354),
5.3.21(974), 5.3.22(975), 5.3.24(1002),
5.5.3(1367)
5.3.25(1003), 5.3.27(1031), 5.3.28(1031),
primitive type, 5.2.1(612), 5.2.2(619),
5.3.30(1060), 5.3.31(1061), 5.3.32(1075),
5.2.3(631), 5.2.4(641), 5.2.5(649),
R
6.3.3.2(1582), 6.3.3.3(1610),
reference, 5.2.1(612), 5.2.2(619),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.4.2(1687), 6.4.3(1703)
5.2.6(656), 5.2.7(667), 5.2.8(676),
reference variables, 4.22(455), 4.23(471)
5.2.9(685), 5.2.10(696), 5.2.11(709),
relational operators, 3.4(69)
5.2.12(727), 5.2.13(739), 5.2.14(762),
reverse method, 5.4.14(1304)
5.2.15(775), 5.2.16(790), 5.3.7(872),
reverse natural order, 5.4.12(1284),
5.3.8(886), 5.3.9(895), 5.3.10(896),
5.4.13(1296)
5.3.11(909), 5.3.12(916), 5.3.13(917),
reverse the order, 5.4.14(1304)
5.3.14(927), 5.3.15(933), 5.3.16(934),
reverseOrder method, 5.4.14(1304)
5.3.17(945), 5.3.18(954), 5.3.19(955),
review, 4.4(352), 4.7(368), 4.9(381),
5.3.20(967), 5.3.21(974), 5.3.22(975),
4.11(392), 4.13(410), 4.15(425),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
4.17(434), 4.19(441), 4.21(449),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
4.23(471), 4.25(494), 4.27(514),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
4.29(537), 4.34(575), 4.37(599),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
5.3.2(824), 5.3.5(854), 5.3.8(886),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
5.3.11(909), 5.3.14(927), 5.3.17(945),
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
5.3.20(967), 5.3.23(994), 5.3.26(1021),
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
5.3.29(1051), 5.3.34(1092), 5.3.37(1115),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.3.40(1140), 5.3.43(1159), 5.3.46(1179)
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
Rotating, 5.3.34(1092)
6.3.1.4(1464), 6.3.1.5(1498),
run method, 5.3.4(832), 5.3.5(854),
6.3.2.1(1510), 6.3.2.2(1523),
5.3.6(871)
6.3.2.3(1538), 6.3.2.4(1549),
6.3.2.5(1559), 6.3.3.1(1575), S Scaling, 5.3.34(1092)
6.3.3.2(1582), 6.3.3.3(1610), search algorithms, 5.4.1(1188)
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673), selection, 4.5(356)
6.4.2(1687), 6.4.3(1703) self assessment, 3.1(11)
reference type, 5.2.1(612), 5.2.2(619), self-assessment, 3.2(12), 3.3(37), 3.4(69),
5.2.3(631), 5.2.4(641), 5.2.5(649), 3.5(93), 3.6(112), 3.7(140), 3.8(167),
5.2.6(656), 5.2.7(667), 5.2.8(676), 3.9(183), 3.10(203), 3.11(223),
5.2.9(685), 5.2.10(696), 5.2.11(709), 3.12(245), 3.13(266), 3.14(300),
5.2.12(727), 5.2.13(739), 5.2.14(762), 3.15(320)
5.2.15(775), 5.2.16(790), 5.3.7(872), sequence, 4.5(356)
5.3.8(886), 5.3.9(895), 5.3.10(896), Set, 5.4.7(1233)
5.3.11(909), 5.3.12(916), 5.3.13(917), Set object, 5.4.6(1227)
5.3.14(927), 5.3.15(933), 5.3.16(934), setBodyColor, 5.3.4(832), 5.3.5(854),
T
5.2.15(775), 5.2.16(790), 5.3.7(872),
The Java Collections Framework, 5.4.5(1218)
5.3.8(886), 5.3.9(895), 5.3.10(896),
this Keyword, 3.11(223)
5.3.11(909), 5.3.12(916), 5.3.13(917),
Tinting, 5.3.29(1051)
5.3.14(927), 5.3.15(933), 5.3.16(934),
toArray method, 5.4.15(1313), 5.4.16(1325)
5.3.17(945), 5.3.18(954), 5.3.19(955),
toString, 3.5(93)
5.3.20(967), 5.3.21(974), 5.3.22(975),
toString method, 5.2.1(612), 5.2.2(619),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
5.2.3(631), 5.2.4(641), 5.2.5(649),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
5.2.6(656), 5.2.7(667), 5.2.8(676),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
5.2.9(685), 5.2.10(696), 5.2.11(709),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
5.2.12(727), 5.2.13(739), 5.2.14(762),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
5.2.15(775), 5.2.16(790), 5.3.7(872),
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
5.3.8(886), 5.3.9(895), 5.3.10(896),
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
5.3.11(909), 5.3.12(916), 5.3.13(917),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.3.14(927), 5.3.15(933), 5.3.16(934),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.3.17(945), 5.3.18(954), 5.3.19(955),
6.3.1.4(1464), 6.3.1.5(1498),
5.3.20(967), 5.3.21(974), 5.3.22(975),
6.3.2.1(1510), 6.3.2.2(1523),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
6.3.2.3(1538), 6.3.2.4(1549),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
6.3.2.5(1559), 6.3.3.1(1575),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
6.3.3.2(1582), 6.3.3.3(1610),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
6.4.2(1687), 6.4.3(1703)
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
super Keyword, 3.10(203)
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
superclass, 5.2.1(612), 5.2.2(619),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
5.2.3(631), 5.2.4(641), 5.2.5(649),
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
5.2.6(656), 5.2.7(667), 5.2.8(676),
6.3.1.4(1464), 6.3.1.5(1498),
5.2.9(685), 5.2.10(696), 5.2.11(709),
6.3.2.1(1510), 6.3.2.2(1523),
V
5.3.12(916), 5.3.13(917), 5.3.14(927),
variable, 5.2.1(612), 5.2.2(619),
5.3.15(933), 5.3.16(934), 5.3.17(945),
5.2.3(631), 5.2.4(641), 5.2.5(649),
5.3.18(954), 5.3.19(955), 5.3.20(967),
5.2.6(656), 5.2.7(667), 5.2.8(676),
5.3.21(974), 5.3.22(975), 5.3.24(1002),
5.2.9(685), 5.2.10(696), 5.2.11(709),
5.3.25(1003), 5.3.27(1031), 5.3.28(1031),
5.2.12(727), 5.2.13(739), 5.2.14(762),
5.3.30(1060), 5.3.31(1061), 5.3.32(1075),
5.2.15(775), 5.2.16(790), 5.3.7(872),
5.3.33(1075), 5.3.35(1099), 5.3.36(1100),
5.3.8(886), 5.3.9(895), 5.3.10(896),
5.3.38(1122), 5.3.39(1122), 5.3.41(1146),
5.3.11(909), 5.3.12(916), 5.3.13(917),
5.3.42(1147), 5.3.44(1166), 5.3.45(1166),
5.3.14(927), 5.3.15(933), 5.3.16(934),
5.3.47(1187), 6.2.1(1378), 6.2.2(1381),
5.3.17(945), 5.3.18(954), 5.3.19(955),
6.2.3(1400), 6.2.4(1400), 6.2.5(1400),
5.3.20(967), 5.3.21(974), 5.3.22(975),
6.2.6(1400), 6.2.7(1401), 6.3.1.1(1401),
5.3.24(1002), 5.3.25(1003), 5.3.27(1031),
6.3.1.2(1427), 6.3.1.3(1449),
5.3.28(1031), 5.3.30(1060), 5.3.31(1061),
6.3.1.4(1464), 6.3.1.5(1498),
5.3.32(1075), 5.3.33(1075), 5.3.35(1099),
6.3.2.1(1510), 6.3.2.2(1523),
5.3.36(1100), 5.3.38(1122), 5.3.39(1122),
6.3.2.3(1538), 6.3.2.4(1549),
5.3.41(1146), 5.3.42(1147), 5.3.44(1166),
6.3.2.5(1559), 6.3.3.1(1575),
5.3.45(1166), 5.3.47(1187), 6.2.1(1378),
6.3.3.2(1582), 6.3.3.3(1610),
6.2.2(1381), 6.2.3(1400), 6.2.4(1400),
6.3.3.4(1623), 6.3.3.5(1637), 6.4.1(1673),
6.2.5(1400), 6.2.6(1400), 6.2.7(1401),
6.4.2(1687), 6.4.3(1703)
6.3.1.1(1401), 6.3.1.2(1427), 6.3.1.3(1449),
6.3.1.4(1464), 6.3.1.5(1498), W World class, 5.3.4(832), 5.3.5(854),
6.3.2.1(1510), 6.3.2.2(1523), 5.3.6(871)
6.3.2.3(1538), 6.3.2.4(1549),
Attributions
Collection: Object-Oriented Programming (OOP) with Java
Edited by: Richard Baldwin
URL: http://cnx.org/content/col11441/1.121/
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0030: Self-assessment, Relational Operators, Increment Operator, and Control Structures"
By: Richard Baldwin
URL: http://cnx.org/content/m45287/1.2/
Pages: 69-93
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0040: Self-assessment, Logical Operations, Numeric Casting, String Concatenation, and the
toString Method"
By: Richard Baldwin
URL: http://cnx.org/content/m45260/1.4/
Pages: 93-112
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0090: Self-assessment, the super keyword, nal keyword, and static methods"
By: Richard Baldwin
URL: http://cnx.org/content/m45270/1.4/
Pages: 203-223
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0100: Self-assessment, The this keyword, static nal variables, and initialization of instance
variables"
By: Richard Baldwin
URL: http://cnx.org/content/m45296/1.3/
Pages: 223-245
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0110: Self-assessment, Extending classes, overriding methods, and polymorphic behavior"
By: Richard Baldwin
URL: http://cnx.org/content/m45308/1.3/
Pages: 245-266
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0130: Self-assessment, Comparing objects, packages, import directives, and some common
exceptions"
By: Richard Baldwin
URL: http://cnx.org/content/m45310/1.3/
Pages: 300-320
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Ap0140: Self-assessment, Type conversion, casting, common exceptions, public class les, javadoc
comments and directives, and null references"
By: Richard Baldwin
URL: http://cnx.org/content/m45302/1.3/
Pages: 320-340
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Jb0105: Java OOP: Similarities and Dierences between Java and C++"
By: Richard Baldwin
URL: http://cnx.org/content/m45142/1.2/
Pages: 342-346
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Jb0190: Java OOP: Using the System and PrintStream Classes"
By: Richard Baldwin
URL: http://cnx.org/content/m45148/1.2/
Pages: 445-448
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java3002: Creating and Manipulating Turtles and Pictures in a World Object"
By: Richard Baldwin
URL: http://cnx.org/content/m44149/1.7/
Pages: 832-853
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java3004: Image Processing Algorithms, Image Inversion, and PictureExplorer Objects"
By: Richard Baldwin
URL: http://cnx.org/content/m44203/1.6/
Pages: 872-885
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java3022: Scaling, Rotating, and Translating Images using Ane Transforms"
By: Richard Baldwin
URL: http://cnx.org/content/m44223/1.6/
Pages: 1075-1091
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java4060: Duplicate Elements, Ordered Collections, Sorted Collections, and Interface Specializa-
tion"
By: Richard Baldwin
URL: http://cnx.org/content/m46141/1.2/
Pages: 1227-1233
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Event Handling in JDK 1.1, A First Look, Delegation Event Model"
By: Richard Baldwin
URL: http://cnx.org/content/m44340/1.1/
Page: 1400
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Background Color, Text Color, Mouse Clicks, etc."
By: Richard Baldwin
URL: http://cnx.org/content/m44351/1.1/
Pages: 1464-1497
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Using Alpha Transparency with Ericson's Media Library"
By: Richard Baldwin
URL: http://cnx.org/content/m44911/1.1/
Pages: 1510-1523
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Controlling Image Rotation with a Slider and Ane Transforms"
By: Richard Baldwin
URL: http://cnx.org/content/m44915/1.3/
Pages: 1559-1575
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Extracting pixel color data from a PictureExplorer object"
By: Richard Baldwin
URL: http://cnx.org/content/m44917/1.2/
Pages: 1582-1610
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Java OOP: Handling document events on a text eld and creating a color swatch"
By: Richard Baldwin
URL: http://cnx.org/content/m44921/1.2/
Pages: 1610-1623
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
About Connexions
Since 1999, Connexions has been pioneering a global system where anyone can create course materials and
make them fully accessible and easily reusable free of charge. We are a Web-based authoring, teaching and
learning environment open to anyone interested in education, including students, teachers, professors and
lifelong learners. We connect ideas and facilitate educational communities.
Connexions's modular, interactive courses are in use worldwide by universities, community colleges, K-12
schools, distance learners, and lifelong learners. Connexions materials are in many languages, including
English, Spanish, Chinese, Japanese, Italian, Vietnamese, French, Portuguese, and Thai. Connexions is part
of an exciting new information distribution system that allows for Print on Demand Books. Connexions
has partnered with innovative on-demand publisher QOOP to accelerate the delivery of printed course
materials and textbooks into classrooms worldwide at lower prices than traditional academic publishers.