Академический Документы
Профессиональный Документы
Культура Документы
Programming Language
JAH-CJ-200
Student Guide
Publishing Information
This publication has been produced using Microsoft Word 2000 and Microsoft PowerPoint 2000 for
Windows.
2
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Table of Contents
About This Course
Course Goal
7
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
8
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 01
Introduction to the Java Programming Language
Objectives
What is Java?
Goals of Java
The Java Programming Language
The Java evolution
The Java platform
The Java execution model
Uses of Java
Programs
Components
Objectives
Upon completion of this module, you should be able to:
Describe the history and properties of the Java programming language
Explain the Java execution model, including the use of byte code and the Java
virtual machine
Outline the types of programs and components that can be built using Java
9
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
What is Java?
Notes:
Java shares characteristics of other object-oriented languages such as C++ and Smalltalk,
and has the following advantages:
10
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Goals of Java
Notes:
Object Orientation: Object orientation has long been considered to be the best
paradigm for software development. Java is object-oriented.
Portability: A big problem with any compiled language is that different executables
are needed for different platforms. The Java virtual machine runtime environment
allows source-level and binary-level portability.
Performance: Portability has been achieved by interpreted languages such as
BASIC. The compromise that has been made is that interpreted languages are
dramatically slower than compiled languages because they must be interpreted as
they run. The Java solution was the JVM and bytecode, which will be discussed in
this unit.
Security: Another problem with portable code is its safety. Java has built-in security
mechanisms to help prevent malicious programming. For example, a certain type of
Java program called an applet has a much more restricted environment in which to
run than does an application.
Internationalization: With portability comes the issue of local preferences, such as
language, date and time formats, currencies, and so forth. Java provides facilities for
internationalization of programs which may allow interaction between the program
and the user's local language.
Distributed Computing: To achieve a Web application environment, the language
of choice has to have excellent networking capabilities built in, and Java provides
these facilities.
Dynamic Systems: Java uses a large number of separate components which are
dynamically interchangeable.
11
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Object-oriented
Java supports software development using the notion of
objects
Software developed using Java is composed of classes and
objects
Notes:
The Java programming language is an object-oriented programming (OOP) language
because one of the main goals of the Java programmer is to create objects, pieces of
autonomous code, that can interact with other objects to solve a problem. OOP started with
the SIMULA-67 programming language in 1967 and has led to popular programming
languages, such as C++, upon which the Java programming language is loosely based.
12
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Network capable
Java supports the development of distributed applications
Some types of Java applications are designed to be accessed
through a Web browser
Notes:
Java has facilities to allow programmers to easily deal with the creation of network
connections, and work with network protocols such as HTTP. Applets and Web
applications (composed of servlets and JSPs) are two types of Java application that are
designed to be accessed through the Web.
13
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Robust
Many aspects of Java promote the development of reliable
software
Java uses a pointer model which does not allow direct
access to memory; memory cannot be overwritten
Secure
Java authentication is based on public-key encryption
methods
Javas pointer model protects private data in objects and
prevents unauthorized applications from accessing data
structures
Notes:
Java does not use pointers, and uses true arrays as opposed to pointer arithmetic. Java's
implementation of arrays allows subscript checking to be done. Also, because Java does
not use pointers, the end of memory buffers cannot be overwritten, and unauthorized
access to memory is prevented.
Program robustness and security are highly related topics, as both strongly relate to how
Java manages access to memory.
14
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Multi-threaded
Allows your program to run more than one task at the same
time
Notes:
The Java programming language supports multithreading, that is performing several tasks
at a time, such as querying a database and displaying a user interface. Multithreading
allows a Java program to be very efficient in its use of system resources.
Threads are also described as lightweight processes; they allow for concurrent paths of
execution through code. C and C++ are single-threaded, and allowing applications to have
multiple threads can increase the difficulty of writing a program, as such programs must
handle concurrent paths of execution through code. Java includes facilities to deal with
synchronization.
15
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The Java virtual machine is a piece of software that acts as a virtual CPU, interpreting
bytecode instructions and then executing these instructions. Bytecode is platform
independent, while the Java virtual machine is specific to a platform.
The Java language is not specific to any computer platform, which allows Java programs to
be portable. For example, primitive data types, such as integers and floats, have an
identical definition over all platforms. Though source and binary code are portable between
operating system platforms, the JVM is specific to the operating system where the program
runs.
16
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Like C and C++ programs, Java programs are also compiled using a Java compiler.
However, the resulting format of a compiled Java program is platform-independent Java
bytecode instead of CPU-specific machine code. After the bytecode is created, it is
interpreted (executed) by a bytecode interpreter called the virtual machine or VM. A virtual
machine is a platform-specific program that understands platform-independent bytecode
and can execute it on a particular platform. For this reason, the Java programming
language is often referred to as an interpreted language, and Java programs are said to be
portable or executable on any platform.
For Java programs to be platform-independent, a virtual machine called the Java virtual
machine (JVM) is required on every platform where your programming will run. The Java
virtual machine is responsible for interpreting Java code, loading Java classes, and
executing Java programs. However, a Java program needs more than just a Java virtual
machine to execute. A Java program also needs a set of standard Java class libraries for
the platform. Java class libraries are libraries of pre-written code that can be combined with
the code you write to create robust applications.
Combined, the JVM software and Java class libraries are referred to as the Java runtime
environment (Java RE). Java runtime environments are available from Sun Microsystems
for many common platforms.
17
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Java evolution
Notes:
The Java programming language originated in 1991 as part of a research project to
develop a programming language, called Oak, that World bridge the communication gap
between many consumer devices, such as video cassette recorders (VCRs) and
televisions. Specifically, a team of highly skilled software developers (called the Green
team), wanted to create a programming language enabling consumer devices with different
central processing units (CPUs) to share the same software enhancements.
This initial concept failed after several deals with consumer device companies were
unsuccessful. The Green team was forced to find another market for their new
programming language. Fortunately, the World Wide Web was becoming popular and the
Green team recognized that the Oak language was perfect for developing Web multimedia
components to enhance Web pages. These small applications, called applets, became the
initial use of the Oak language and programmers using the Internet adopted what became
the Java programming language.
18
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
A platform is a development or
deployment environment
The Java platform runs on any
operating system
Other platforms are
hardware and vendor
specific
The Java platform provides:
The Java virtual
machine (JVM)
Application Programming
Interface (API)
Notes:
Java programs make use of the Java API; when completed, programs are compiled into
bytecode. This bytecode is interpreted by the Java virtual machine, and that same
bytecode can be interpreted by Java virtual machines residing on other computers of
different platforms or architectures. A Java program runs on the Java virtual machine; the
JVM runs on a real machine, on the host platform.
19
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
In a compiled language, a compiler translates the source code of a program into a binary
file of machine code. The machine code is understood and executed by the hardware and
the operating system. Java, however, is compiled into bytecode; bytecode is understood
and executed by the Java virtual machine. The Java virtual machine runs on an operating
system, and the bytecode is interpreted by the JVM. Java source code is written once, and
can be run in any environment which has the Java virtual machine installed. The source
code and bytecode remain the same no matter where the program is to be run.
20
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Java bytecode can be executed by the Java virtual machine in three ways:
1. Bytecode can be interpreted and executed
2. Bytecode can be translated into executable instructions for the specific platform and
then executed (called just-in-time or JIT compilation)
3. Bytecode can act as the native machine code for a platform built using Java chips;
in this case, no compiler or interpreter is used, and bytecode is executed directly
21
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
22
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Uses of Java
Notes:
A component is a building block of larger programs. Ideally, programs are built from
components, and components are designed to be reusable by many programs.
23
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Programs
Application
A stand-alone program that can access system resources such
as files
Does not need to run in a Web browser
Is explicitly invoked through the command line or menu
selection
The method main() is the entry point for an application
Notes:
An application is a type of program that runs on a single machine or over a network, and
interacts with the computers operating systems.
24
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Programs
Applet
A Java program that is embedded within a Web page; almost
always graphical
Security limits access to system resources
Code executes on the client inside a Web browser
Notes:
Applets are different from applications; they are not self-contained programs and are more
like applications fragments. Applets run within the browser, not the operating system.
An applet is stored on a server, and is transmitted to the client when its HTML <APPLET>
tag is accessed. Applets are usually visual programs and have limited access to the client
operating system in order to preserve client security.
25
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Components
Servlet
Handles requests from the Web browser and returns
responses
Creates dynamic content on the server
Runs inside an application server
JavaServer Page (JSP)
HTML page embedded with Java code
Creates dynamic content on the server instead of on the
browser
Runs inside an application server
Notes:
An application server is a special server which allows you to run enterprise Java
components such as servlets, JSPs, and EJBs.
Servlet: Servlets are commonly used to interact with Web sites. Typically, a set of HTML
pages interacts with the user, and then sends the collected data to the servlet to be
processed. It usually interacts with database and other server-side components. Servlets
are capable of writing HTML dynamically.
JavaServer Page: JSPs are a way of creating HTML dynamically as well. They are in
essence HTML pages with special tags that represent Java functions. Servlets and JSPs
are Web components that are a part of the Java 2 Enterprise Edition (J2EE) architecture.
Servlets and JSPs require special support, and run on a platform, called a Web container,
that provides this support.
Servlets and JSPs are the building blocks of enterprise Java applications. Though they run
the same way and can provide the same functionality, the way servlets and JSPs are
coded in Java lends these components to different tasks within an application.
26
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Components
JavaBeans
Java code that has its properties, methods, and events
exposed to promote reuse among developers
Reusable software component that can be manipulated
visually in a builder tool
Notes:
JavaBeans are a software component that can be reused throughout the Java language by
many other types of Java programs and components: JSPs, EJBs, and so forth. A
JavaBean is simply a class that has been written in a manner that exposes its properties,
methods and events in a standard way; it is a class that adheres to certain standards to
promote reuse.
JavaBeans have many different uses, including being used within enterprise Java
applications. Some JavaBeans have a visual representation at run time, while others do
not. One use of JavaBeans is to store information that must be passed within an
application and allow it to be retrieved by different parts of the application. EJBs are serverside components that are a part of the Java 2 Enterprise Edition (J2EE) architecture.
These components are run on a Java-enabled Web server; they also require special
support, and are run on a platform, called an EJB container, that provides this support.
27
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Components
Notes:
28
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 02
Developing and Testing a Java Program
Objectives
Identifying the Components of a Class
o Structuring Classes
o Class Declaration
o Variable Declarations and Assignments
o Comments
o Methods
Creating and Using a Test Class
o The main method
Compiling and Executing (Testing) a Program
o Compiling a Program
Executing (Testing) a Program
Debugging Tips
Objectives
Upon completion of this module, you should be able to:
Identify the four components of a class in the Java programming language
Use the main method in a test class to run a Java program from the command line
Compile and execute a Java program
29
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Classes are the blueprints that you create to define the objects
in a program.
Notes:
An object simply represents any object that you may think of in the "real world".
we define objects by creating a class.
In Java,
30
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Structuring Classes
//Employee.java
//Employee.java
public
public class
class Employee
Employee {{
private
private String
String id;
id;
private
private String
String lastName;
lastName;
Methods
}}
public
public int
int getId()
getId() {}
{}
public
public void
void setId()
setId() {}
{}
Notes:
Classes are composed of the Java code necessary to instantiate objects, such as Shirt
objects. This course divides the code in a Java class file into four separate sections:
The class declaration
Attribute variable declarations and initialization (optional)
Methods (optional)
Comments (optional)
31
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Structuring Classes
private
private int
int keys
keys == 88;
88;
//this
//this method
method displays
displays the
the number
number of
of keys
keys of
of piano
piano
public
public void
void displayPianoInformation()
displayPianoInformation() {{
System.out.println("
System.out.println("AA piano
piano has
has "" ++ keys
keys ++ "" keys.");
keys.");
}} //end
//end of
of display
display method
method
}} //end
//end of
of class
class
Notes:
The programming code for a class is contained within a text file that must adhere to a
certain structure. The following example shows a Piano class. The Piano class has one
attribute variable and one method.
32
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Class Declaration
Syntax:
[modifier] class class_identifier
Example:
public class Piano
public class Cat
public class Shirt
//Piano.java
//Piano.java
public
public class
class Shirt
Shirt {{
//write
//write your
your code
code here
here
}} //end
//end of
of class
class
Notes:
For each class, you must write a class declaration. The syntax for declaring a class is:
[modifier] class class_identifier
where:
[modifier] determines the accessibility that other classes have to this class. The
[modifier] is optional (indicated by the square brackets) and can be public, abstract,
or final. For now, use the public modifier.
The class keyword tells the compiler that the code block is a class declaration.
Keywords are words that are reserved by the Java programming language for
certain constructs.
The class_identifier is the name that you give to the class. Class naming guidelines
are as follows:
o Class names should be nouns, in mixed case with the first letter of each word
capitalized, for example, MyClass.
o Class names should contain whole words. Avoid acronyms and abbreviations
(unless the abbreviation is much more widely used than the long form, such
as JVM or UML).
33
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Class Declaration
public
public class
class Shirt
Shirt {{
public
public int
int shirtID
shirtID == 0;
0; //
// Default
Default ID
ID for
for the
the shirt
shirt
public
public String
String description
description == "-description
"-description required-";
required-"; //
// default
default
//
// The
The color
color codes
codes are
are R=Red,
R=Red, B=Blue,
B=Blue, G=Green,
G=Green, U=Unset
U=Unset
public
public char
char colorCode
colorCode == U;
U;
public
public double
double price
price == 0.0;
0.0; //
// Default
Default price
price for
for all
all shirts
shirts
public
int
quantityInStock
=
0;
//
Default
quantity
public int quantityInStock = 0; // Default quantity for
for all
all shirts
shirts
//
// This
This method
method displays
displays the
the values
values for
for an
an item
item
public
public void
void displayShirtInformation()
displayShirtInformation() {{
System.out.println("Shirt
System.out.println("Shirt ID:
ID: " " ++ shirtID);
shirtID);
System.out.println("Shirt
description:"
System.out.println("Shirt description:" ++ description);
description);
System.out.println("Color
System.out.println("Color Code:
Code: " " ++ colorCode);
colorCode);
System.out.println("Shirt
System.out.println("Shirt price:
price: " " ++ price);
price);
System.out.println("Quantity
System.out.println("Quantity in
in stock:
stock: " " ++ quantityInStock);
quantityInStock);
}} //
// end
end of
of display
display method
method
}} //
// end
end of
of class
class
Notes:
In this course, you will be developing your classes so that the Java programming code you
write for each class is in its own text file or source code file. In the Java programming
language, source code file names must match the public class name in the source code file
and must have a .java extension. For example, the Shirt class must be saved in a file
called Shirt.java.
The class definition is followed by an open curly brace ({) indicating the beginning of the
class_body, the attribute variables, and the methods that compose the class. The braces {
} around the class_body define where the class starts and ends.
34
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Shirt id
Description
Color Code
Price
Quantity in stock
Notes:
The attribute variable declarations and assignments block follows the first open curly brace
({). Generally, you set up all of the attribute variables for the class after this brace.
The Shirt class code example contains five attribute variable declarations, one for a shirt
ID, one for a description, one for a color code, one for price, and one for a quantity in stock.
35
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Comments
Notes:
You should put comments in every class that
what the program is doing. Commenting is
developed by large teams where several
Commenting helps with the maintenance of a
determine what the code is doing.
Single-line comments A // marker tells the compiler to ignore everything to the end
of the current line. In long programs, it can be very difficult to find the ending braces
of the class. Commenting the structure that each ending brace belongs to makes
reading and fixing errors much easier.
Traditional comments A /* character combination tells the compiler to ignore
everything on all lines up to, and including, a comment termination marker (*/).
Programmers often use traditional comments to provide details for a large block of
code.
There is a third type of comment called a documentation comment. You can use a
Java tool, the Javadoc software, to create documentation for any of your classes
that will be used by other programmers. In fact, all of the class library documentation
that comes with the J2SE SDK was created using the javadoc tool. Documentation
comments must begin with a forward slash and two asterisks (/**) and end with an
asterisk and a forward slash (*/).
36
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Methods
Syntax:
[modifiers] return_type method_identifier([arguments]){
method_code_block
}
Example:
public
public void
void displayShirtInformation()
displayShirtInformation() {{
System.out.println("Shirt
System.out.println("Shirt ID:
ID: "" ++ shirtID);
shirtID);
System.out.println("Shirt
description:"
System.out.println("Shirt description:" ++ description);
description);
System.out.println("Color
System.out.println("Color Code:
Code: "" ++ colorCode);
colorCode);
System.out.println("Shirt
System.out.println("Shirt price:
price: "" ++ price);
price);
System.out.println
("Quantity
in
stock:
"
System.out.println("Quantity in stock: " ++ quantityInStock
quantityInStock);
);
}} //
end
of
display
method
// end of display method
Notes:
Methods follow the attribute variable declarations in a class. The syntax for methods is:
[modifiers] return_type method_identifier ([arguments]) {
method_code_block
}
where:
The [modifiers] represent several unique Java keywords that modify the way
methods are accessed. Modifiers are optional (indicated by the square brackets).
The return_type indicates the type of value (if any) that the method returns. If the
method returns a value, the type of the value must be declared. Returned values
can be used by the calling method. Any method can return at most one value. If the
method returns nothing, the keyword void must be used as the return_type.
The method_identifier is the name of the method.
The ([arguments]) represent a list of variables whose values are passed to the
method for use by the method. Arguments are optional (as indicated by the square
brackets) because methods are not required to accept arguments. Also note that the
parentheses are not optional. A method that does not accept arguments is declared
with an empty set of parentheses.
The method_code_block is a sequence of statements that the method performs. A
wide variety of tasks can take place in the code block or body of the method.
37
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Methods
Classes
Classesin
inJava
Javamay
mayhave
havemethods
methodsand
andattributes.
attributes.
Methods
define
actions
that
a
class
can
perform.
Methods define actions that a class can perform.
Attributes
Attributesdescribe
describethe
theclass.
class.
Notes:
38
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
Shirt.java
ShirtTest.java
public
public class
class Shirt
Shirt {{
public
public void
void displayShirtInformation()
displayShirtInformation()
{{
}}
}}
public
public class
class ShirtTest
ShirtTest {{
public
static
public static void
void main
main (String
(String args[])
args[]) {{
Shirt
myShirt;
Shirt myShirt;
myShirt
myShirt == new
new Shirt();
Shirt();
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
}}
}}
Notes:
Most of the classes that you create throughout this course cannot be used (executed and
tested) by themselves. Instead, you must execute another class to create an object
instance of your class before your class can be tested.
Throughout this course, you use a test or main class to test each of your classes. Every
test class within this course should be named so that it can be recognized as the test class
for a particular class you have written.
Specifically, each test class name should consist of the name of the class you are testing,
followed by the word Test. For example, the class designed to test the Shirt class is
called ShirtTest.
Test classes have two distinct tasks to perform. These are:
Providing a starting point, called the main method, for your program
Creating an object instance of your class and testing its methods
39
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
public static void main (String args[])
The main() method is the normal entry point for Java
applications
To create an application, you write a class definition that
includes a main() method
Notes:
The main method is a special method that the Java virtual machine recognizes as the
starting point for every Java program that runs from the command line or from a prompt.
Any program that you want to run from a command line or a prompt must have a main
method.
The syntax for the main method is:
public static void main (String args[])
The main method contains two required modifiers, public and static. The main
method does not return any values, so it has a return type of void.
The main method has a method identifier (name) of main.
The main method accepts zero or more objects of type String (String args[]). This
syntax allows you to type in values on the command line to be used by your
program while it is running.
40
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The code for the method appears between the pair of curly braces. This version of the
method has only one executable statement:
System.out.println(Rome wanst burn in a day!!);
System is the name of a standard class that contains objects that encapsulate the
standard I/O devices for your systemthe keyboard for command-line input and
command-line output to the display. It is contained in the package java.lang, so it is
always accessible just by using the simple class name System.
The object out represents the standard output streamthe command line on your
display screenand is a data member of the class System. The member, out, is a
special kind of member of the System class. Like the method main() in our
OurFirstProgram class, it is static. This means that out exists even though there are
no objects of type System Using the class name, System, separated from the
member name out by a periodSystem.outreferences the out member.
The bit at the rightmost end of the statement, println(Rome wasnt burn in a day!!),
calls the println() method that belongs to the object out, and that outputs the text
string that appears between the parentheses to your display. This demonstrates one
way in which you can call a class methodby using the object name followed by the
method name, with a period separating them. The stuff between the parentheses
following the name of a method is information that is passed to the method when it
is executed. As we said, for println() it is the text we want to output to the command
line.
41
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Compiling a program
Notes:
42
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Compiling a program
Notes:
After the compilation has finished, and assuming no compilation errors have occurred, you
should have a new file called classname.class in your directory for each source code file
that you compiled. If you compile a class that references other objects, the classes for
those objects are also compiled (if they have not been compiled already). For example, if
you compiled the ShirtTest.java file (which references a Shirt object), you have a
Shirt.class and ShirtTest.class file.
43
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
When you have successfully compiled your source code files, you can execute and test
them using the Java virtual machine.
44
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Debugging Tips
Notes:
You will almost always have at least one error in any code you write. Debugging is the term
used for fixing errors or bugs in your code.
When the compiler reports a syntax error, the error may not be on the line number
indicated by the error message. First, check the line for which the error was reported. If that
line does not contain syntax errors, check the preceding several lines in the program.
The Java compiler generates syntax error messages when the syntax of a program is
incorrect. When you are learning how to program, sometimes it is helpful to break a
working program so you can see the error messages produced by the compiler. Then,
when you encounter that error message again, you will have an idea of the errors cause.
45
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 03
Writing, Compiling, and Testing a Basic Program Lab
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Become familiar with the structure and parts of a basic Java Program.
46
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Solutions:
47
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Solutions:
48
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Solutions:
49
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 04
Declaring, Initializing, and Using Variables
Objectives
Identifying Variable Use and Syntax
o Uses for Variables
o Variable Declaration and Initialization
Describing Primitive Data Types
o Integral Primitive Types
o Floating Point Primitive Types
o Textual Primitive Type
o Logical Primitive Type
o Choosing a Data Type
Declaring Variables and Assigning Values to Variables
o Naming a Variable
o Assigning a Value to a Variable
o Constants
o Storing Primitive and Constants in Memory
Using Arithmetic Operators to Modify Values
o Standard Mathematical Operators
o Increment and Decrement Operators (++ and --)
o Operator Precedence
Using Promotion and Type Casting
o Casting primitive types
o Implicit versus explicit casting
o Examples
Objectives
Upon completion of this module, you should be able to:
Identify the uses for variables and define the syntax for a variable
List the eight Java programming language primitive data types
Declare, initialize, and use variables and constants according to Java programming
language guidelines and coding standards
Modify variable values using operators
Use promotion and type casting
50
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class PianoKeys
PianoKeys {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
int
int keys
keys == 88;
88;
System.out.println(
System.out.println("A
"A piano
piano has
has "" ++ keys
keys ++ "" keys."
keys.");
);
}}
}}
Notes:
A variable is a name for a location in memory used to hold a data value. A variable
declaration instructs the compiler to reserve a portion of main memory space large enough
to hold a particular type of value and indicates the name by which we refer to that location.
Consider the program PianoKeys, shown above. The first line of the main method is the
declaration of a variable named keys that holds an integer (int) value. The declaration also
gives keys an initial value of 88. If an initial value is not specified for a variable, the value is
undefined. Most Java compilers give errors or warnings if you attempt to use a variable
before youve explicitly given it a value.
51
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class Geometry
Geometry {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
int
int sides
sides == 7;
7; //
// declaration
declaration with
with initialization
initialization
System.out.println(
"A
heptagon
has
"
+
System.out.println("A heptagon has " + sides
sides ++ "" sides."
sides.");
);
sides
=
10;
//
assignment
statement
sides = 10; // assignment statement
System.out.println("A
System.out.println("A decagon
decagon has
has "" ++ sides
sides ++ "" sides.");
sides.");
sides
sides == 12;
12;
System.out.println(
System.out.println("A
"A dodecagon
dodecagon has
has "" ++ sides
sides ++ "" sides."
sides.");
);
}}
}}
Notes:
A variable can store only one value of its declared type. A new value overwrites the old
one. In this case, when the value 10 is assigned to sides, the original value 7 is overwritten
and lost forever. However, when a reference is made to a variable, such as when it is
printed, the value of the variable is not changed.
The Java language is strongly typed, meaning that we are not allowed to assign a value to
a variable that is inconsistent with its declared type. Trying to combine incompatible types
will generate an error when you attempt to compile the program. Therefore, the expression
on the right-hand side of an assignment statement must evaluate to a value compatible
with the type of the variable on the left-hand side.
52
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Examples:
id = 428890;
price = 2.35F;
myChar = t;
isOpen = false;
The = operator assigns the value on the right side to the item on the left side. The operator
should be read as is assigned to.
53
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Attribute variable declarations and initialization follow the same general syntax. The syntax
for attribute variables declaration and initialization is:
[modifiers] type identifier = value;
Local variables can be declared and initialized separately (on separate lines of code) or in
a single line of code. The syntax for declaring a variable inside of a method is:
type identifier;
The syntax for initializing a variable inside of a method is:
identifier = value;
The syntax for declaring and initializing a variable inside of a method is:
type identifier = value;
54
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Many of the values in Java programs are stored as primitive data types. These are the
eight primitive types built into the Java programming language. The sizes of the primitives
are defined by the JVM. They are the same on all platforms.
55
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
There are four integral primitive types in the Java programming language, identified by the
keywords byte, short, int, and long. These types store numbers that do not have decimal
points.
When you specify a literal value for a long type, put a capital L to the right of the value to
explicitly state that it is a long type. Integer literals are assumed by the compiler to be of
type int unless you specify otherwise using an L indicating long type.
The Shirt class contains two integral types, int, to hold the default value for a shirt ID and
the quantity in stock, respectively:
public int shirtID = 0; // Default ID for the shirt
public int quantityInStock = 0; // Default quantity for all shirts
56
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
For each of the binary numbers shown here, the leftmost bit is the sign bit, marked with an
s. When the sign bit is 0 the number is positive, and when it is 1 the number is negative.
Binary negative numbers are represented in what is called 2s complement form.
57
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class IntegralType
IntegralType {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
byte
age
=
12;
byte age = 12;
short
short idCourse
idCourse == 1230;
1230;
int
javaProgrammers
int javaProgrammers == 2300000;
2300000;
long
worldPeople
=
5000000000L;
long worldPeople
= 5000000000L;
System.out.println(worldPeople);
System.out.println(worldPeople);
}}
}}
Notes:
If you want to define an integer literal of type long, you need to append an L to the value.
The values 1L, -9999L, and 123456789L are all of the type long
58
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
There are two types for floating point numbers, float and double. They are used to store
numbers with values to the right of the decimal point. As with the different integer types,
these share functionality but differ in size.
It is not possible to state the largest or smallest value that each of these can hold because
they allow variable accuracy depending on the magnitude of the number. (That is, the
number can hold X number of digits, but the placement of the decimal point determines
whether it is an extremely large number, or whether it is a small number like pi)
When you specify a literal value for a float type, put a capital F (float) to the right of the
value to explicitly state that it is a float type, not a double type. Literal values for floating
point types are assumed to be of type double unless you specify otherwise, using the F
indicating float type.
59
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class Tax
Tax {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
double
price
=
20;
double price = 20;
float
float tax
tax == 0.15f;
0.15f;
double
double total;
total;
total
total == price
price ** tax;
tax;
System.out.println(
System.out.println( total
total );
);
}}
}}
Notes:
Floating-point literals are of type double by default, so 1.0 and 345.678 are both of type
double. When you want to specify a value of type float, you just append and f, or an F, to
the value, so 1.0f and 345.678F are both literals of type float.
60
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Another data type you use for storing and manipulating data is single-character
information. The primitive type used for storing a single character, such as a y is char,
which is 16 bits in size.
You can store only one character in a char variable. If you want to store whole words or
phrases you use an object type (not primitive type) called String.
When you assign a literal value to a char variable, such as t, you must use single quotation
marks around the character: t
Using single quotation marks around the character clarifies for the compiler that the t is just
the literal value t, rather than a variable t that represents another value.
The char type does not store the actual character you type, such as the t shown. The char
representation is reduced to a series of bits that corresponds to a character. The numbercharacter mappings are set up in the character set that the programming language uses.
The Java programming language uses a 16-bit character set called Unicode that can store
all the necessary displayable characters from the vast majority of languages used in the
modern world. Therefore, your programs can be written so that they work correctly and
display the correct language for most countries. Unicode contains a subset of ASCII (the
first 128 characters).
61
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class PrintChar
PrintChar {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
char
c
=
'x';
char c = 'x';
int
int ii == c;
c;
System.out.println(
System.out.println( "Print:
"Print: "" ++ cc );
);
System.out.println(
"Print:
System.out.println( "Print: "" ++ ii );
);
cc == 88;
88;
System.out.println(
System.out.println( "Print:
"Print: "" ++ cc );
);
}}
}}
Notes:
Variables of type char store a single character code. They each occupy 16 bits, or 2 bytes,
in memory because all characters in Java are stored as Unicode.
62
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Variables of type boolean can store only:
63
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class CatDog
CatDog {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
boolean
boolean personWithDog
personWithDog == true;
true;
boolean
personWithCat
boolean personWithCat == false;
false;
System.out.println(
System.out.println("personWithDog
"personWithDog is
is "+personWithDog
"+personWithDog);
);
System.out.println(
"personWithCat
is
"+personWithCat
);
System.out.println("personWithCat is "+personWithCat);
}}
}}
Notes:
Variables of type boolean can have only of two values, true or false. The values true and
false are boolean literals.
64
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Naming a Variable
Rules:
Variable identifiers must start with either an uppercase or
lowercase letter, an underscore (_), or a dollar sign ($).
Variable identifiers cannot contain punctuation, spaces, or
dashes.
Java keywords cannot be used.
Guidelines:
Begin each variable with a lowercase letter; subsequent
words should be capitalized, such as myVariable.
Chose names that are mnemonic and that indicate to the
casual observer the intent of the variable.
Notes:
Just as with a class or method, you must assign each variable in your program an identifier
or a name. Remember, the purpose of the variable is to act as a mechanism for storing
and retrieving values. Therefore, you should make variable identifiers simple but
descriptive.
For example, if you store the value of an item ID, you might name the variable myID,
itemID, itemNumber, or anything else that clarifies the use of the variable to yourself, and
to others reading your program.
The Java programming language is a case-sensitive programming language. Case
sensitivity means distinguishing between the uppercase and lowercase representations of
each alphabetical character. The Java programming language considers two characters in
your code to be different if their capitalization differs. For example, a variable called order is
different from a variable called Order.
65
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
double price = 12.99;
Example (boolean):
boolean isOpen = false;
Notes:
You can assign a value to a variable at the time the variable is declared or you can assign
the variable later. To assign a value to a variable during declaration, add an equal sign
after the declaration followed by the value to be assigned. For example, the price attribute
variable in the Shirt class could be assigned the value 12.99 as the price for a Shirt object.
double price = 12.99;
An example of boolean variable declaration and assignment is:
boolean isOpen = false;
The = operator assigns the value on the right side to the item on the left side. The =
operator should be read as is assigned to. In a previous example you could say, 12.99 is
assigned to price.
Attribute variables are automatically initialized: integral types are set to 0, floating point
types are set to 0.0, the char type is set to \u0000, and the boolean type is set to false.
However, you should explicitly initialize your attribute variables so that other people can
read your code. Local variables (declared within a method) must be explicitly initialized
before being used.
66
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
type identifier = value [, identifier = value];
Example:
double price = 0.0, wholesalePrice = 0.0;
int miles
furlong
yards
feet
=
=
=
=
0,
0,
0,
0;
Notes:
You can declare one or more variables on the same line of code, but only if they are all of
the same type. The syntax for declaring several variables in one line of code is:
type identifier = value [, identifier = value];
Therefore, if there is a separate retail price and wholesale price in the Shirt class, they
might be declared as follows:
double price = 0.0, wholesalePrice = 0.0;
67
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Explicit data values that appear in your program are called literals. Each literal will also be
of a particular type: int, float, double, etc.
68
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
69
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Constants
Notes:
A variable that is declared using the final modifier denotes its inability to have its value
changed once initialized. Use all capital letters and underscores for identifier.
70
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
When you use a literal value or create a variable or constant and assign it a value, the
value is stored in the memory of the computer. The figure illustrates that local variables
are stored separately (on the stack) from attribute variables on the heap.
Objects and their attribute variables and methods are usually stored in heap memory. Heap
memory is dynamically allocated memory chunks containing information used to hold
objects (including their attribute variables and methods) while they are needed by your
program. Other variables are usually stored in stack memory. Stack memory stores items
that are only used for a brief period of time (shorter than the life of an object), such as
variables declared inside of a method.
71
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Arithmetic operators are used to indicate arithmetic operations like addition, subtraction,
multiplication, division, and modulo operations.
The + operator is used to indicate the addition operation. It is used for adding values stored
in two or more variables. The following expression illustrates the use of the + operator:
a+b
The - operator is used to indicate the subtraction operation. It is used for subtracting a
value stored in one variable from a value stored in another variable. The following
expression illustrates the use of the operator:
a-b
The * operator is used to indicate the multiplication operation. It is used for multiplying
values stored in two variables. The following expression illustrates the use of the *operator:
a*b
The / operator is used to indicate the division operation. It is used to divide a value stored
in one variable by a value stored in another variable. The following expression illustrates
the use of the / operator:
a/b
72
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
73
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The % operator is used to indicate the modulo operation. It is used to find the remainder
after dividing a value stored in one variable by a value stored in another variable. The
following expression illustrates the use of the % operator:
a%b
74
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The first three statements in main() declare the variables numOranges, numApples, and
numFruit to be of type int and initialize them to the values 5, 10, and 0, respectively. The
next statement adds the values stored in numOranges and numApples, and stores the
result, 15, in the variable numFruit. We then generate some output from the program.
75
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
76
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
A common requirement in programs is to add or subtract 1 from the value of a variable.
You can do this by using the + operator, as follows:
age = age + 1;
However, incrementing or decrementing by 1 is such a common action that there are
specific unary operators for it: the increment (++) and decrement (--) operators. These
operators can come before (pre-increment and pre-decrement) or after (post-increment
and post-decrement) a variable.
Use these operators within an expression cautiously. With the prefix form, the operation
(increment or decrement) is applied before any subsequent calculations or assignments.
With the postfix form, the operation is applied after the subsequent calculations or
operations, so that the original value is used in subsequent calculations or assignments,
not the updated value.
77
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
78
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Initial value of x
Expression
Final value of y
Final value of x
y = ++x
y = x++
y = --x
y = x--
Notes:
79
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class UnaryOperators
UnaryOperators {{
public
public static
static void
void main(String
main(String args[
args[ ])
]) {{
int
int y;
y;
int
x
int x == 5;
5;
yy == ++x;
++x;
System.out.println("x
System.out.println("x == "" ++ xx ++ "\ty
"\ty == "" ++ y);
y);
xx == 5;
5;
yy == x++;
x++;
System.out.println("x
System.out.println("x == "" ++ xx ++ "\ty
"\ty == "" ++ y);
y);
}}
}}
Notes:
80
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Operator precedence
Rules of precedence:
1. Operators within a pair of parentheses
2. Increment and decrement operators
3. Multiplication and division operators, evaluated from left to
right
4. Addition and subtraction operators, evaluated from left to
right
Example of need for rules of precedence (is the answer 34 or
9?):
c = 25 - 5 * 4 / 2 - 10 + 4;
Notes:
To make mathematical operations consistent, the Java programming language follows the
standard mathematical rules for operator precedence. Operators are processed in the
following order:
1.
2.
3.
4.
81
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Operator precedence
Notes:
82
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using Parentheses
Examples:
c
c
c
c
c
c
=
=
=
=
=
=
(((25 - 5) * 4) / (2 - 10)) + 4;
((20 * 4) / (2 - 10)) + 4;
(80 / (2 - 10)) + 4;
(80 / -8) + 4;
-10 + 4;
-6;
Notes:
83
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The Java language permits conversions between integer values and floating-point values.
In addition, because every character corresponds to a number in the Unicode encoding,
values of the char type may be converted to and from the integer and floating-point types.
The boolean type is the only primitive type that cannot be converted to or from another
primitive type in Java.
There are two types of conversions: widening and narrowing conversions. Widening
conversions occur when a value of one type is converted to a type that is represented with
more bits, therefore having a larger range. Widening conversions are performed by Java
automatically when you assign an int literal value to a double variable or a char literal to an
int variable.
Narrowing conversions occur when a value is converted to a type that is represented with
fewer bits. Narrowing conversions are more risky; since you are converting from a type of a
wider range to a smaller range, you risk losing data. For example, you may convert an int
literal value of 21 to a byte, but you could not properly convert an int literal value of 1099 to
a byte, since the byte type has a possible range of values from -128 to 127.
However, if you must do a narrowing conversion, you may use a cast to do so by putting
the name of the desired type (the result type) in parentheses before the value to be
converted. These examples cast an int literal value to a byte:
int i = 25;
byte b = (byte) i;
84
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
85
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
In some circumstances, the compiler changes the type of a variable to a type that supports
a larger size value. This action is referred to a promotion. Some promotions occur
automatically by the compiler if data would not be lost by doing so. These promotions
include:
If you assign a smaller type (on the right of the =) to a larger type (on the left of the
=)
If you assign an integral type to a floating point type (because there are no decimal
places to lose)
The following example contains a literal (an int) that will automatically be promoted to
another type (a long) to before the value (6) is assigned to the variable (big of type long).
The following examples show what will be automatically promoted by the compiler and
what will not be.
long big = 6;
Because 6 is an int type, promotion works because the int value is converted to a long
value.
Type casting lowers the range of a value, quite literally chopping it down to a smaller size,
by changing the type of the value. For example, by converting a long value to an int value.
You do this so that you can use methods that accept only certain types as arguments, so
that you can assign values to a variable of a smaller data type, or to save memory.
86
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Put the target_type (the type the value is being type cast to) in parentheses in front of the
item that you are type casting. The syntax for type casting a value is:
identifier = (target_type) value
where:
87
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples
byte b = 3;
int x = b;
byte a;
int b = 3;
a = (byte)b;
int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (num1 + num2); // causes compiler error
Notes:
Assigning a variable or an expression to another variable can lead to a mismatch between
the data types of the calculation and the storage location you are using to save the result.
Specifically, the compiler will either recognize that precision will be lost and not allow you to
compile the program, or the result will be incorrect. To fix this problem, variable types have
to either be promoted to a larger size type or type cast to a smaller size type.
For example, consider the following assignment:
int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (num1 + num2); // causes compiler error
This code should work, because a byte, while smaller than an int, is large enough to store
a value of 100. However, the compiler will not make this assignment and, instead, issues a
possible loss of precision error because a byte value is smaller than an int value. To fix
this problem, you can either type cast the right side data type down to match the left side
data type, or declare the variable on the left side (num3) to be a larger data type, such as
an int. This problem is fixed by changing num3 to a int:
int num1 = 53;
int num2 = 47;
int num3;
num3 = (num1 + num2);
88
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples
Notes:
89
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples
short s = 259;
byte b = s; // Compiler error
System.out.println(s = + s + , b = + b);
short s = 259;
byte b = (byte)s; // Explicit cast
System.out.println(s = + s + , b = + b);
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1
b = (byte)s
0 0 0 0 0 0 1 1
Notes:
Casting means explicitally telling Java to make a conversion. A casting operation may
widen or narrow its argument. To cast, just precede a value with the paranthesized name
of desired type.
90
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples
public
public class
class ExplicitCasting
ExplicitCasting {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
byte
byte b;
b;
int
int ii == 266;
266; //0000000100001010
//0000000100001010
bb == (byte)i;
//
00001010
(byte)i; //
00001010
System.out.println("byte
System.out.println("byte to
to int
int is
is "" ++ bb );
);
}}
}}
Notes:
When this code is executed, the number 266 (binary 100001010) must be squeezed into a
single byte. This is accomplished by preserving the low-order byte of the value and
discarding the rest.
91
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
92
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 05
Using Primitive Types, Operators and Type Casting, in a
Program Lab
Objectives
Lab Exercises
Objectives
Upon completion of this module, you should be able to:
Write the code to declare, assign values to, and use variables in a program
Practice using operators and type-casting
93
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
94
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 06
Creating and Using Objects
Objectives
o Declaring Object References, Instantiating Objects, and Initializing Object
References
o Declaring Object Reference Variables
o Instantiating an Object
o Initializing Object Reference Variables
o Using an Object Reference Variable to Manipulate Data
o Storing Object Reference Variables in Memory
o Assigning a Reference From One Variable to Another
Using the String Class
o Creating a String Object With the new Keyword
o Creating a String Object Without the new Keyword
o Storing String Objects in Memory
o Using Reference Variables for String Objects
Objectives
Upon completion of this module, you should be able to:
Declare, instantiate, and initialize object reference variables
Compare how object reference variables are stored in relation to primitive variables
Use a class (the String class) included in the Java SDK
95
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
96
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
97
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Class
Object (Instance)
Notes:
98
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Object reference variables are variables containing an address to an object in memory. A
letter is like a reference variable because it has an address pointing to a particular building
object. The illustration demonstrates addresses pointing to different houses.
99
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class ShirtTest
ShirtTest {{
public
static
public static void
void main
main (String
(String args[])
args[]) {{
Shirt
myShirt
=
new
Shirt();
Shirt myShirt = new Shirt();
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
}}
}}
public
public class
class Shirt
Shirt {{
public
public int
int shirtID
shirtID == 0;
0;
public
public String
String description
description == "-description
"-description required-";
required-";
public
char
colorCode
public char colorCode == U;
U;
public
double
price
=
0.0;
public double price = 0.0;
public
public int
int quantityInStock
quantityInStock == 0;
0;
public
public void
void displayShirtInformation()
displayShirtInformation() {{
System.out.println("Shirt
System.out.println("Shirt ID:
ID: " " ++ shirtID);
shirtID);
System.out.println("Shirt
System.out.println("Shirt description:"
description:" ++ description);
description);
System.out.println("Color
Code:
"
+
System.out.println("Color Code: " + colorCode);
colorCode);
System.out.println("Shirt
price:
"
+
price);
System.out.println("Shirt price: " + price);
System.out.println("Quantity
System.out.println("Quantity in
in stock:
stock: " " ++ quantityInStock);
quantityInStock);
}}
}}
Notes:
The example shows a ShirtTest class that creates one variable, an object reference
variable (myShirt), and initializes the variable to point to an instance of the Shirt class.
When the reference variable has been created and initialized, it can be used to invoke the
displayShirtInformation method of the Shirt object.
Declaring and initializing a reference variable is very similar to declaring and initializing a
primitive type variable. The only difference is that you must create an object instance (from
a class) for the reference variable to point to before you can initialize the object instance.
To declare, instantiate, and initialize an object reference variable:
1. Declare a reference to the object by specifying its identifier and the type of object
that the reference points to (the class of the object).
2. Create the object instance using the new keyword.
3. Initialize the object reference variable by assigning the object to the object reference
variable.
100
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
Classname identifier;
Example:
Shirt myShirt;
Circle x;
Cat gardfiel;
Notes:
To declare an object reference variable, state the class that you want to create an object
from, then select the name you want to use to refer to the object. The syntax for declaring
object reference variables is:
Classname identifier;
where:
The Classname is the class or type of object referred to with the object reference.
The identifier is the name you assigned to the variable of type Classname.
101
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Instantiating an Object
Syntax:
new Classname();
Notes:
After you declare the object reference, you can create the object that you refer to. The
syntax for instantiating an object is:
new Classname();
where:
The new keyword creates an object instance from a class.
The Classname is the class or type of object being created.
102
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The final step in creating an object reference variable is to initialize the object reference
variable by assigning the newly created object to the object reference variable. Just as with
variable assignment or initialization, you do this with the equal sign (=). The syntax for
initializing an object to an object reference variable is:
identifier = new Classname();
For example, the ShirtTest class assigns the newly created Shirt object to the myShirt
object reference variable. You can say The myShirt object reference points to a Shirt
object.
myShirt = new Shirt();
When you have created a valid object instance, you can use it to manipulate an objects
data or call an objects methods.
103
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
1. Declare a reference.
2. Create the object.
3. Assign values.
public
public class
class ShirtTest2
ShirtTest2 {{
public
public static
static void
void main
main (String
(String args[])
args[]) {{
Shirt
Shirt myShirt;
myShirt;
myShirt
myShirt == new
new Shirt();
Shirt();
myShirt.size
myShirt.size == L;
L;
myShirt.price
myShirt.price == 29.99F;
29.99F;
myShirt.longSleeved
myShirt.longSleeved == true;
true;
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
}}
}}
Notes:
You use the dot (.) operator with an object reference to manipulate the values or to invoke
the methods of a specific object.
104
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class ShirtTestTwo
ShirtTestTwo {{
public
static
public static void
void main
main (String
(String args[])
args[]) {{
Shirt
myShirt
=
new
Shirt();
Shirt myShirt = new Shirt();
Shirt
Shirt yourShirt
yourShirt == new
new Shirt();
Shirt();
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
yourShirt.displayShirtInformation();
yourShirt.displayShirtInformation();
myShirt.colorCode=R;
myShirt.colorCode=R;
yourShirt.colorCode=G;
yourShirt.colorCode=G;
}}
}}
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
yourShirt.displayShirtInformation();
yourShirt.displayShirtInformation();
Notes:
In this example, the declaration, instantiation, and initialization for each reference is
performed on a single line of code. The declaration is on the left side of the equal sign
while the instantiation of the object is on the right side of the equal sign. The equal sign
assigns the newly instantiated object to the newly declared object reference.
After the object references are created, each object is manipulated independently.
Specifically, the object that the myShirt reference points to is given a colorCode value of
R for red while the object that the yourShirt reference points to is given a colorCode value
of G for green.
105
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class AlarmClock
AlarmClock {{
public
void
public void snooze()
snooze() {{
System.out.println("ZZZZZ");
System.out.println("ZZZZZ");
}}
}}
public
public class
class AlarmClockTest
AlarmClockTest {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
AlarmClock
aClock
=
new
AlarmClock();
AlarmClock aClock = new AlarmClock();
aClock.snooze();
aClock.snooze();
}}
}}
Notes:
106
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class AlarmClock
AlarmClock {{
public
void
public void snooze(long
snooze(long snoozeInterval)
snoozeInterval) {{
System.out.println("ZZZZZ
System.out.println("ZZZZZ for:
for: "" ++ snoozeInterval);
snoozeInterval);
}}
}}
public
public class
class AlarmClockTest
AlarmClockTest {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
AlarmClock
aClock
=
new
AlarmClock();
AlarmClock aClock = new AlarmClock();
//Pass
//Pass in
in the
the snooze
snooze interval
interval when
when you
you call
call the
the method
method
}}
}}
aClock.snooze(10000);
aClock.snooze(10000); //Snooze
//Snooze for
for 10000
10000 msecs
msecs
Notes:
107
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class Circle
Circle {{
private
private int
int radius;
radius;
}}
public
public class
class ShapeTester
ShapeTester {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
Circle
Circle x;
x;
xx == new
new Circle();
Circle();
System.out.println(x);
System.out.println(x);
}}
}}
Notes:
108
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class Circle
Circle {{
private
int
private int radius;
radius;
}}
public
public class
class Rectangle
Rectangle {{
public
public double
double width
width == 10.128;
10.128;
public
double
height
public double height == 5.734;
5.734;
}}
public
public class
class ShapeTester
ShapeTester {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
Circle
Circle x;
x;
Rectangle
Rectangle y;
y;
xx == new
new Circle();
Circle();
yy == new
new Rectangle();
Rectangle();
System.out.println(x
System.out.println(x ++ "" "" ++ y);
y);
}}
}}
Notes:
109
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public static
static void
void main
main (String
(String args[])
args[]) {{
int
counter;
int counter;
counter
counter == 10;
10;
Shirt
Shirt myShirt
myShirt == new
new Shirt
Shirt (( );
);
}}
Notes:
While primitive variables hold values, object reference variables hold the location (memory
address) of objects in memory.
Memory addresses are usually written in hexadecimal notation, beginning with a 0x (for
example, 0x334009). These addresses are unique for each object and are assigned while
a program runs.
The figure shows how the primitive variable and object reference variables are stored
differently.
Local object reference variables and their values are stored in stack memory while the
objects that they point to are stored in heap memory. The myShirt and yourShirt object
reference variables contain addresses referring to different Shirt objects.
110
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
111
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Cat B = A;
Notes:
112
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
113
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The String class is one of the many classes included in the Java class libraries. The String
class provides you with the ability to store a sequence of characters. You will use the String
class frequently throughout your programs. Therefore, it is important to understand some of
the special characteristics of strings in the Java programming language.
There are a number of ways to create and initialize a String object. One way is to use the
new keyword to create a String object and, at the same time, define the string with which to
initialize that object:
String myName = new String(Fred Smith);
114
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The String class is immutable, which means that its value cannot
be changed one an object of String type is created.
We can use the varius characters in the String class to do the
following:
Examine the varius characters that make up a string
Search for a given sub-string within another string
Compare two strings
Create another string that has all the characters of the given
string in upper or lower case
All string values referred by String objects are stored in the
string pool. When we create two String objects and assign to
them a value, for example hello, there is only one string with
the value hello create in the string pool. Both the String
objects refer to the same value hello in the string pool.
Notes:
115
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
116
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
117
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
}}
Notes:
118
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
119
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
//
// Convert
Convert an
an integer
integer to
to String
String and
and join
join with
with two
two other
other strings
strings
}}
}}
int
int numHands
numHands == 99;
99;
myString
myString == numHands
numHands ++ ++ secondString
secondString ++ thirdString;
thirdString;
System.out.println(myString);
System.out.println(myString);
//
// Combining
Combining aa string
string and
and integers
integers
myString
=
fifty
five
myString = fifty five is
is ++ 55 ++ 5;
5;
System.out.println(myString);
System.out.println(myString);
//
// Combining
Combining integers
integers and
and aa string
string
myString
=
5
+
5
+
is
myString = 5 + 5 + is ten;
ten;
System.out.println(myString);
System.out.println(myString);
Notes:
120
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
121
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The essential difference between the two is that the first statement always has at least one
operand of type String, so the operation is one of string concatenation, whereas in the
second statement the first operation is an arithmetic addition because both operands are
integers. In the first statement, each of the integers is converted to type String individually.
In the second, the numerical values are added, and the result, 10, is converted to a string
representation to allow the literal is ten to be concatenated.
122
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The String object itself is distinct from the variable you use to refer to it. In the same way as
you saw with array objects, the variable myString stores a reference to a String object, not
the object itself, so in other words, a String variable records where the String object is in
memory. When you declare and initialize myString, it references the object corresponding
to the initializing string literal. When you execute the assignment statement, the original
reference is overwritten by the reference to the new string and the old string is discarded.
The variable myString then contains a reference to the new string.
String objects are said to be immutablewhich just means that they cannot be changed.
This means that you cannot extend or otherwise modify the string that an object of type
String represents. When you execute a statement that combines existing String objects,
you are always creating a new String object as a result. When you change the string
referenced by a String variable, you throw away the reference to the old string and replace
it with a reference to a new one. The distinction between a String variable and the string it
references is not apparent most of the time.
123
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 07
Objects and Strings Lab
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Create instances of a class and manipulate these instances in several ways.
Make use of the String class and its methods
124
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
125
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
// the
public
public
public
public
return
}
}
126
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
127
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
5. Call methods of the objects and see what effect they have.
savings.credit(1000);
System.out.println(savings);
cheque.credit(500);
System.out.println(cheque);
cheque.credit(1500);
System.out.println(cheque);
cheque.debit(200);
System.out.println(cheque);
128
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
129
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 08
Using Operators and Decision Constructors
Objectives
Using Relational and Conditional Operators
o Elevator Example
o Relational Operators
o Testing Equality Between Strings
o Conditional Operators
Creating if and if/else Constructs
o The if Construct
o Nested if Statements
o The if/else Construct
o Chaining if/else Constructs
Using the switch Construct
o When to Use switch Constructs
Objectives
Upon completion of this module, you should be able to:
Identify relational and conditional operators
Create if and if/else constructs
Use the switch construct
130
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
In addition to arithmetic operators, such as plus (+) and increment (++), the Java
programming language provides several relational operators including < and > for less than
and greater than and && for AND. These operators are used when you want your program
to execute different blocks or branches of code depending on different conditions, such as
checking if the value of two variables is the same.
131
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Elevator Example
public
public class
class Elevator
Elevator {{
public
boolean
public boolean doorOpen=false;
doorOpen=false; //
// Doors
Doors are
are closed
closed by
by default
default
public
int
currentFloor
=
1;
//
All
elevators
start
on
first
public int currentFloor = 1; // All elevators start on first floor
floor
public
public final
final int
int MAX_FLOORS
MAX_FLOORS == 10;
10;
public
final
int
MIN_FLOORS
public final int MIN_FLOORS == 1;
1;
public
public void
void openDoor()
openDoor() {{
System.out.println(Opening
System.out.println(Opening door.);
door.);
doorOpen
doorOpen == true;
true;
System.out.println(Door
System.out.println(Door is
is open.);
open.);
}}
public
public void
void closeDoor()
closeDoor() {{
System.out.println(Closing
System.out.println(Closing door.);
door.);
doorOpen
doorOpen == false;
false;
System.out.println(Door
System.out.println(Door is
is closed.);
closed.);
}}
Notes:
An elevator has many functions. The functions of the elevator are:
132
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Elevator Example
public
public void
void goUp()
goUp() {{
System.out.println(Going
System.out.println(Going up
up one
one floor.);
floor.);
currentFloor++;
currentFloor++;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
public
public void
void goDown()
goDown() {{
System.out.println(Going
System.out.println(Going down
down one
one floor.);
floor.);
currentFloor--;
currentFloor--;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
public
public int
int getFloor()
getFloor() {{
return
currentFloor;
return currentFloor;
}}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {{
return
return doorOpen;
doorOpen;
}}
}}
Notes:
133
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class ElevatorTest
ElevatorTest {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
Elevator
Elevator myElevator
myElevator == new
new Elevator();
Elevator();
myElevator.openDoor();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goDown();
myElevator.openDoor();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goDown();
myElevator.openDoor();
myElevator.openDoor();
}}
}}
Notes:
134
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Relational Operators
Notes:
Relational operators compare two values to determine their relationship. The result of all
relational operators is a boolean value. Boolean values can be either true or false. For
example, all of the examples in the previous table yield a boolean result of true.
135
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Conditional Operators
Notes:
For AND operations, true AND true produces true. Any other combination produces false.
For OR operations false OR false produces false. Any other combination produces true.
As with all operations, the two operands must be of compatible types. So, if either operand
is of boolean type, both must be. Java does not permit you to cast any type to Boolean;
instead you must use comparisons or methods that return boolean values.
136
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
Notes:
An if statement, or an if construct, executes a block of code if an expression is true.
There are a few variations on the basic if construct. However, the simplest and most
common is:
if (boolean_expression) {
code_block;
} // end of if construct
// program continues here
where:
The boolean_expression is a combination of relational operators, conditional
operators, and values resulting in a value of true or false.
The code_block represents the lines of code that are executed if expression is true.
First, the boolean_expression is tested. If the expression is true, then the code_block is
executed. If boolean_expression is not true, the program skips to the brace marking the
end of the if construct code block.
137
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
public
public class
class Coffee
Coffee {{
private
static
private static int
int hour=9;
hour=9;
public
public static
static void
void main(String
main(String args[])
args[]) {{
}}
if(hour>=8
if(hour>=8 &&
&& hour<12)
hour<12) {{
System.out.println(Drink
System.out.println(Drink coffee);
coffee);
}}
}}
Notes:
The example shows the code for deciding whether to drink coffee, bases on wheter it is
morning (between 8:00 AM and 12:00 PM, on a military time system).
138
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
public
public class
class IfElevator
IfElevator {{
public
public boolean
boolean doorOpen=false;
doorOpen=false; //
// Doors
Doors are
are closed
closed by
by default
default
public
int
currentFloor
=
1;
//
All
elevators
start
on
first
public int currentFloor = 1; // All elevators start on first floor
floor
public
public final
final int
int MAX_FLOORS
MAX_FLOORS == 10;
10;
public
final
int
MIN_FLOORS
public final int MIN_FLOORS == 1;
1;
public
public void
void openDoor()
openDoor() {{
System.out.println(Opening
System.out.println(Opening door.);
door.);
doorOpen
doorOpen == true;
true;
System.out.println(Door
System.out.println(Door is
is open.);
open.);
}}
public
public void
void closeDoor()
closeDoor() {{
System.out.println(Closing
System.out.println(Closing door.);
door.);
doorOpen
doorOpen == false;
false;
System.out.println(Door
System.out.println(Door is
is closed.);
closed.);
}}
Notes:
139
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
public
public void
void goUp()
goUp() {{
System.out.println(Going
System.out.println(Going up
up one
one floor.);
floor.);
currentFloor++;
currentFloor++;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
public
public void
void goDown()
goDown() {{
if(currentFloor
if(currentFloor ==
== MIN_FLOORS)
MIN_FLOORS) {{
System.out.println(Cannot
System.out.println(Cannot Go
Go down);
down);
}}
if(currentFloor
if(currentFloor >> MIN_FLOORS)
MIN_FLOORS) {{
System.out.println(Going
System.out.println(Going down
down one
one floor.);
floor.);
currentFloor--;
currentFloor--;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
}}
Notes:
140
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
public
public int
int getFloor()
getFloor() {{
return
currentFloor;
return currentFloor;
}}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {{
return
doorOpen;
return doorOpen;
}}
}}
Notes:
141
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Nested if Statements
public
public class
class NestedIfElevator
NestedIfElevator {{
public
public boolean
boolean doorOpen=false;
doorOpen=false; //
// Doors
Doors are
are closed
closed by
by default
default
public
int
currentFloor
=
1;
//
All
elevators
start
on
first
public int currentFloor = 1; // All elevators start on first floor
floor
public
public final
final int
int MAX_FLOORS
MAX_FLOORS == 10;
10;
public
public final
final int
int MIN_FLOORS
MIN_FLOORS == 1;
1;
public
public void
void openDoor()
openDoor() {{
System.out.println(Opening
System.out.println(Opening door.);
door.);
doorOpen
doorOpen == true;
true;
System.out.println(Door
System.out.println(Door is
is open.);
open.);
}}
public
public void
void closeDoor()
closeDoor() {{
System.out.println(Closing
System.out.println(Closing door.);
door.);
doorOpen
doorOpen == false;
false;
System.out.println(Door
System.out.println(Door is
is closed.);
closed.);
}}
Notes:
142
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Nested if Statements
public
public void
void goUp()
goUp() {{
System.out.println(Going
System.out.println(Going up
up one
one floor.);
floor.);
currentFloor++;
currentFloor++;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
public
public void
void goDown()
goDown() {{
if
if (currentFloor
(currentFloor ==
== MIN_FLOORS)
MIN_FLOORS) {{
System.out.println(Cannot
System.out.println(Cannot Go
Go down);
down);
}}
if
if (currentFloor
(currentFloor >> MIN_FLOORS)
MIN_FLOORS) {{
if
(!doorOpen)
{
if (!doorOpen) {
System.out.println(Going
System.out.println(Going down
down one
one floor.);
floor.);
currentFloor--;
currentFloor--;
System.out.println(Floor:
System.out.println(Floor: ++ currentFloor);
currentFloor);
}}
}}
}}
Notes:
143
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Nested if Statements
public
public int
int getFloor()
getFloor() {{
return
currentFloor;
return currentFloor;
}}
}}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {{
return
doorOpen;
return doorOpen;
}}
Notes:
144
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
else {
code_block;
} // end of else construct
// program continues here
Notes:
Often, you want one block of code to be executed if the expression is true and another
block of code to be executed if the expression is false. You can use an if construct to
execute a code block if the expression is true with an else construct that only executes if
the expression is false. The syntax for an if/else construct is:
if (boolean_expression) {
code_block;
} // end of if construct
else {
code_block;
} // end of else construct
// program continues here
where:
The boolean_expression is a combination of relational operators, conditional
operators, and values resulting in a value of true or false.
The code_block represents the lines of code that are executed if expression is true.
145
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The if Construct
public
public class
class CoffeeIfElse
CoffeeIfElse {{
private
static
private static int
int hour=9;
hour=9;
public
public static
static void
void main(String
main(String args[])
args[]) {{
if(hour>=8
if(hour>=8 &&
&& hour<12)
hour<12) {{
System.out.println(Drink
System.out.println(Drink coffee);
coffee);
}}
}}
else
else {{
System.out.println(Drink
System.out.println(Drink tea);
tea);
}}
//continue
//continue here
here
}}
Notes:
146
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
147
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
148
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {{
return
return doorOpen;
doorOpen;
}}
Notes:
149
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
else if (boolean_expression){
code_block;
} // end of else if construct
else {
code_block;
}
// program continues here
Notes:
You can chain if and else constructs together to state multiple outcomes for several
different expressions. The syntax for a chained if/else construct is:
if (boolean_expression) {
code_block;
} // end of if construct
else if (boolean_expression){
code_block;
} // end of else if construct
else {
code_block;
}
// program continues here
where:
The boolean_expression is a combination of relational operators, conditional
operators, and values resulting in a value of true or false.
The code_block represents the lines of code that are executed if expression is true.
150
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
}}
if
if (testscore
(testscore >=
>= 90)
90) {{
grade
grade == 'A';
'A';
}} else
else if
if (testscore
(testscore >=
>= 80)
80) {{
grade
=
'B';
grade = 'B';
}} else
else if
if (testscore
(testscore >=
>= 70)
70) {{
grade
=
'C';
grade = 'C';
}} else
else if
if (testscore
(testscore >=
>= 60)
60) {{
grade
grade == 'D';
'D';
}} else
else {{
grade
grade == 'F';
'F';
}}
System.out.println("Grade
System.out.println("Grade == "" ++ grade);
grade);
Notes:
The following program, IfElseDemo, assigns a grade based on the value of a test score: an
A for a score of 90% or above, a B for a score of 80% or above, and so on.
151
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
public
public void
void calculateNumDays()
calculateNumDays() {{
if
if (month
(month ==
== 11 ||
|| month
month ==
== 33 ||
|| month
month ==
== 55 ||
|| month
month ==
== 77 ||
||
month
month ==
== 88 ||
|| month
month ==
== 10
10 ||
|| month
month ==
== 12)
12) {{
System.out.println(There
System.out.println(There are
are 31
31 days
days in
in that
that month.);
month.);
}}
else
else if
if (month
(month ==
== 2)
2) {{
System.out.println(There
System.out.println(There are
are 28
28 days
days in
in that
that month.);
month.);
}}
else
else if
if (month
(month ==
== 44 ||
|| month
month ==
== 66 ||
|| month
month ==
== 99 ||
|| month
month ==
== 11)
11) {{
System.out.println(There
System.out.println(There are
are 30
30 days
days in
in that
that month.);
month.);
}}
else
else {{
System.out.println(Invalid
System.out.println(Invalid month.);
month.);
}}
}}
Notes:
152
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Another keyword used in decision-making is the switch keyword. The switch construct
helps you avoid confusing code because it simplifies the organization of the various
branches of code that can be executed.
153
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
A switch works with the byte, short, char, and int primitive data
types.
Syntax:
switch (variable) {
case literal_value:
code_block;
[break;]
case another_literal_value:
code_block;
[break;]
[default:]
code_block;
}
Notes:
The syntax for the switch construct is:
switch (variable) {
case literal_value:
code_block;
[break;]
case another_literal_value:
code_block;
[break;]
[default:]
code_block;
}
where:
155
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
156
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
}}
}}
System.out.println(There
System.out.println(There are
are 28
28 days
days in
in that
that month.);
month.);
break;
break;
case
case 4:
4:
case
case 6:
6:
case
case 9:
9:
case
case 11:
11:
System.out.println(There
System.out.println(There are
are 30
30 days
days in
in that
that month.);
month.);
break;
break;
default:
default:
System.out.println(Invalid
System.out.println(Invalid month.);
month.);
break;
break;
Notes:
157
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
}}
default:
default: System.out.println("Invalid
System.out.println("Invalid month.");
month."); break;
break;
}}
System.out.println("Number
System.out.println("Number of
of Days
Days == "" ++ numDays);
numDays);
}}
Notes:
158
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Equality tests
Tests against a single variable, such as customerStatus
Tests against the value of an int, short, byte, or char
type
Notes:
The switch construct is only for testing equality, not for testing whether values are greater
or less than a single value. You cannot use the switch construct to test against more than
one value, and you can only use it with integral data types.
The switch construct can be considered for:
Equality tests
Tests against a single variable, such as customerStatus
Tests against the value of an int, short, byte, or char type
159
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 09
Control Structures
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Create classes that use if and if/else constructs.
Using the switch construct in decision-making programs
160
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
161
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises
162
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
163
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
164
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 10
Using loop constructs
Objectives
Creating while loops
o Nested while loops
Developing a for loop
o Nested for Loops
Coding a do/while Loop
o Nested do/while Loops
o Comparing Loop Constructs
Objectives
Upon completion of this module, you should be able to:
Create while loops
Develop for loops
Create do/while loops
165
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
A while loop iterates through a code block while an expression yields a value of true. The
syntax for a while loop is:
while (boolean_expression) {
code_block;
} // end of while construct
// program continues here
All loops have the following components:
The while loop is a zero-to-many iterative loop, the boolean_expression part of the loop is
processed before the body of the loop, and, if it is immediately false, then the body will not
be processed at all.
166
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class WhileCountDown
WhileCountDown {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
int
int count
count == 10;
10;
while(count>=0)
while(count>=0) {{
System.out.println(count);
System.out.println(count);
count--;
count--;
}}
System.out.println(Blast
System.out.println(Blast Off.);
Off.);
}}
}}
Notes:
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression evaluates to false.
167
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
while
(currentFloor
!=
desiredFloor)
while (currentFloor != desiredFloor)
if
if (currentFloor
(currentFloor << desiredFloor)
desiredFloor) {{
goUp();
goUp();
}} else
else {{
goDown();
goDown();
}}
}}
public
public int
int getFloor()
getFloor() {}
{}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {}
{}
}}
Notes:
The following code example shows a setFloor method that contains a while loop that helps
to move an elevator up or down.
168
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The code prints a rectangle of @ symbols, ten columns wide by three row long (three rows
composed of 10 @ symbols each). Printing each row is done by the inner loop; the outer
loop prints that code three times.
169
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The for loop allows your program to loop through a sequence of statements for a
predetermined number of times. The for loop operates in exactly the same way as the
while loop, including the fact that it is a zero-to-many loop, but it has a more centralized
structure for counting through a range of values. The syntax for the for loop is:
for (initialize[,initialize]; boolean_expression; update[,update]) {
code_block;
}
where:
The initialize[,initialize] portion of the for construct contains statements that initialize
variables (such as loop counters) used throughout the loop. This section of code is
processed once, before any other part of the loop. Separate multiple variables with
commas.
The boolean_expression is an expression that evaluates to true or false. This
expression is processed before each iteration of the loop.
The update[,update] section is where variables (loop counters) are updated
(incremented or decremented). This section is processed after the body but before
each subsequent re-test of the boolean_expression. Separate multiple variables
with commas.
The code_block represents lines of code that are executed if the
boolean_expression is true.
170
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class ForLoop
ForLoop {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
int
int limit
limit == 20;
20; //
// Sum
Sum from
from 11 to
to this
this value
value
int
int sum
sum == 0;
0; //
// Accumulate
Accumulate sum
sum in
in this
this variable
variable
//
// Loop
Loop from
from 11 to
to the
the value
value of
of limit,
limit, adding
adding 11 each
each cycle
cycle
for(int
for(int ii == 1;
1; ii <=
<= limit;
limit; i++)
i++) {{
sum
sum +=
+= i;
i; //
// Add
Add the
the current
current value
value of
of ii to
to sum
sum
}}
System.out.println(sum
System.out.println(sum == ++ sum);
sum);
}}
}}
Notes:
171
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
Notes:
172
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
if
(currentFloor
>
desiredFloor)
if (currentFloor > desiredFloor) {{
for
for (int
(int down
down == currentFloor;
currentFloor; down
down !=
!= desiredFloor;
desiredFloor; --down)
--down) {{
goDown();
goDown();
}}
}} else
else {{
for
for (int
(int up
up == currentFloor;
currentFloor; up
up !=
!= desiredFloor;
desiredFloor; ++up)
++up) {{
goUp();
goUp();
}}
}}
}}
public int getFloor() {}
public int getFloor() {}
public boolean checkDoorStatus() {}
public boolean checkDoorStatus() {}
}}
Notes:
The following code example shows a setFloor method that contains a for loop.
173
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
174
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
do {
code_block;
}
while(boolean_expression);// Semicolon is
// mandatory.
Notes:
The do/while loop is a one-to-many iterative loop: The condition is at the bottom of the loop
and is processed after the body. The body of the loop is therefore processed at least once.
If you want the statement or statements in the body to be processed at least once, use a
do/while loop instead of a while or for loop. The syntax for the do/while loop is as follows:
do {
code_block;
}
while (boolean_expression);// Semicolon is mandatory.
where:
The code_block represents lines of code that are executed more than once if the
boolean_expression is true.
The boolean_expression is an expression that evaluates to true or false. The
boolean_expression is processed after each iteration of the loop.
175
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
do
{
do {
if
if (currentFloor
(currentFloor << desiredFloor)
desiredFloor) {{
goUp();
goUp();
}}
if
if (currentFloor
(currentFloor >> desiredFloor)
desiredFloor) {{
goDown();
goDown();
}}
}}
while
while (currentFloor
(currentFloor !=
!= desiredFloor);
desiredFloor);
}}
}}
Notes:
The code example shows a setFloor method that contains a while loop that helps to move
an elevator up or down.
176
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
177
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
178
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
179
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
180
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 11
Loop Constructs
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Write classes that use while loops.
Write classes that use for loops.
Write classes that use do/while loops.
181
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Lab Exercises 1
182
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
183
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
184
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 12
Developing and Using Methods
Objectives
Creating and Invoking Methods
o Basic Form of a Method
o Invoking a Method from Different Class
o Invoking a Method in the Same Class
o Guidelines for Invoking Methods
Passing Arguments and Returning Values
o Declaring Methods With Arguments
o Invoking Methods With Return Values
o Returning a Value
o Advantages of Method Use
Creating static Methods and Variables
o Static Methods and Variables in the Java API
o When to Declare a static Method or Variable
Using Method Overloading
o Method Overloading and the Java API
o Uses for Method Overloading
Objectives
Upon completion of this module, you should be able to:
Describe the advantages of methods and define worker and calling methods
Declare and invoke a method
Compare object and static methods
Use overloaded methods
185
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
186
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
187
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
188
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
colour = anUmbrella.getColour();
anUmbrella.setColour("blue");
homer.eat(donuts);
Notes:
189
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
190
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Message
A message is a request for a service.
Method
A method is the implementation of the service requested by
the message
In procedural languages, these are known as procedures or
functions
A message is typically sent from one object to another; it does
not imply what actual code will be executed
A method is the code that will be executed in response to a
message that is sent to an object
Notes:
191
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Introduction
Notes:
192
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Most of the code you write for a class is contained within one or more methods. Methods
let you divide the work that your program does into separate logical tasks or behaviors.
The syntax of all method declarations is as follows:
[modifiers] return_type method_identifier ([arguments]) {
method_code_block
}
where:
The [modifiers] represent several Java keywords that modify the way methods are
used. Modifiers are optional (as indicated by the square brackets).
The return_type is the type of value returned from a method that can be used
elsewhere in the program. Methods can return only one item (literal value, variable,
object reference, and so on). If nothing is to be returned, the keyword void must be
specified as the return type.
The method_identifier is the name of the method.
The ([arguments]) represent a list of variables whose values are passed to the
method for use by the method. Arguments are optional (indicated by the square
brackets); many methods do not accept arguments.
The method_code_block is a sequence of statements that the method performs. A
wide variety of tasks can take place in the code block or body of a method.
193
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
modifier keyword
public
public void
void displayShirtInformation(
displayShirtInformation( )) {{
System.out.println("Shirt
System.out.println("Shirt ID:
ID: "" ++ shirtID);
shirtID);
System.out.println("Shirt
description:"
System.out.println("Shirt description:" ++ description);
description);
System.out.println("Color
System.out.println("Color Code:
Code: "" ++ colorCode);
colorCode);
System.out.println("Shirt
System.out.println("Shirt price:
price: "" ++ price);
price);
System.out.println("Quantity
System.out.println("Quantity in
in stock:
stock: ""
++ quantityInStock);
quantityInStock);
}} //
end
of
display
method
// end of display method
Notes:
The basic form of a method accepts no arguments and returns nothing.
method from the Shirt class is a basic method.
The display
194
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
To invoke, or execute, a method in a different class, you can use the dot (.) operator with
an object reference variable just as you do to access the public variables of an object.
In this example, an object reference variable called myShirt is declared and initialized to a
Shirt object. The myShirt object reference variable then invokes the display method within
the Shirt object.
195
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
196
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
197
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
A calling method tells an object to do something for you, with one of its methods.
Calling methods often contain normal method processes, in addition to calling the
worker method.
The object contains worker methods to do work for you. Might take input
information, might return one piece of information.
198
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Calling
method
Worker
method
public
public class
class One
One {{
public
public static
static void
void main(String
main(String args[]
args[])) {{
Two
twoRef
=
new
Two();
Two twoRef = new Two();
twoRef.workerMethod();
twoRef.workerMethod();
}}
}}
public
public class
class Two
Two {{
public
void
public void workerMethod()
workerMethod() {{
int
int ii == 42;
42;
int
j
=
24;
int j = 24;
}}
}}
Notes:
You need to write code within a calling method that tells an object to so something for you,
with one of its methods.
You need a class that has some methods that complete tasks you want done. This is the
worker method. This method might or might not require additional information when its run.
It also might return one piece of information to the calling method.
199
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The example shows a very basic program, to highlight the separation of the worker and
calling methods. These calling method just call two methods in WorkerClass; those two
methods print the values of variables set in their methods.
200
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
201
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
202
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
203
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Methods can be invoked by a calling method with a list of arguments (variables or values to
be used by the worker method). Additionally, methods can return a value to the calling
method that can be used in the calling method.
204
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
205
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public void setFloor(int desiredFloor) {
while (currentFloor != desiredFloor) {
if (currentFloor < desiredFloor) {
goUp();
}
else {
goDown();
}
}
}
Example:
public void multiply(int NumberOne, int NumberTwo)
Notes:
To write a method declaration that accepts one or more arguments, list one or more type
and variable pairs within the parentheses of the method declaration.
206
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
207
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
208
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaration:
public int sum(int numberOne, int numberTwo)
Notes:
Most of the method declarations that you have seen do not have a return value (void).
However, many of the methods you will create will have return values and many methods
in the Java class libraries also have return values.
To declare a method that returns a value, place the type of the value you want the method
to return in front of the method identifier.
209
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Returning a Value
Example:
public int sum(int numberOne, int numberTwo) {
int sum = numberOne + numberTwo;
return sum;
}
Example:
public int getFloor() {
return currentFloor;
}
Notes:
210
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
211
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class AddsValues
AddsValues {{
public
int
returnSum()
public int returnSum() {{
int
int xx == 4;
4;
int
int yy == 17;
17;
return(x
return(x ++ y);
y);
}}
}}
Notes:
212
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
213
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Variables having the same value for all instances of a class are
called class variables
Class variables are also sometimes referred to as static variables
public
public class
class Student
Student {{
//class
variables
//class variables
static
static int
int maxIdAssigned;
maxIdAssigned;
//instance
variable
//instance variable
private
private int
int id;
id;
//constructor
//constructor
public
public Student()
Student() {{
this.id
this.id == maxIdAssigned;
maxIdAssigned;
maxIdAssigned++;
maxIdAssigned++;
}}
}}
Notes:
Local variables are declared inside a method and instance variables are declared in a class
but not inside a method.
An instance variable is accessed through a particular instance (an object) of a class.
In general, each object has distinct memory space for each variable so that each object
can have a distinct value for that variable.
A static variable or class variable, is shared among all instances of a class. There is only
one copy of a static variable for all objects of a class. Therefore, changing the value of a
static variable in one object changes it for all of the others.
214
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
215
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
216
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
class
public
Example:
public
class Slogan
Slogan {{
private
private String
String phrase;
phrase;
private
static
int
private static int count
count == 0;
0;
public
public Slogan
Slogan (String
(String str)
str) {{
phrase
phrase == str;
str;
count++;
count++;
}}
public
public String
String toString()
toString() {{
return
return phrase;
phrase;
}}
public
public static
static int
int getCount
getCount ()
() {{
return
return count;
count;
}}
}}
Notes:
217
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Static fields, also called class variablesA given class will have only one copy of each of
its static fields or class variables, and these will be shared between and among all the
objects of the class. Each class variable exists even if no objects of the class have been
created. Class variables belong to the class, and they can be referenced by any object or
class method, not just methods belonging to instances of that class. If the value of a static
field is changed, the new value is available equally in all the objects of the class. This is
quite different from non-static fields, where changing a value for one object does not affect
the values in other objects. A static field must be declared using the keyword static
preceding the type name.
218
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples:
The Math class
The System class
Notes:
Certain Java class libraries, such as the System class, contain only static methods and
variables. The System class contains utility methods for handling operating system-specific
tasks (they do not operate on an object instance). For example, the getProperties method
of the System class gets information about the computer you are using.
There are several classes in the Java API that are utility classes. These classes contain
static methods that are useful for objects of all types. Examples of utility classes and
methods are:
The Math class. This class contains methods and variables for performing basic
numeric operations, such as the elementary exponential, logarithm, square root, and
trigonometric functions.
The System class. This class contains methods and variables for performing
system-level functions, such as retrieving environment variable information from
your operating system.
219
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
class
public
Examples:
public
class Get
Get {{
public
public static
static void
void main
main (String[]
(String[] args)
args) {{
StaticExample ex
ex == new
new StaticExample();
StaticExample();
StaticExample
ex.getNumber();
ex.getNumber();
}}
public
public class
class StaticExample
StaticExample {{
public
void
public void getNumber()
getNumber() {{
System.out.println(A
System.out.println(A random
random number:
number:
++ Math.random());
Math.random());
}}
}}
Notes:
An example of a common static method is Math.random(); most of the Math methods
included with the Java API are static. The example calls Math.random().
220
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
//
// Use
Use the
the quadratic
quadratic formula
formula to
to compute
compute the
the roots.
roots.
//
Assumes
a
positive
discriminant.
// Assumes a positive discriminant.
double
double discriminant
discriminant == Math.pow(b,
Math.pow(b, 2)
2) -- (4
(4 ** aa ** c);
c);
double
root1
=
((-1
*
b)
+
Math.sqrt(discriminant))
double root1 = ((-1 * b) + Math.sqrt(discriminant)) // (2
(2 ** a);
a);
double
root2
=
((-1
*
b)
Math.sqrt(discriminant))
/
(2
double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 ** a);
a);
System.out.println
System.out.println ("Root
("Root #1:
#1: "" ++ root1);
root1);
System.out.println
System.out.println ("Root
("Root #2:
#2: "" ++ root2);
root2);
}}
}}
Notes:
221
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
222
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Java allows us to have two or more methods with the same name inside
the same class
As with constructors, the overloaded methods should also have
different number of parameters, or have different data types for the
parameters
This feature of Java is called method overloading
The compiler will detect errors at the compilation time if two methods
in a class have the same name and have the same number and type of
parameters
Notes:
In the Java programming language, there can be several methods in a class that have the
same name but different arguments (different method signatures). This concept is called
method overloading. Just as you can distinguish between two students in the same class
named Jim by calling them Jim in the green shirt and Jim with the beeper, you can
distinguish between two methods by their name and arguments.
223
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
224
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
225
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
226
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
227
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples:
public int sum(int numberOne, int numberTwo)
public int sum(int numberOne, int numberTwo, int numberThree)
public int sum(int numberOne, int numberTwo,int numberThree, int
numberFour)
Notes:
228
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
229
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
230
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
public
public class
class ShirtTwoTest
ShirtTwoTest {{
public
static
public static void
void main
main (String
(String args[])
args[]) {{
ShirtTwo
shirtOne
=
new
ShirtTwo();
ShirtTwo shirtOne = new ShirtTwo();
ShirtTwo
ShirtTwo shirtTwo
shirtTwo == new
new ShirtTwo();
ShirtTwo();
ShirtTwo
shirtThree
=
ShirtTwo shirtThree = new
new ShirtTwo();
ShirtTwo();
shirtOne.setShirtInfo(100,
shirtOne.setShirtInfo(100, Button
Button Down,
Down, 12.99);
12.99);
shirtTwo.setShirtInfo(101,
shirtTwo.setShirtInfo(101, Long
Long Sleeve
Sleeve Oxford,
Oxford, 27.99,
27.99, G);
G);
shirtThree.setShirtInfo(
102,
Shirt
Sleeve
T-Shirt,
9.99,
shirtThree.setShirtInfo( 102, Shirt Sleeve T-Shirt, 9.99, B,
B, 50
50);
);
shirtOne.display();
shirtOne.display();
shirtTwo.display();
shirtTwo.display();
shirtThree.display();
shirtThree.display();
}}
}}
Notes:
231
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 13
Methods Labs
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Create classes and objects
Invoke methods of a class
Overload methods in a class
232
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
1. Write a Shirt class that has a price, item ID, and type (such
as Oxford or polo). Declare methods that return those three
values. (These are get methods).
2. Write another class that calls and prints those values.
3. You will need to create two files, one called Shirt.java that
declares the shirt variables and methods, and one called
CreateShirt.java that calls the methods and prints the
values.
233
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
234
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
235
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
1. Write a Java program that has the classes Area and User.
Area has overloaded static methods by the name area() that
can be used to calculate the area of a circle, triangle, rectangle
and a cylinder. User uses the methods of Area to calculate the
area of different geometric figures and prints it to the standard
output.
2. Write a class called Area.
3. Write four overloaded methods named area that take different
numbers and type of data types as parameters. These methods
are used to calculate the area of a circle, triangle, rectangle
and cylinder.
236
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Area of
Area of
Area of
Area of
height
237
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 14
Implementing Encapsulation and Constructors
Objectives
Using Encapsulation
o Visibility Modifiers
o The public Modifier
o The private Modifier
o Interface and Implementation
o Get and Set Methods
o Encapsulated Elevator
Describing Variable Scope
o How Instance Variables and Local Variables Appear in Memory
Creating Constructors
o Default Constructor
o Overloading Constructors
Objectives
Upon completion of this module, you should be able to:
Use encapsulation to protect data
Create constructors to initialize objects
238
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using Encapsulation
Hide
implementation
from clients.
Clients depend
on interface
Notes:
Encapsulation separates the external aspects of an object, which are accessible to other
objects, from the internal implementation details of the object, which are hidden from other
objects.
The advantage of encapsulation, which hides implementation detail, is that the class might
change. If the only changes take place in the hidden implementation and if the new
interface is compatible with the original, programs using the changed class are unaffected.
In addition, the implementation can change without affecting the interface.
239
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using Encapsulation
Notes:
In pure OO systems, all attributes are private and can be changed or accessed only
through public operations
Most or all variables should kept private.
Variables are modified by methods of their own class.
Implementation can change without changing the interface.
240
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using Encapsulation
Notes:
In object-oriented programming, the term encapsulation refers to the hiding of data within a
class (a safe capsule) and making it available only through certain methods.
Encapsulation is important because it makes it easier for other programmers to use your
classes and protects certain data within a class from being modified inappropriately.
The figure illustrates the concept of encapsulation by showing a safe that has a public
interface (a combination lock) that, when used correctly, allows access to private contents.
241
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Attributes and methods can have modifiers, such as public, that indicate the levels of
access other objects can have to the attribute or method. The most commonly used
modifiers are public and private.
242
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The public modifier allows the class, its attributes, and methods, to be visible to any object
in your program.
The figure illustrates an elevator in a hotel with free (public) access to any floor in a
building, including areas where visitors or unregistered guests might not be welcome.
243
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PublicElevator
PublicElevator {{
public
boolean
public boolean doorOpen=false;
doorOpen=false;
public
public int
int currentFloor
currentFloor == 1;
1;
public
public final
final int
int TOP_FLOOR
TOP_FLOOR == 5;
5;
public
final
int
BOTTOM_FLOOR
public final int BOTTOM_FLOOR == 1;
1;
}}
Notes:
The following code example illustrates the problems introduced when all of the attributes in
a program are public.
All of the attributes are public, which permits their values to be changed without any error
checking.
244
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PublicElevatorTest
PublicElevatorTest {{
public
static
public static void
void main(String
main(String args[])
args[]) {{
PublicElevator
pubElevator
=
new
PublicElevator pubElevator = new PublicElevator();
PublicElevator();
pubElevator.doorOpen
pubElevator.doorOpen == true;
true; //passengers
//passengers get
get on
on
pubElevator.doorOpen
=
false;
//doors
close
pubElevator.doorOpen = false; //doors close
//go
//go down
down to
to floor
floor 00 (below
(below bottom
bottom of
of building)
building)
pubElevator.currentFloor--;
pubElevator.currentFloor--;
pubElevator.currentFloor++;
pubElevator.currentFloor++;
//jump
//jump to
to floor
floor 77 (only
(only 55 floors
floors in
in building)
building)
pubElevator.currentFloor
=
7;
pubElevator.currentFloor = 7;
pubElevator.doorOpen
pubElevator.doorOpen == true;
true; //passengers
//passengers get
get on/off
on/off
pubElevator.doorOpen
pubElevator.doorOpen == false;
false;
pubElevator.currentFloor
pubElevator.currentFloor == 1;
1; //go
//go to
to the
the first
first floor
floor
Notes:
The code example illustrates how a program could be written to directly access the
attributes of a PublicElevator object, resulting in several problems.
Because the PublicElevator class does not use encapsulation, the PublicElevatorTest class
can change the values of its attributes freely and in many undesirable ways.
245
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
pubElevator.doorOpen
pubElevator.doorOpen == true;
true; //passengers
//passengers get
get on/off
on/off
pubElevator.currentFloor++;
//elevator
moves
pubElevator.currentFloor++; //elevator moves with
with door
door open
open
pubElevator.doorOpen
=
false;
pubElevator.doorOpen = false;
pubElevator.currentFloor--;
pubElevator.currentFloor--;
pubElevator.currentFloor--;
pubElevator.currentFloor--;
}}
}}
Notes:
Generally, you should use the public modifier only on methods and attribute variables that
you want to be accessed directly by other objects.
246
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The private modifier allows objects of a given class, their attributes, and operations to be
inaccessible by other objects.
247
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The figure illustrates an elevator that has private access to certain floors. By having private
access to some floors, people and property on those floors are protected from being
accessed by unregistered guests or visitors.
248
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PrivateElevator1
PrivateElevator1 {{
private
boolean
private boolean doorOpen=false;
doorOpen=false;
private
private int
int currentFloor
currentFloor == 1;
1;
private
private final
final int
int TOP_FLOOR
TOP_FLOOR == 5;
5;
private
final
int
BOTTOM_FLOOR
private final int BOTTOM_FLOOR == 1;
1;
}}
Notes:
The code example illustrates how to encapsulate the data within the previous elevator
example to ensure that the data is not modified inappropriately.
The PrivateElevator1 class only consists of private attribute variables.
249
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PrivateElevator1Test
PrivateElevator1Test {{
public
static
public static void
void main(String
main(String args[])
args[]) {{
PrivateElevator1
privElevator
PrivateElevator1 privElevator == new
new PrivateElevator1();
PrivateElevator1();
/**************************************************
/**************************************************
** The
The following
following lines
lines of
of code
code will
will not
not compile
compile **
** because
they
attempt
to
access
private
because they attempt to access private **
** variables.
variables.
***************************************************/
***************************************************/
privElevator.doorOpen
privElevator.doorOpen == true;
true; //passengers
//passengers get
get on
on
privElevator.doorOpen
=
false;
//doors
close
privElevator.doorOpen = false; //doors close
//go
//go down
down to
to currentFloor
currentFloor 00 (below
(below bottom
bottom of
of building)
building)
privElevator.currentFloor--;
privElevator.currentFloor--;
privElevator.currentFloor++;
privElevator.currentFloor++;
Notes:
In the code example, an object reference attempts to modify the private variables in the
PrivateElevator1 class.
The code in the prior code example does not compile because the main method in the
PrivateElevator1Test class is attempting to change the value of private attributes in the
PrivateElevator1 class.
The PrivateElevator1 class is not very useful, however, because there is no way to modify
the values of the class.
In an ideal program, most or all of the attributes of a class are kept private. Private
attributes cannot be modified or viewed directly by classes outside their own class, they
can only be modified or viewed by methods of that class. These methods should contain
code and business logic to make sure that inappropriate values are not assigned to the
variable for an attribute.
250
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
//jump
//jump to
to currentFloor
currentFloor 77 (only
(only 55 floors
floors in
in building)
building)
privElevator.currentFloor
privElevator.currentFloor == 7;
7;
privElevator.doorOpen
privElevator.doorOpen == true;
true; //passengers
//passengers get
get on/off
on/off
privElevator.doorOpen
privElevator.doorOpen == false;
false;
privElevator.currentFloor
privElevator.currentFloor == 1;
1; //go
//go to
to the
the first
first floor
floor
privElevator.doorOpen
=
true;
//passengers
get
privElevator.doorOpen = true; //passengers get on/off
on/off
privElevator.currentFloor++;
privElevator.currentFloor++; //elevator
//elevator moves
moves with
with door
door open
open
privElevator.doorOpen
=
false;
privElevator.doorOpen = false;
privElevator.currentFloor--;
privElevator.currentFloor--;
privElevator.currentFloor--;
privElevator.currentFloor--;
}}
}}
Notes:
251
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The public method and attribute variable declarations are often referred to as the interface
to a class because they are the only elements that another class can use. The details on
how a class completes an operation within a method is called the implementation of the
method. A goal of good OO programming is to create public methods and attribute variable
declarations so that the implementation can change without affecting the interface.
The figure illustrates the interface of an elevator and two separate implementations. While
many elevators around the world might have the same interface, they can have different
implementations.
When classes are encapsulated, other objects interact with only a few parts (methods) of
every other class. For example, a programmer can change the code block for a print
method as much as needed, but if the declaration of the print method does not change,
then the code that refers to that declaration does not need to change either.
252
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PrivateShirt1
PrivateShirt1 {{
private
private int
int shirtID
shirtID == 0;
0; //
// Default
Default ID
ID for
for the
the shirt
shirt
private
private String
String description
description == -description
-description required-;
required-; //
// default
default
//
// The
The color
color codes
codes are
are R=Red,
R=Red, B=Blue,
B=Blue, G=Green,
G=Green, U=Unset
U=Unset
private
private char
char colorCode
colorCode == U;
U;
private
double
private double price
price == 0.0;
0.0; //
// Default
Default price
price for
for all
all items
items
private
int
quantityInStock
=
0;
//
Default
quantity
private int quantityInStock = 0; // Default quantity for
for all
all items
items
public
public char
char getColorCode()
getColorCode() {{
return
colorCode;
return colorCode;
}}
Notes:
The example contains a PrivateShirt1 class with private attributes and a public method for
getting and setting the colorCode variable.
253
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public void
void setColorCode(char
setColorCode(char newCode)
newCode) {{
colorCode
colorCode == newCode;
newCode;
}}
//Additional
//Additional get
get and
and set
set methods
methods for
for shirtID,
shirtID, description,
description,
//
price,
and
quantityInStock
would
follow
// price, and quantityInStock would follow
}} //
// end
end of
of class
class
Notes:
While this code is syntactically correct, the setcolorCode method does not contain the logic
to ensure that the correct values are set.
254
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PrivateShirt1Test
PrivateShirt1Test {{
public
static
public static void
void main
main (String
(String args[])
args[]) {{
PrivateShirt1
privShirt
=
new
PrivateShirt1();
PrivateShirt1 privShirt = new PrivateShirt1();
char
char colorCode;
colorCode;
//
// Set
Set aa valid
valid colorCode
colorCode
privShirt.setColorCode(R);
privShirt.setColorCode(R);
colorCode
colorCode == privShirt.getColorCode();
privShirt.getColorCode();
//
// The
The PrivateShirtTest1
PrivateShirtTest1 class
class can
can set
set aa valid
valid colorCode
colorCode
System.out.println(Color
System.out.println(Color Code:
Code: ++ colorCode);
colorCode);
//
// Set
Set an
an invalid
invalid color
color code
code
privShirt.setColorCode(Z);
privShirt.setColorCode(Z);
colorCode
colorCode == privShirt.getColorCode();
privShirt.getColorCode();
//The
//The PrivateShirtTest1
PrivateShirtTest1 class
class can
can set
set an
an invalid
invalid colorCode
colorCode
System.out.println(Color
Code:
+
colorCode);
System.out.println(Color Code: + colorCode);
}}
}}
Notes:
The test class in the following code example successfully sets an invalid color code in a
PrivateShirt1 object.
This class can set an invalid code because the PrivateShirt1 class is not properly
encapsulated to prevent invalid codes from being set.
255
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class PrivateShirt2
PrivateShirt2 {{
private
private int
int shirtID
shirtID == 0;
0; //
// Default
Default ID
ID for
for the
the shirt
shirt
private
private String
String description
description == -description
-description required-;
required-; //
// default
default
//
// The
The color
color codes
codes are
are R=Red,
R=Red, B=Blue,
B=Blue, G=Green,
G=Green, U=Unset
U=Unset
private
private char
char colorCode
colorCode == U;
U;
private
double
private double price
price == 0.0;
0.0; //
// Default
Default price
price for
for all
all items
items
private
int
quantityInStock
=
0;
//
Default
quantity
private int quantityInStock = 0; // Default quantity for
for all
all items
items
public
public char
char getColorCode()
getColorCode() {{
return
colorCode;
return colorCode;
}}
Notes:
256
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Following is another version of the PrivateShirt1 class. However, before setting the value,
this class ensures that any value that it receives is valid.
The setColorCode method verifies that a valid color code is set using a switch statement. If
an invalid color code is passed to the setColorCode method, an error is displayed.
After you have written a class encapsulating its data using the private keyword and getter
and setter methods, you can write a class that invokes these getter and setter methods to
access the objects values.
257
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
+
colorCode);
System.out.println(Color Code: + colorCode);
Notes:
258
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
259
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
Example:
public
public class
class PrivateElevator2
PrivateElevator2 {{
private
boolean
private boolean doorOpen=false;
doorOpen=false;
private
private int
int currentFloor
currentFloor == 1;
1;
private
private int
int weight
weight == 0;
0;
final
final int
int CAPACITY
CAPACITY == 1000;
1000;
final
final int
int TOP_FLOOR
TOP_FLOOR == 5;
5;
final
final int
int BOTTOM_FLOOR
BOTTOM_FLOOR == 1;
1;
public
public void
void openDoor()
openDoor() {{
doorOpen
=
doorOpen = true;
true;
}}
Notes:
The code example illustrates how to encapsulate the elevator program to prevent problems
with its use.
260
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
public void
void closeDoor()
closeDoor() {{
CalculateCapacity();
CalculateCapacity();
if
if (weight
(weight <=
<= CAPACITY)
CAPACITY) {{
doorOpen
=
false;
doorOpen = false;
}}
else
else {{
System.out.println(The
System.out.println(The elevator
elevator has
has exceeded
exceeded capacity.);
capacity.);
System.out.println(
System.out.println(Doors
Doors will
will remain
remain open
open until
until someone
someone exits!
exits!);
);
}}
}}
Notes:
261
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
public void
void goUp()
goUp() {{
if
(!doorOpen)
if (!doorOpen) {{
if
if (currentFloor
(currentFloor << TOP_FLOOR)
TOP_FLOOR) {{
currentFloor++;
currentFloor++;
System.out.println(currentFloor);
System.out.println(currentFloor);
}}
else
else {{
System.out.println(Already
System.out.println(Already on
on top
top floor.);
floor.);
}}
}}
else
else {{
System.out.println(Doors
System.out.println(Doors still
still open!);
open!);
}}
}}
Notes:
262
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
public void
void goDown()
goDown() {{
if
(!doorOpen)
if (!doorOpen) {{
if
if (currentFloor
(currentFloor >> BOTTOM_FLOOR)
BOTTOM_FLOOR) {{
currentFloor--;
currentFloor--;
System.out.println(currentFloor);
System.out.println(currentFloor);
}}
else
else {{
System.out.println(Already
System.out.println(Already on
on bottom
bottom floor.);
floor.);
}}
}}
else
else {{
System.out.println(Doors
System.out.println(Doors still
still open!);
open!);
}}
}}
Notes:
263
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
if((desiredFloor
>=
BOTTOM_FLOOR)
if((desiredFloor >= BOTTOM_FLOOR) &&
&& (desiredFloor<=TOP_FLOOR))
(desiredFloor<=TOP_FLOOR)) {{
while
(currentFloor
!=
desiredFloor)
while (currentFloor != desiredFloor) {{
if
if (currentFloor
(currentFloor << desiredFloor)
desiredFloor) {{
goUp();
goUp();
}}
else
else {{
goDown();
goDown();
}}
}}
}}
else
else {{
System.out.println(Invalid
System.out.println(Invalid Floor);
Floor);
}}
}}
Notes:
264
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
Example:
public int
int getFloor()
getFloor() {{
return
return currentFloor;
currentFloor;
}}
public
public boolean
boolean getDoorStatus()
getDoorStatus() {{
return
return doorOpen;
doorOpen;
}}
}}
Notes:
265
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
Example:
public int
int getFloor()
getFloor() {{
return
return currentFloor;
currentFloor;
}}
public
public boolean
boolean getDoorStatus()
getDoorStatus() {{
return
return doorOpen;
doorOpen;
}}
}}
Notes:
The code example illustrates how to access the attribute variables in the PrivateElevator2
class using public methods.
266
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
privElevator.goDown();
privElevator.goDown();
privElevator.goDown();
privElevator.goDown();
int
int curFloor
curFloor == privElevator.getFloor();
privElevator.getFloor();
if
if (curFloor
(curFloor !=
!= 55 &&
&& !! privElevator.getDoorStatus())
privElevator.getDoorStatus()) {{
privElevator.setFloor(5);
privElevator.setFloor(5);
}}
privElevator.setFloor(10);
privElevator.setFloor(10);
privElevator.openDoor();
privElevator.openDoor();
}}
}}
Notes:
267
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
public
public class
class PrivateElevator2Test
PrivateElevator2Test {{
public
static
public static void
void main(String
main(String args[])
args[]) {{
PrivateElevator2
privElevator
PrivateElevator2 privElevator == new
new PrivateElevator2();
PrivateElevator2();
privElevator.openDoor();
privElevator.openDoor();
privElevator.closeDoor();
privElevator.closeDoor();
privElevator.goDown();
privElevator.goDown();
privElevator.goUp();
privElevator.goUp();
privElevator.goUp();
privElevator.goUp();
privElevator.openDoor();
privElevator.openDoor();
privElevator.closeDoor();
privElevator.closeDoor();
privElevator.goDown();
privElevator.goDown();
privElevator.openDoor();
privElevator.openDoor();
privElevator.goDown();
privElevator.goDown();
privElevator.closeDoor();
privElevator.closeDoor();
Notes:
268
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Encapsulated Elevator
privElevator.goDown();
privElevator.goDown();
privElevator.goDown();
privElevator.goDown();
int
int curFloor
curFloor == privElevator.getFloor();
privElevator.getFloor();
if
if (curFloor
(curFloor !=
!= 55 &&
&& !! privElevator.getDoorStatus())
privElevator.getDoorStatus()) {{
privElevator.setFloor(5);
privElevator.setFloor(5);
}}
privElevator.setFloor(10);
privElevator.setFloor(10);
privElevator.openDoor();
privElevator.openDoor();
}}
}}
Notes:
269
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
270
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
271
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
272
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
273
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Constructors of a Class
Notes:
274
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Creating Constructors
To define a constructor use the same name as the class and give no
return type
public
public class
class Hat
Hat {{
private
private String
String type;
type;
public
public Hat(String
Hat(String hatType)
hatType) {{
type
type == hatType;
hatType;
}}
public
public class
class Order
Order {{
Hat
Hat hat1
hat1 == new
new
Hat(Fedora);
Hat(Fedora);
}}
Notes:
275
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Default Constructors
public
public class
class MyClass
MyClass {{
int
int x;
x;
MyClass()
MyClass() {{
xx == 10;
10;
}}
}}
public
public class
class ConstructorDemo
ConstructorDemo {{
public
static
public static void
void main(String[]
main(String[] args
args )) {{
MyClass
t1
=
new
MyClass();
MyClass t1 = new MyClass();
MyClass
MyClass t2
t2 == new
new MyClass();
MyClass();
System.out.println(t1.x
System.out.println(t1.x ++ "" "" ++ t2.x);
t2.x);
}}
}}
Notes:
276
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Overloading Constructors
public
public class
class MyClassTwo
MyClassTwo {{
int
x;
int x;
MyClassTwo()
MyClassTwo() {{
xx == 10;
10;
}}
MyClassTwo(int
MyClassTwo(int i)
i) {{
xx == i;
i;
}}
}}
public
public class
class ParametrizedConstructorDemo
ParametrizedConstructorDemo {{
public
static
public static void
void main(String[]
main(String[] args)
args) {{
MyClassTwo
t1
=
new
MyClassTwo(10);
MyClassTwo t1 = new MyClassTwo(10);
MyClassTwo
MyClassTwo t2
t2 == new
new MyClassTwo(88);
MyClassTwo(88);
System.out.println(t1.x
System.out.println(t1.x ++ "" "" ++ t2.x);
t2.x);
}}
}}
Notes:
277
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Overloading Constructors
public
public class
class Student
Student {{
private int id = 0;
private int id = 0;
private String name;
private String name;
public
public Student()
Student() {{
}}
public
public Student(int
Student(int a)
a) {{
id
id == a;
a;
}}
public
public Student(int
Student(int a,
a, String
String aName)
aName) {{
id
=
a;
id = a;
name
name == aName;
aName;
}}
}}
Notes:
278
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 15
Encapsulation and Constructors Lab
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Create classes, and objects
Invoke methods of a class
Overload constructors
279
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
280
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
281
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
282
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 16
Creating and Using Arrays
Objectives
Creating One-Dimensional Arrays
o Declaring a One-Dimensional Array
o Instantiating a One-Dimensional Array
o Initializing a One-Dimensional Array
o Declaring, Instantiating, and Initializing One-Dimensional Arrays
o Accessing a Value Within an Array
o Storing One-Dimensional Arrays in Memory
Setting Arrays Values Using the length Attribute and a Loop
o The length Attribute
o Setting Array Values Using a Loop
Using the args Array in the main Method
o Converting String Arguments to Other Types
Describing Two-Dimensional Arrays
o Declaring a Two-Dimensional Array
o Instantiating a Two-Dimensional Array
o Initializing a Two-Dimensional Array
Objectives
Upon completion of this module, you should be able to:
283
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
ageOne = 27;
ageTwo = 12;
ageThree = 82;
ageFour = 70;
ageFive = 54;
ageTen = 42;
Notes:
Arrays are commonly used efficient data structures. They allows to group data together in
an efficient manner.
The Java programming language allows you to group multiple values of the same type
(lists) using one-dimensional arrays. Arrays are useful when you have related pieces of
data (such as the ages for several people), but you do not want to create separate
variables to hold each piece of data.
284
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Arrays are used to hold many values of the same data type
The index of an array is used to identify each element of the
array
Arrays also enable us to easily perform various functions like
sorting, searching, merging, etc
Arrays can store only one type of value, where the type is any
data type supported by Java
Notes:
285
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
You can create an array of primitive types, such as int, or an array of references to object
types, such as Shirt.
Each part of the array is an element. If you declare an array of 100 int types, there are 100
elements.
You can access each specific element within the array using its location or index in the
array.
286
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
type [] array_identifier;
Examples:
char [] status;
int [] ages;
Shirt [] shirts;
String [] names;
Notes:
Arrays are handled by an implicit Array object (which is not available in the Java API, but is
available in your code). Just as with any object, you must declare an object reference to
the array, instantiate an Array object, and then initialize the Array object before you can
use it. The syntax used to declare a one-dimensional array is:
type [] array_identifier;
where:
The type represents the primitive data type or object type for the values stored in the
array.
The [] informs the compiler that you are declaring an array.
The array_identifier is the name that you are assigning to refer to the array.
Use the following code to declare an array of char values called status and an array of int
values called ages.
char [] status;
int [] ages;
Use the following code to declare an array of Shirt references called shirts and an array of
String references called names.
Shirt [] shirts;
287
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
String [] names;
When you declare an array, the compiler and the Java virtual machine (JVM) have no idea
how large the arrays will be because you have declared reference variables that do not
currently point to any objects.
288
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
array_identifier = new type [length];
Examples:
status = new char [20];
ages = new int [5];
names = new String [7];
shirts = new Shirt [3];
Notes:
Before you can initialize an array, you must instantiate an Array object large enough to hold
all of the values in the array. Instantiate an array by defining the number of elements in the
array. The syntax used to instantiate an Array object is:
array_identifier = new type [length];
where:
The array_identifier is the name you are assigning to reference the array.
The type represents the primitive data type or object type for the values stored in the
array.
The length represents the size (in number of elements) of the array.
Use the following code to instantiate an array of char called status and an array of int called
ages.
status = new char [20];
ages = new int [5];
Use the following code to instantiate an Array object containing String references called
names and an array of Shirt references called shirts.
names = new String [7];
shirts = new Shirt [3];
289
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
When you instantiate an Array object, every primitive element is initialized to the zero value
for the type you specified. In the case of the char array called status, each value is
initialized to \u0000 (the null character of the Unicode character set). For the int array
called ages, the initial value is the integer value 0. For the names and shirt arrays, the
object references are initialized to null.
290
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
291
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
array_identifier[index] = value;
Examples:
ages[0] =
ages[1] =
ages[2] =
ages[3] =
ages[4] =
shirts[0]
shirts[1]
shirts[2]
19;
42;
92;
33;
46;
= new Shirt();
= new Shirt(G);
= new Shirt(G, 1000);
Notes:
You can fill the contents of an array after you have created the array. The syntax for setting
the values in an array is:
array_identifier[index] = value;
where:
292
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples:
int[] height = new int[11];
height[0] = 69;
height[1] = 61;
height[2] = 70;
height[3] = 74;
height[4] = 62;
height[5] = 69;
height[6] = 66;
height[7] = 73;
height[8] = 79;
height[9] = 62;
height[10] = 70;
Notes:
293
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
type [] array_identifier =
{comma-separated list of values or expressions};
Examples:
int [] ages = {19, 42, 92, 33, 46};
Shirt [] shirts = {new Shirt(), new Shirt(121,Work Shirt,
B, 12.95), new Shirt(122,Flannel Shirt, G, 22.95)};
double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5};
boolean[] tired = {true, false, false, true};
char vowels[] = {'a', 'e', 'i', 'o', 'u'}
Notes:
If you know the values you want in your array at the time that you declare the array, you
can declare, instantiate, and set the values for an Array object in the same line of code.
The syntax for this combined declaration, instantiation, initialization of values is:
type [] array_identifier = {comma-separated_list_of_values_or_expressions};
where:
The type represents the primitive data type or object type for the values stored in the
array.
The [] informs the compiler that you are declaring an array.
The array_identifier is the name you are assigning to the array.
The {comma-separated_list_of_values_or_expressions} represents a list of values
you want to store in the array or a list of expressions with results that will be stored
in the array.
294
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples:
long[] even = {2L, 4L,6L,10L};
long[] value = even;
Notes:
An initializer list can be used to instantiate an array object instead of using the new
operator. The size of the array and its initial values are determined by the initializer list.
295
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Each element of an array is accessed using its index. To access a value from the array,
state the array name and the index number for the element (in braces []) on the right side
of an assignment operator.
The following code example demonstrates how to set the value at a particular index in an
array:
status[0] = 3;
names[1] = "Fred Smith";
ages[1] = 19;
prices[2] = 9.99F;
The following code example demonstrates how to retrieve values from a particular index in
an array:
char s = status[0];
String name = names [1];
int age = ages[1];
double price = prices[2];
296
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Examples:
height[2] = 72;
height[count] = feet * 12;
average = (height[0] + height[1]
+ height[2]) / 3;
System.out.println (The middle value is
+ height[MAX/2]);
pick = height[rand.nextInt(11)];
Notes:
297
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
298
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
299
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
300
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
301
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Arrays are objects referred to by an object reference variable.
The figure illustrates how a primitive array is stored in memory in comparison to how a
primitive data type is stored in memory.
The value of the size variable (a char primitive) is L. The value of sizes[] is 0x334009, and
it points to an object of type array of char with three values. The value of sizes[0] is the
char S, the value of sizes[1] is char M, and the value of sizes[2] is char L.
302
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The figure illustrates how an object reference array is stored in memory.
The value of the myShirt object reference is x99f311 which is an address to an object of
type Shirt with the values 0, 0.0, and U. The value of the shirts[] object reference is
x179009 which is an address to an object of type array of Shirt object references
containing three object references:
The value of the shirts[0] index is 0x00099, which is an object reference pointing to
an object of type Shirt with the values of 0, 0, and U.
The value of the shirts[1] index is 0x00327, which is an object reference pointing to
an object of type Shirt with the values of 0, 0, and U.
The value of the shirts[2] index is 0x00990, which is an object reference pointing to
an object of type Shirt with the values of 0, 0, and U.
303
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
All Array objects have a length attribute variable that contains the length of the array.
The length of an array also referred to as its bounds. The bounds of an array, such as
ages[10], is from ages[0] to ages[9], because all arrays start with element zero (0).
The number of elements in an array are stored as part of the array object. The length is
used by the JVM machine software to ensure that every access to the array corresponds to
an actual element of the array.
If you attempt to access an element of the array that does not exist, such as specifying
ages[21] in your code for an ages array with length [10], you receive an error.
304
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
305
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
The args array accepts an unspecified number of String objects:
public static void main (String args[]);
When you pass strings to your program on the command line, the strings are put in the
args array. To use these strings, you must extract them from the args array and, optionally,
convert them to their proper type.
The formal parameter to the main method of a Java application is always an array of
String objects.
The Java runtime environment invokes the main method when an application is
submitted to the interpreter. The String [] parameter, which we typically call args,
represents command-line arguments that are provided when the interpreted is
invoked.
306
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
int ID = Integer.parseInt(args[0]);
The Integer class is one of Java's
"wrapper" classes that provides
methods useful for manipulating
primitive types. Its parseInt() method
will convert a String into an int,
if possible.
Notes:
The main method treats everything you type as a literal string. If you want to use the string
representation of a number in an expression, you must convert the string to its numerical
equivalent. Every data type has an associated class containing static utility methods for
converting strings to that data type (Integer class for int, Byte class for byte, Long class for
long, and so on). For example, to convert the first argument passed to the main method to
an int type:
int ID = Integer.parseInt(args[0]);
307
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
Java allows arrays of multiple dimensions (two or more), 2-dimensional arrays are often
used to represent:
Tables
Grid
Images
308
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Notes:
You also can store matrices of data by using multiple-dimensional arrays (arrays of arrays,
of arrays, and so on). A two-dimensional array (an array of arrays) is similar to a
spreadsheet with multiple columns (each column represents one array or list of items) and
multiple rows.
309
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
type [][] array_identifier;
Example:
int [][] yearlySales;
Notes:
Two dimensional arrays require an additional set of square brackets. The process of
creating and using two-dimensional arrays is otherwise the same as with one-dimensional
arrays. The syntax for declaring a two dimensional array is:
type [][] array_identifier;
where:
The type represents the primitive data type or object type for the values stored in the
array.
The [][] inform the compiler that you are declaring a two-dimensional array.
The array_identifier is the name you have assigned the array during declaration.
310
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Syntax:
array_identifier = new type [number_of_arrays] [length];
Example:
// Instantiates a two-dimensional array: 5 arrays of 4 elements each
yearlySales = new int[5][4];
Notes:
The syntax for instantiating a two dimensional array is:
array_identifier = new type [number_of_arrays] [length];
where:
The array_identifier is the name you have assigned the array during declaration.
The number_of_arrays is the number of arrays within the array.
The length is the length of each array within the array.
311
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
yearlySales[0][0]
yearlySales[0][1]
yearlySales[0][2]
yearlySales[1][0]
yearlySales[2][0]
yearlySales[3][3]
=
=
=
=
=
=
1000;
1500;
1800;
1000;
1400;
2000;
Notes:
312
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
");
Notes:
313
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Example:
public
public class
class TwoDArray
TwoDArray {{
public
static
public static void
void main
main (String[]
(String[] args)
args) {{
int[][]
table
=
new
int[5][10];
int[][] table = new int[5][10];
//
// Load
Load the
the table
table with
with values
values
for
(int
row=0;
row
for (int row=0; row << table.length;
table.length; row++)
row++)
for
for (int
(int col=0;
col=0; col
col << table[row].length;
table[row].length; col++)
col++)
table[row][col]
table[row][col] == row
row ** 10
10 ++ col;
col;
//
// Print
Print the
the table
table
for
for (int
(int row=0;
row=0; row
row << table.length;
table.length; row++)
row++) {{
for
for (int
(int col=0;
col=0; col
col << table[row].length;
table[row].length; col++)
col++)
System.out.print
System.out.print (table[row][col]
(table[row][col] ++ "\t");
"\t");
System.out.println();
System.out.println();
}}
}}
}}
Notes:
314
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 17
Arrays Lab
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Create and Initialize an array
315
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
316
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
317
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
318
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 18
Implementing Inheritance
Objectives
Inheritance
o Superclasses and Subclasses
o Declaring a Subclass
Objectives
Upon completion of this module, you should be able to:
Define and test your use of inheritance
319
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
320
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
321
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
322
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
Inheritance enables programmers to put common members (variables and methods) in one
class and have other classes inherit these common members from this new class.
The class containing members common to several other classes is called the superclass or
the parent class. The classes that inherit from, or extend, the superclass, are called
subclasses or child classes.
Inheritance results in a class hierarchy of Java classes similar to the taxonomies found in
biology.
In the Java programming language, each class can inherit the members of only one other
class.
Some programming languages, such as C++, allow a class to inherit from multiple
superclasses. This concept is called multiple inheritance. The Java programming
language does not allow multiple inheritance because it can be confusing for programmers
to implement. Instead, the Java programming language uses the concept of an interface.
323
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
324
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
325
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
326
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Inheritance
Notes:
327
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
Syntax:
[class_modifier] class class_identifier extends
superclass_identifier
Notes:
Use the extends keyword to indicate that a class inherits from another class. To declare
that a class is a subclass of another class, use the following syntax in your class
declaration:
[class_modifier] class class_identifier extends superclass_identifier
where:
The class_modifier keyword is optional (as indicated by the square brackets) and
can be public, abstract, or final. If the class_modifier is not included in the class
declaration, it defaults to a default that is sometimes called package level and
allows access only to other classes in the same package.
The class keyword tells the compiler that the code block is a class declaration.
The class_identifier is the name that you give to this subclass.
The extends keyword tells the compiler that this is a subclass of another class.
The superclass_identifier is the name of the superclass that this subclass extends.
328
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
Example:
public
public class
class Animal
Animal {{
public
public void
void speak()
speak() {{
System.out.println("I
System.out.println("I am
am aa generic
generic animal");
animal");
}}
}}
public
public class
class Dog
Dog extends
extends Animal
Animal {{
public
public void
void speak()
speak() {{
System.out.println("Woof!!");
System.out.println("Woof!!");
}}
}}
public
public class
class Cat
Cat extends
extends Animal
Animal {{
public
public void
void speak()
speak() {{
System.out.println(Meow!!");
System.out.println(Meow!!");
}}
}}
Notes:
A subclass, in its declaration, uses the extends keyword, followed by the super class name
to specify its super class
329
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class TwoDShape
TwoDShape {{
double
double width;
width;
double
double height;
height;
}}
public
public void
void showDim()
showDim() {{
System.out.println("Width
System.out.println("Width and
and height
height are
are "" ++ width
width
++ "" and
and "" ++ height);
height);
}}
public
public class
class Triangle
Triangle extends
extends TwoDShape
TwoDShape {{
String
String style;
style;
public
public double
double area()
area() {{
return
return width
width ** height
height // 2;
2;
}}
}}
public
public void
void showStyle()
showStyle() {{
System.out.println("Triangle
System.out.println("Triangle is
is "" ++ style);
style);
}}
Notes:
330
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class ClassRoom
ClassRoom {{
private
private String
String roomNumber;
roomNumber;
private
private int
int totalSeats
totalSeats == 60;
60;
private
private static
static int
int totalRooms
totalRooms == 0;
0;
}}
public
public void
void setRoomNumber(String
setRoomNumber(String rn)
rn) {{
roomNumber
=
rn;
roomNumber = rn;
}}
String
String getRoomNumber()
getRoomNumber() {{
return
return roomNumber;
roomNumber;
}}
public
public void
void setTotalSeats(int
setTotalSeats(int seats)
seats) {{
totalSeats
=
seats;
totalSeats = seats;
}}
public
public int
int getTotalSeats()
getTotalSeats() {{
return
return totalSeats;
totalSeats;
}}
Notes:
331
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class ComputerLab
ComputerLab extends
extends ClassRoom
ClassRoom {{
int
int totalComputers
totalComputers == 30;
30;
String
String labAssistant
labAssistant == "TBA";
"TBA";
public
public void
void printSeatInfo()
printSeatInfo() {{
System.out.println("There
System.out.println("There are
are "" ++ getTotalSeats()
getTotalSeats() ++ ""
seats,
and
+
totalComputers
+
"
computers
seats, and + totalComputers + " computers in
in this
this
computer
computer lab.");
lab.");
}}
public
public String
String getLabAssistant()
getLabAssistant() {{
return
return labAssistant;
labAssistant;
}}
}}
public
public void
void setLabAssistant(String
setLabAssistant(String assistant)
assistant) {{
this.labAssistant
this.labAssistant == assistant;
assistant;
}}
Notes:
332
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class MoodyObject
MoodyObject {{
//
// return
return the
the mood
mood
protected
protected String
String getMood()
getMood() {{
return
"moody";
return "moody";
}}
//
// ask
ask the
the object
object how
how it
it feels
feels
public
public void
void queryMood()
queryMood() {{
System.out.println("I
System.out.println("I feel
feel "" ++ getMood()
getMood() ++ "" today!");
today!");
}}
}}
public
public class
class HappyObject
HappyObject extends
extends MoodyObject
MoodyObject {{
//
// redefine
redefine classs
classs mood
mood
protected
protected String
String getMood()
getMood() {{
return
return "happy";
"happy";
}}
//
// specialization
specialization
public
public void
void laugh()
laugh() {{
System.out.println("hehehe...
System.out.println("hehehe... hahaha...
hahaha... HAHAHAHAHAHA!!!!!");
HAHAHAHAHAHA!!!!!");
}}
}}
Notes:
333
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class SadObject
SadObject extends
extends MoodyObject
MoodyObject {{
//
// redefine
redefine classs
classs mood
mood
protected
protected String
String getMood()
getMood() {{
return
"sad";
return "sad";
}}
//
// specialization
specialization
public
public void
void cry()
cry() {{
System.out.println("wah
System.out.println("wah boo
boo hoo
hoo weep
weep sob
sob
weep");
weep");
}}
}}
Notes:
334
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring a Subclass
public
public class
class MoodyDriver
MoodyDriver {{
public
public final
final static
static void
void main(String[]
main(String[] args)
args) {{
MoodyObject
moodyObject
=
new
MoodyObject();
MoodyObject moodyObject = new MoodyObject();
SadObject
SadObject sadObject
sadObject == new
new SadObject();
SadObject();
HappyObject
HappyObject happyObject
happyObject == new
new HappyObject();
HappyObject();
System.out.println("How
System.out.println("How does
does the
the moody
moody object
object feel
feel today?");
today?");
moodyObject.queryMood();
moodyObject.queryMood();
System.out.println("");
System.out.println("");
System.out.println("How
System.out.println("How does
does the
the sad
sad object
object feel
feel today?");
today?");
sadObject.queryMood();
sadObject.queryMood(); //
// notice
notice that
that overriding
overriding changes
changes the
the mood
mood
sadObject.cry();
sadObject.cry();
System.out.println("");
System.out.println("");
System.out.println("How
System.out.println("How does
does the
the happy
happy object
object feel
feel today?");
today?");
happyObject.queryMood();
happyObject.queryMood(); //notice
//notice that
that overriding
overriding changes
changes the
the mood
mood
happyObject.laugh();
happyObject.laugh();
System.out.println("");
System.out.println("");
}}
}}
Notes:
335
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Module 19
Inheritance Lab
Objectives
Lab Excercises
Objectives
Upon completion of this module, you should be able to:
Work with inheritance
Invoke methods in a super class
336
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
337
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
1. Write a Java program that has a class called Color. Color has an
attribute called colorName that is private. Color also has the following
methods:
final void setColor(String color);
String getColor(); // returned string gives the color
2. The class White inherits from Color, and has its (private) attribute
colorName set to White. The classes Violet, Indigo, Blue, Green,
Yellow, Orange, and Red inherit from the White class. All these classes
have a private variable each, called colorName, initialized to violet,
indigo, blue, yellow, orange, and red respectively. The class
Prism has the following method:
void activatePrism(Color c);
338
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
339
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.