Professional Documents
Culture Documents
Programming Language
JAH-CJ-200
Student Guide
This publication has been produced using Microsoft Word 2000 and Microsoft PowerPoint 2000 for
Windows.
HotJava browser, Java Development Kit (JDK), Java, Java Servlet, Solaris, Enterprise Java Beans,
Java Server Pages, JDK, JSP – Sun Microsystems, Microsoft MAKECAB, Windows operating
system, ASP, VB, .NET, VC++, Microsoft Access, Microsoft SQL Server, Microsoft ODBC for
Oracle – Microsoft Corp, WinZip – Nico Mak Computing, Inc., Time – Time Warner, JDBC –
Javasoft, Oracle – Oracle Corporation, Sybase – Sybase Inc., UDB DB2 – IBM.
The information contained in this document is distributed on an ―as is‖ basis without any warranty
either express or implied. The use of this information or the implementation of any of these
techniques is a customer responsibility and depends on the customer’s ability to evaluate and
integrate them into the customer’s operational environment.
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
3
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Floating Point Primitive Types
Textual Primitive Type
Logical Primitive Type
Choosing a Data Type
Declaring Variables and Assigning Values to Variables
Naming a Variable
Assigning a Value to a Variable
Constants
Storing Primitive and Constants in Memory
Using Arithmetic Operators to Modify Values
Standard Mathematical Operators
Increment and Decrement Operators (++ and --)
Operator Precedence
Using Promotion and Type Casting
Casting primitive types
Implicit versus explicit casting
Compiler Assumptions for Integral and Floating Point Data Types
5
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
When to Declare a static Method or Variable
Using Method Overloading
Method Overloading and the Java API
Uses for Method Overloading
7
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
About This Course
Course Goal
This course provides first-time programmers an excellent choice for learning programming
using the Java Programming language. Keys areas are the significance of the Java
programming language, principles of object orientation (OO), and applying those concepts
when writing Java code encompassing the essential Java programming functions.
At the end of the course, you will be able to write simple Java programs, but will not have
extensive programming ability. This course provides a solid basis in the Java programming
language on which you can base your continued work and training.
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:
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.
The Java programming language
• Object-oriented
– Java supports software development using the notion of
objects
– Software developed using Java is composed of classes and
objects
Notes:
12
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The Java programming language
• 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.
The Java programming language
• 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
– Java’s 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.
The Java programming language
• 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.
The Java programming language
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.
The Java programming language
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:
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.
The Java Platform
• 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.
The Java execution model
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.
The Java execution model
Notes:
Java bytecode can be executed by the Java virtual machine in three ways:
21
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The Java execution model
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 computer’s 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 server-
side 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:
29
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Identifying the Components of a Class
• 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". In Java,
we define objects by creating a class.
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
Comments
//Employee.java
//Employee.java
Class declaration public
public class
class Employee
Employee {{
private
private String
String id;
id;
Attributes private
private String
String lastName;
lastName;
public
public int
int getId()
getId() {…}
{…}
Methods 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 has "" ++ keys
piano has keys ++ "" keys.");
keys.");
}} //end
//end of
of display
display method
method
}} //end
//end of
of class
class
The class body end’s here
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:
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 description == "-description
String 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
public int quantityInStock = 0; // Default quantity for
int quantityInStock = 0; // Default quantity 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
System.out.println("Shirt description:" ++ description);
description:" description);
System.out.println("Color Code: " " ++ colorCode);
System.out.println("Color Code: colorCode);
System.out.println("Shirt price: " " ++ price);
System.out.println("Shirt price: price);
System.out.println("Quantity
System.out.println("Quantity in stock: " " ++ quantityInStock);
in stock: 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.
Variables declarations and assignments
public
public int
int shirtID
shirtID == 0;
0; //
// Default
Default ID
ID for
for the
the shirt
shirt
public
public String description == "-description
String 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 price
double price == 0.0;
0.0; //// Default
Default price
price for
for all
all shirts
shirts
public
public int quantityInStock = 0; // Default quantity for
int quantityInStock = 0; // Default quantity for all
all shirts
shirts
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 you create to make it easier to determine
what the program is doing. Commenting is particularly important in longer programs
developed by large teams where several programmers need to read the code.
Commenting helps with the maintenance of a program when new programmers need to
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
System.out.println("Shirt description:" ++ 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 in stock: " quantityInStock);
System.out.println("Quantity in stock: " ++ quantityInStock
("Quantity );
}} // end of display method
// end of display method
Notes:
Methods follow the attribute variable declarations in a class. The syntax for methods is:
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
methodsandandattributes.
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.
Creating and Using a Test Class
public
public class
class Shirt
Shirt {{
• Example: ……
public
public void
void displayShirtInformation()
displayShirtInformation()
{{
Shirt.java ……
}}
ShirtTest.java }}
public
public class
class ShirtTest
ShirtTest {{
public
public static void
static 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.
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.
The main method
• Syntax:
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 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.
The main method
• This is the definition of the class OurFirstProgram. The class definition only
contains the method main
public
public class
class OurFirstProgram
OurFirstProgram {{
public
public static
static void
void main
main (String
(String args[])
args[]) {{
System.out.println("Rome
System.out.println("Rome wasn‟t burned
wasn‟t burned in
in aa day!");
day!");
}}
}}
Notes:
The code for the method appears between the pair of curly braces. This version of the
method has only one executable statement:
System is the name of a standard class that contains objects that encapsulate the
standard I/O devices for your system—the 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 stream—the command line on your
display screen—and 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 period—System.out—references the out member.
The bit at the rightmost end of the statement, println(―Rome wasn´t 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 method—by 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:
Writing: define your classes by writing what is called .java files (also known as your
source code).
Compiling: send these .java files to the JAVA compiler, which will produce .class
files
Running: send one of these .class files to the JAVA interpreter to run your
program.
Compiling converts the class files you write into bytecode that can be executed by a Java
virtual machine. Remember the rules for naming your Java source files. If a source file
contains a public class, the source file must use the same name as the public class, with a
.java extension. For example, the class Shirt must be saved in a file called Shirt.java.
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
• Syntax:
javac filename
• Example:
javac Shirt.java
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.
Executing (Testing) a program
• Syntax
java classname
• Example
java ShirtTest
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 error’s 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 Exercises. One.
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 Exercises. One.
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 Exercises. Two.
distance = howlong*60;
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.
Identifying Variable Use and Syntax
public
public class
class PianoKeys
PianoKeys {{
public
public static void
static 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 you’ve 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.
Identifying Variable Use and Syntax
public
public class
class Geometry
Geometry {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
int
int sides
sides == 7;
7; //
// declaration
declaration with
with initialization
initialization
System.out.println(
System.out.println("A heptagon has " + sides
"A heptagon has " + 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.
Uses for variables
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.
Variable Declaration and Initialization
Notes:
Attribute variable declarations and initialization follow the same general syntax. The syntax
for attribute variables declaration and initialization is:
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;
identifier = value;
The syntax for declaring and initializing a variable inside of a method is:
54
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Describing Primitive Data Types
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.
Integral Primitive Types
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:
56
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Integral Primitive Types
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 2’s 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.
Integral Primitive Types
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
int javaProgrammers == 2300000;
javaProgrammers 2300000;
long worldPeople
long worldPeople = 5000000000L;
= 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.
Floating Point Primitive Types
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.
Floating Point Primitive Types
public
public class
class Tax
Tax {{
public
public static
static void
void main(
main( String
String args[]
args[] )) {{
double price =
double price = 20;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.
Textual Primitive Types
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 number-
character 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.
Textual Primitive Types
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(
System.out.println( "Print: "" ++ ii );
"Print: );
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.
Logical Primitive Types
Notes:
63
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Logical Primitive Types
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
boolean personWithCat == false;
personWithCat false;
System.out.println(
System.out.println("personWithDog
"personWithDog is "+personWithDog);
is "+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.
65
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Assigning a Value to a Variable
• 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.
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.
Declaring and Initializing Several Variables in One Line of Code
• Syntax:
type identifier = value [, identifier = value];
• Example:
double price = 0.0, wholesalePrice = 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:
Therefore, if there is a separate retail price and wholesale price in the Shirt class, they
might be declared as follows:
67
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Additional Ways to Declare Variables and Assign Values to Variables
Variables
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.
Additional Ways to Declare Variables and Assign Values to Variables
Variables
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.
Storing Primitive and Constants in Memory
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.
Standard Mathematical Operators
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.
Standard Mathematical Operators
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.
Standard Mathematical Operators
public
public class
class Fruit
Fruit {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
//
// Declare and initialize three variables
Declare and initialize three variables
int
int numOranges
numOranges == 5;
5; //// Count
Count of
of oranges
oranges
int numApples = 10; // Count of
int numApples = 10; // Count of apples apples
int
int numFruit
numFruit == 0;
0; //
// Count
Count of
of fruit
fruit
//Calculate
//Calculate the
the total
total fruit
fruit count
count
numFruit=numOranges+numApples;
numFruit=numOranges+numApples;
//
// Display
Display the
the result
result
System.out.println(“A
System.out.println(“A totally
totally fruity
fruity program”);
program”);
System.out.println(“Total
System.out.println(“Total fruit
fruit is
is ““ ++ numFruit);
numFruit);
}}
}}
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.
Standard Mathematical Operators
public
public class
class TempConverter
TempConverter {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
final int BASE = 32;
final int BASE = 32;
final
final double
double CONVERSION_FACTOR
CONVERSION_FACTOR == 9.0
9.0 // 5.0;
5.0;
int celsiusTemp = 24; // value to convert
int celsiusTemp = 24; // value to convert
double
double fahrenheitTemp;
fahrenheitTemp;
fahrenheitTemp
fahrenheitTemp == celsiusTemp
celsiusTemp ** CONVERSION_FACTOR
CONVERSION_FACTOR ++ BASE;
BASE;
System.out.println("Celsius
System.out.println("Celsius Temperature:
Temperature: ""
++ celsiusTemp);
celsiusTemp);
System.out.println("Fahrenheit
System.out.println("Fahrenheit Equivalent:
Equivalent: ""
++ fahrenheitTemp);
fahrenheitTemp);
}}
}}
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.
Increment and Decrement Operators (++ and --)
--)
Notes:
age = age + 1;
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.
Increment and Decrement Operators (++ and --)
--)
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.
Increment and Decrement Operators (++ and --)
--)
5 y = ++x 6 6
5 y = x++ 6 5
5 y = --x 4 4
5 y = x-- 4 5
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.
Increment and Decrement Operators (++ and --)
--)
public
public class
class UnaryOperators
UnaryOperators {{
public
public static
static void
void main(String
main(String args[
args[ ])
]) {{
int
int y;
y;
int
int x == 5;
x 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
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:
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 = (((25 - 5) * 4) / (2 - 10)) + 4;
c = ((20 * 4) / (2 - 10)) + 4;
c = (80 / (2 - 10)) + 4;
c = (80 / -8) + 4;
c = -10 + 4;
c = -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.
Casting primitive types
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.
This example casts a double literal value to an int:
85
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Implicit versus explicit casting
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:
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;
Notes:
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:
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; //
(byte)i; // 00001010
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:
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
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.
Declaring Object References, Instantiating Objects, and Initializing
Initializing Object
References
Notes:
99
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Declaring Object References, Instantiating Objects, and Initializing
Initializing Object
References
public
public class
class ShirtTest
ShirtTest {{
public
public static void
static 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 description == "-description
String description "-description required-";
required-";
public
public char colorCode == „U‟;
char colorCode „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: " +
System.out.println("Shirt price: " + price); price);
System.out.println("Quantity
System.out.println("Quantity in stock: " " ++ quantityInStock);
in stock: 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.
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.
Declaring Object Reference Variables
• 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:
102
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Initializing Object Reference Variables
• Examples:
myShirt = new Shirt();
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:
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.‖
When you have created a valid object instance, you can use it to manipulate an object’s
data or call an object’s 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.
Using an Object Reference Variable to Manipulate Data
public
public class
class ShirtTest2
ShirtTest2 {{
public
public static
static void
void main
main (String
(String args[])
args[]) {{
Shirt
Shirt myShirt;
myShirt;
1. Declare a reference. myShirt
myShirt == new
new Shirt();
Shirt();
2. Create the object. myShirt.size
myShirt.size == „L‟;
„L‟;
3. Assign values. 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.
Using an Object Reference Variable to Manipulate Data
public
public class
class ShirtTestTwo
ShirtTestTwo {{
public
public static void
static 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.
Using an Object Reference Variable to Manipulate Data
public
public class
class AlarmClock
AlarmClock {{
public
public void snooze()
void snooze() {{
System.out.println("ZZZZZ");
System.out.println("ZZZZZ");
}}
}}
public
public class
class AlarmClockTest
AlarmClockTest {{
public
public static void
static 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.
Using an Object Reference Variable to Manipulate Data
public
public class
class AlarmClock
AlarmClock {{
public
public void snooze(long
void snooze(long snoozeInterval)
snoozeInterval) {{
System.out.println("ZZZZZ
System.out.println("ZZZZZ for:
for: "" ++ snoozeInterval);
snoozeInterval);
}}
}}
public
public class
class AlarmClockTest
AlarmClockTest {{
public
public static void
static 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.
Using a Object Reference Variable to Manipulate Data
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.
Using an Object Reference Variable to Manipulate Data
public
public class
class Circle
Circle {{
private
private int radius;
int radius;
}}
public
public class
class Rectangle
Rectangle {{
public
public double
double width
width == 10.128;
10.128;
public
public double height == 5.734;
double height 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.
Storing Object Reference Variables in Memory
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.
Assigning an Object Reference From One Variable to Another
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.
Assigning an Object Reference From One Variable to Another
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.
Assigning an Object Reference From One Variable to Another
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.
Using the String Class
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:
114
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using the String Class
• 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.
Storing String Objects in Memory
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.
Storing String Objects in Memory
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.
Using Reference Variables for String Objects
public
public class
class StringMutation
StringMutation {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String phrase
phrase == new
new String("Change
String("Change is
is inevitable");
inevitable");
String
String mutation1,
mutation1, mutation2,
mutation2, mutation3,
mutation3, mutation4;
mutation4;
System.out.println("Original
System.out.println("Original string:
string: \""
\"" ++ phrase
phrase ++ "\"");
"\"");
System.out.println("Length
System.out.println("Length of of string:
string: "" ++ phrase.length());
phrase.length());
mutation1
mutation1 == phrase.concat(",
phrase.concat(", except
except from
from vending
vending machines.");
machines.");
mutation2 = mutation1.toUpperCase();
mutation2 = mutation1.toUpperCase();
mutation3
mutation3 == mutation2.replace('E',
mutation2.replace('E', 'X');
'X');
mutation4
mutation4 == mutation3.substring(3,
mutation3.substring(3, 30);
30);
//
// Print
Print each
each mutated
mutated string
string
System.out.println("Mutation
System.out.println("Mutation #1: #1: "" ++ mutation1);
mutation1);
System.out.println("Mutation
System.out.println("Mutation #2: #2: "" ++ mutation2);
mutation2);
System.out.println("Mutation
System.out.println("Mutation #3: #3: "" ++ mutation3);
mutation3);
System.out.println("Mutation
System.out.println("Mutation #4: #4: "" ++ mutation4);
mutation4);
System.out.println("Mutated
System.out.println("Mutated length:
length: "" ++ mutation4.length());
mutation4.length());
}}
}}
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.
Using Reference Variables for String Objects
public
public class
class StringEqual
StringEqual {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String str1 = "Hello Dear!";
String str1 = "Hello Dear!";
String
String str2
str2 == "Hello
"Hello Dear!";
Dear!";
String
String str3
str3 == new
new String("Hello
String("Hello Dear!");
Dear!");
if
if (str1.equals(str2))
(str1.equals(str2)) {{
System.out.println("str1
System.out.println("str1 and and str2
str2 refer
refer to
to identical
identical
strings.");
strings.");
}} else
else {{
System.out.println("str1
System.out.println("str1 and and str2
str2 refer
refer to
to non-identical
non-identical
strings.");
strings.");
}}
if
if (str1
(str1 ==
== str3)
str3) {{
System.out.println("str1
System.out.println("str1 and and str3
str3 refer
refer to
to the
the same
same
string.");
string.");
}} else
else {{
System.out.println("str1
System.out.println("str1 and and str3
str3 refer
refer to
to different
different
strings.");
strings.");
}}
}}
}}
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.
Using Reference Variables to Manipulate Data
public
public class
class JoinStrings
JoinStrings {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
String
String firstString
firstString == “Many
“Many “;
“;
String
String secondString
secondString == “hands
“hands “;
“;
String
String thirdString = “make light
thirdString = “make light work”;
work”;
String
String myString;
myString; //
// Variable
Variable to
to store
store results
results
//
// Join
Join three
three strings
strings and
and store
store the
the result
result
myString
myString == firstString
firstString ++ secondString
secondString ++ thirdString;
thirdString;
System.out.println(myString);
System.out.println(myString);
//
// 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
myString = “fifty five is
= “fifty five is ““ ++ 55 ++ 5;
5;
System.out.println(myString);
System.out.println(myString);
//
// Combining
Combining integers
integers and
and aa string
string
myString
myString = 5 + 5 + “ is ten”;
= 5 + 5 + “ is 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.
Using Reference Variables fro Storing Objects
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.
Using Reference Variables for Storing Objects
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.
Using Reference Variables for Storing Objects
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 immutable—which 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:
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
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
BankAccount myAccount;
myAccount = cheque;
System.out.println(myAccount);
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:
130
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using Relational and Conditional Operators
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
public boolean doorOpen=false;
boolean doorOpen=false; //
// Doors
Doors are
are closed
closed by
by default
default
public int currentFloor = 1;
public int currentFloor = 1; // All elevators start on first floor
// All elevators start on first floor
public
public final
final int
int MAX_FLOORS
MAX_FLOORS == 10;
10;
public
public final int MIN_FLOORS == 1;
final int MIN_FLOORS 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:
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.
Elevator Test Class
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
• Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
// program continues here
Notes:
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:
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
private static int
static 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;
public int currentFloor = 1; // All elevators start on first floor
// All elevators start on first floor
public
public final
final int
int MAX_FLOORS
MAX_FLOORS == 10;
10;
public
public final int MIN_FLOORS == 1;
final int MIN_FLOORS 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 GoGo 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;
public int currentFloor = 1; // All elevators start on first floor
// All elevators start on first 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 voidvoid 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 downdown 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.
The if/else Construct
• 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:
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
private static int
static 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.
The if/else Construct
public
public class
class IfElseElevator
IfElseElevator {{
public
public boolean doorOpen=false;
boolean doorOpen=false; // // Doors
Doors are
are closed
closed by
by default
default
public int currentFloor = 1;
public int currentFloor = 1; // All elevators start on first floor
// All elevators start on first 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:
147
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/else 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
if (currentFloor ==
(currentFloor == MIN_FLOORS)
MIN_FLOORS) {{
System.out.println(“Cannot
System.out.println(“Cannot Go Go down”);
down”);
}}
else
else {{
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:
148
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/else Construct
public
public int
int getFloor()
getFloor() {{
return
return currentFloor;
currentFloor;
}}
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.
Chaining if/else Constructs
• 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.
Chaining if/else Constructs
public
public class
class IfElseDemo
IfElseDemo {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
int
int testscore
testscore == 76;
76;
char
char grade;
grade;
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.
Chaining if/else Constructs
public
public class
class IfElseDate
IfElseDate {{
public
public int
int month
month == 10;
10;
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 3131 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 2828 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 3030 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.
Using the switch Construct
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.
Using the switch Construct
• 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:
switch (variable) {
case literal_value:
code_block;
[break;]
case another_literal_value:
code_block;
[break;]
[default:]
code_block;
}
where:
154
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
variables like MAX_NUMBER defined somewhere else), literals (like ’A’ or 10), or
both
The [break;] statement is an optional keyword that causes the flow of code to
immediately exit the switch statement. Without a break statement, all code_blocks
following the accepted case statement are executed (until a break statement or the
end of the switch construct is reached).
The default keyword indicates a default code_block that is executed if all of the other cases
are not met. The default case label is similar to an else construct in an if/else statement.
The
default case is optional.
155
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Using the switch Construct
public
public class
class SwitchDemo
SwitchDemo {{
public
public static void
static void main(String[]
main(String[] args)
args) {{
int month = 8;
int month = 8;
switch
switch (month)
(month) {{
case
case 1:System.out.println("January");break;
1:System.out.println("January");break;
case
case 2:System.out.println("February");break;
2:System.out.println("February");break;
case
case 3:System.out.println("March");break;
3:System.out.println("March");break;
case
case 4:System.out.println("April");break;
4:System.out.println("April");break;
case
case 5:System.out.println("May");break;
5:System.out.println("May");break;
case
case 6:System.out.println("June");break;
6:System.out.println("June");break;
case
case 7:System.out.println("July");break;
7:System.out.println("July");break;
case
case 8:System.out.println("August");break;
8:System.out.println("August");break;
case
case 9:System.out.println("September");break;
9:System.out.println("September");break;
case
case 10:System.out.println("October");break;
10:System.out.println("October");break;
case
case 11:System.out.println("November");break;
11:System.out.println("November");break;
case
case 12:System.out.println("December");break;
12:System.out.println("December");break;
default:System.out.println("Invalid
default:System.out.println("Invalid month.");break;
month.");break;
}}
}}
}}
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.
Using the switch Construct
System.out.println(“There
System.out.println(“There areare 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 3030 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.
Using the switch Construct
public
public class
class SwitchDemo2
SwitchDemo2 {{
public
public static
static void
void main(String[]
main(String[] args) args) {{
int
int month
month == 2;int
2;int year
year == 2000;int
2000;int numDays
numDays == 0; 0;
switch
switch (month)
(month) {{
case
case 1:
1:
case
case 3:
3:
case
case 5:
5:
case
case 7:
7:
case
case 8:
8:
case
case 10:
10:
case
case 12:
12: numDays
numDays == 31;break;
31;break;
case
case 4:
4:
case
case 6:
6:
case
case 9:
9:
case
case 11:numDays
11:numDays == 30;break;
30;break;
case
case 2:
2: if
if (((year
(((year %% 44 ==
== 0)
0) &&
&& !(year
!(year %% 100
100 ==
== 0))
0)) ||
|| (year
(year %% 400
400 ==
== 0))
0))
numDays
numDays == 29;
29;
else
else numDays 28; break;
numDays == 28; break;
default:
default: System.out.println("Invalid
System.out.println("Invalid month.");
month."); break;
break;
}}
System.out.println("Number
System.out.println("Number ofof 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.
When to Use switch Constructs
• 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.
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:
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:
165
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Creating while Loops
while(boolean_expression) {
code_block;
} // end of while construct
// program continues here
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
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.
Creating while Loops
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.
Creating while Loops
public
public class
class WhileElevator
WhileElevator {{
//instance
//instance variables
variables
public
public void
void openDoor()
openDoor() {…}
{…}
public
public void
void closeDoor()
closeDoor() {…}
{…}
public
public void
void goUp()
goUp() {…}
{…}
public
public void
void goDown()
goDown() {…}
{…}
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.
Nested while Loops
•public
Example potential solution:
public class WhileRectangle {
class WhileRectangle {
public
public int
int height
height == 3;
3;
public
public int
int width
width == 10;
10;
public
public void
void displayRectangle()
displayRectangle() {{
int
int colCount == 0;
colCount 0;
int
int rowCount
rowCount == 0;
0;
while
while (rowCount
(rowCount << height)
height) {{
colCount=0;
colCount=0;
while
while (colCount
(colCount << width)
width) {{
System.out.print(“@”);
System.out.print(“@”);
colCount++;
colCount++;
}}
System.out.println();
System.out.println();
rowCount++;
rowCount++;
}}
}}
}}
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.
Developing a for Loop
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:
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.
Developing a for Loop
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 inin 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.
Developing a for Loop
• 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.
Developing a for Loop
public
public class
class ForElevator
ForElevator {{
//instance variables
//instance variables
public void openDoor() {…}
public void openDoor() {…}
public void closeDoor() {…}
public void closeDoor() {…}
public void goUp() {…}
public void goUp() {…}
public void goDown() {…}
public void goDown() {…}
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
if
if (currentFloor > desiredFloor) {{
(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.
Nested for Loops
public
public class
class ForRectangle
ForRectangle {{
public
public int height == 3;
int height 3;
public
public int
int width
width == 10;
10;
public
public void
void displayRectangle()
displayRectangle() {{
for
for (int
(int rowCount
rowCount == 0;
0; rowCount
rowCount << height;
height; rowCount++)
rowCount++) {{
for
for (int
(int colCount
colCount == 0;
0; colCount
colCount << width;
width; colCount++)
colCount++) {{
System.out.print(“@”);
System.out.print(“@”);
}}
System.out.println();
System.out.println();
}}
}}
}}
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.
Coding a do/while Loop
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.
Coding a do/while Loop
public
public class
class DoWhileElevator
DoWhileElevator {{
//instance variables
//instance variables
public void openDoor() {…}
public void openDoor() {…}
public void closeDoor {…}
public void closeDoor {…}
public void goUp() {…}
public void goUp() {…}
public void goDown() {…}
public void goDown() {…}
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);
}}
public int getFloor() {…}
public int getFloor() {…}
public boolean checkDoorStatus() {…}
public boolean checkDoorStatus() {…}
}}
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.
Nested do/while Loops
public
public class
class DoWhileRectangle
DoWhileRectangle {{
public
public int int height
height == 3;
3;
public
public int width == 10;
int width 10;
public
public voidvoid displayRectangle()
displayRectangle() {{
int
int rowCount == 0;
rowCount 0;
int
int colCount
colCount == 0;0;
do
do {{
colCount
colCount == 0; 0;
do
do {{
System.out.print(“@”);
System.out.print(“@”);
colCount++;
colCount++;
}while
}while (colCount
(colCount << width);
width);
System.out.println();
System.out.println();
rowCount++;
rowCount++;
}while
}while (rowCount
(rowCount << height);
height);
}}
}}
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.
Comparing Loop Constructs
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.
Comparing Loop Constructs
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:
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.
Lab Exercises. Two.
183
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. Three.
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.
Creating and Invoking Methods
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.
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.
Basic Form of a Method
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
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 inin 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. The display
method from the Shirt class is a basic method.
194
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Invoking a Method From a Different Class
public
public class
class ShirtTest
ShirtTest {{
public
public static
static void
void main
main (String
(String args[])
args[]) {{
Shirt myShirt;
Shirt myShirt;
myShirt
myShirt == new
new Shirt();
Shirt();
myShirt.displayShirtInformation();
myShirt.displayShirtInformation();
}}
}}
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.
Invoking a Method From a Different Class
•public
Example:
public class
class CountFlips
CountFlips {{
public
public static void
static void main
main (String[]
(String[] args)
args) {{
final int NUM_FLIPS =
final int NUM_FLIPS = 1000;1000;
int
int heads
heads == 0,
0, tails
tails == 0;
0;
Coin
Coin myCoin = new Coin(); //
myCoin = new Coin(); // instantiate
instantiate the
the Coin
Coin object
object
for
for (int count=1; count <= NUM_FLIPS; count++) {{
(int count=1; count <= NUM_FLIPS; count++)
myCoin.flip();
myCoin.flip();
if
if (myCoin.isHeads())
(myCoin.isHeads())
heads++;
heads++;
else
else
tails++;
tails++;
}}
System.out.println
System.out.println ("The("The number
number flips:
flips: "" ++ NUM_FLIPS);
NUM_FLIPS);
System.out.println
System.out.println ("The number of heads: " ++ heads);
("The number of heads: " heads);
System.out.println
System.out.println ("The("The number
number of
of tails:
tails: "" ++ tails);
tails);
}}
}}
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.
Invoking a Method From a Different Class
•import
Example:
import java.util.Random;
java.util.Random;
public
public class Coin
class Coin {{
private
private final int
final int HEADS
HEADS == 0;
0;
private
private final int TAILS == 1;
final int TAILS 1;
private int face;
private int face;
public
public Coin
Coin ()
() {{
flip();
flip();
}}
public
public void
void flip
flip ()
() {{
face
face = (int) (Math.random() ** 2);
= (int) (Math.random() 2);
}}
public
public boolean
boolean isHeads
isHeads ()
() {{
return (face == HEADS);
return (face == HEADS);
}}
}}
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.
Calling and Worker Methods
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 and Worker Methods
public
public class
class One
One {{
public
public static
static void
void main(String args[])) {{
main(String args[]
Calling Two twoRef = new Two();
Two twoRef = new Two();
method twoRef.workerMethod();
twoRef.workerMethod();
}}
}}
public
public class
class TwoTwo {{
public
public void workerMethod()
void workerMethod() {{
Worker int
int ii == 42;
42;
method 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.
Calling and Worker Methods
public
public class
class CallingClass
CallingClass {{
public
public static void
static void main(String
main(String args[])
args[]) {{
WorkerClass
WorkerClass workerObject = new WorkerClass();
workerObject = new WorkerClass();
workerObject.worker1();
workerObject.worker1();
workerObject.worker2();
workerObject.worker2();
}}
}}
public
public class
class WorkerClass
WorkerClass {{
public
public void worker1()
void worker1() {{
int id = 44559;
int id = 44559;
System.out.println(“The
System.out.println(“The idid is
is ”” ++ id);
id);
}}
public
public void
void worker2()
worker2() {{
float
float price
price == 29.99f;
29.99f;
System.out.println(“The
System.out.println(“The price
price isis ”” ++ price);
price);
}}
}}
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.
Invoking a Method in the Same Class
public
public class
class DisclaimerOneFile
DisclaimerOneFile {{
public
public void callMethod()
void callMethod() {{
//calls
//calls the printDisclaimer
the printDisclaimer method
method
printDisclaimer();
printDisclaimer();
}}
public
public void
void printDisclaimer()
printDisclaimer() {{
System.out.println(“Hello
System.out.println(“Hello Culiacan”);
Culiacan”);
}}
}}
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.
Invoking a Method in the Same Class
public
public class
class Elevator
Elevator {{
//instance variables
//instance variables
public
public void
void openDoor()
openDoor() {…}
{…}
public
public void closeDoor() {…}
void closeDoor() {…}
public
public void
void goUp()
goUp() {…}
{…}
public
public void
void goDown()
goDown() {…}
{…}
public
public void
void setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
while
while (currentFloor
(currentFloor != != desiredFloor)
desiredFloor)
if
if (currentFloor
(currentFloor << desiredFloor)
desiredFloor) {{
goUp();
goUp();
}}
else
else {{
goDown();
goDown();
}}
}}
public
public intint getFloor()
getFloor() {…}
{…}
public
public boolean
boolean checkDoorStatus()
checkDoorStatus() {…}{…}
}}
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.
Guidelines for Invoking Methods
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.
Passing Arguments and Returning Values
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.
Passing Arguments and Returning Values
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.
Declaring Methods With Arguments
• 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.
Invoking Methods With Arguments
public
public class
class GetInfo2
GetInfo2 {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
//makes a Shirt object
//makes a Shirt object
Shirt2
Shirt2 theShirt
theShirt == new
new Shirt2();
Shirt2();
//calls
//calls the printInfo method
the printInfo method
theShirt.printInfo(44339,‟L‟);
theShirt.printInfo(44339,‟L‟);
}}
public
public class
class Shirt2
Shirt2 {{
int id;
int id;
char
char size;
size;
public
public void
void printInfo(int
printInfo(int shirtId,
shirtId, char
char shirtSize)
shirtSize) {{
id
id == shirtId;
shirtId; //assign
//assign arguments
arguments to
to variables
variables
size
size == shirtSize;
shirtSize;
System.out.println(id);
System.out.println(id);
System.out.println(size);
System.out.println(size);
}}
}}
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.
Invoking Methods With Arguments
public
public class
class Arguments
Arguments {{
public
public void
void passArguments()
passArguments() {{
subtract(
subtract( 3.14159f,
3.14159f, 9f
9f );
);
}}
public
public void
void subtract(
subtract( float
float first
first ,, float
float second
second )) {{
if((first-second)>=0)
if((first-second)>=0) { {
System.out.println(“Positive”);
System.out.println(“Positive”);
}}
else
else {{
System.out.println(“Negative”);
System.out.println(“Negative”);
}}
}}
}}
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.
Declaring Methods With Return Values
• 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:
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.
Receiving Return Values
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.
Receiving Return Values
public
public class
class ReceiveValues
ReceiveValues {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
AddsValues adder = new AddsValues();
AddsValues adder = new AddsValues();
int
int sum
sum == adder.returnSum();
adder.returnSum();
}}
}}
public
public class
class AddsValues
AddsValues {{
public
public int returnSum() {{
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.
Advantages of Method Use
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.
Creating static Methods and Variables
• 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.
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.
Creating static Methods and Variables
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.
Creating static Methods and Variables
•public
Example:
public class
class CountInstances
CountInstances {{
public
public static
static void
void main
main (String[]
(String[] args)
args) {{
Slogan obj;
Slogan obj;
obj
obj == new
new Slogan
Slogan ("Remember
("Remember the
the Alamo.");
Alamo.");
System.out.println (obj);
System.out.println (obj);
obj
obj == new
new Slogan
Slogan ("Don't
("Don't Worry.
Worry. BeBe Happy.");
Happy.");
System.out.println (obj);
System.out.println (obj);
obj
obj == new
new Slogan
Slogan ("Live
("Live Free
Free or
or Die.");
Die.");
System.out.println (obj);
System.out.println (obj);
obj
obj == new
new Slogan
Slogan ("Talk
("Talk is
is Cheap.");
Cheap.");
System.out.println (obj);
System.out.println (obj);
obj
obj == new
new Slogan
Slogan ("Write
("Write Once,
Once, Run
Run Anywhere.");
Anywhere.");
System.out.println (obj);
System.out.println (obj);
System.out.println();
System.out.println();
System.out.println
System.out.println (("Slogans
"Slogans created: Slogan.getCount());
created: "" ++ Slogan.getCount() );
}}
}}
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.
Creating static Methods and Variables
•public
Example:
public class
class Slogan
Slogan {{
private
private String
String phrase;
phrase;
private
private static int count
static int 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.
Creating static Methods and Variables
Notes:
Static fields, also called class variables—A 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.
Static Methods and Variables in the Java API
• Examples:
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.
Static Methods and Variables in the Java API
•public
Examples:
public class
class Get
Get {{
public
public static
static void
void main
main (String[]
(String[] args)
args) {{
• StaticExample
StaticExample exex == new
new StaticExample();
StaticExample();
ex.getNumber();
ex.getNumber();
}}
public
public class
class StaticExample
StaticExample {{
public
public void getNumber()
void getNumber() {{
System.out.println(“A
System.out.println(“A random
random number:
number: ””
++ Math.random());
Math.random());
}}
}}
Notes:
220
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Static Methods and Variables in the Java API
•//Examples:
// Determines
Determines the
the roots
roots of
of aa quadratic
quadratic equation.
equation.
public
public class
class Quadratic
Quadratic {{
public
public static void
static void main
main (String[]
(String[] args)
args) {{
• int a, b, c; // ax^2 + bx
int a, b, c; // ax^2 + bx + c + c
aa == 5;
5; //
// the
the coefficient
coefficient of
of xx squared
squared
bb == 7;
7; //
// the
the coefficient
coefficient of
of xx
cc == 2;
2; //
// the
the constant
constant
//
// Use
Use the
the quadratic
quadratic formula
formula to
to compute
compute thethe 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
double root1 = ((-1 * b) + Math.sqrt(discriminant)) // (2
root1 = ((-1 * b) + Math.sqrt(discriminant)) (2 ** a);
a);
double
double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 ** a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 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.
When to declare a static method or variable
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.
Uses for Method Overloading
• 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.
Using Method Overloading
MethodOverloadingDemo
MethodOverloadingDemo md
md == new
new MethodOverloadingDemo();
MethodOverloadingDemo();
md.printToScreen(53,8965);
md.printToScreen(53,8965);
md.printToScreen(68,
md.printToScreen(68, 'g');
'g');
md.printToScreen('f',
md.printToScreen('f', 74);
74);
md.printToScreen(64,
md.printToScreen(64, 36,
36, 'h');
'h');
md.printToScreen(85,
md.printToScreen(85, 'd',
'd', (float)745.3,
(float)745.3, "true");
"true");
}}
}}
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.
Using Method Overloading
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.
Using Method Overloading
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.
Method Overloading and the Java API
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.
Uses for Method Overloading
• Examples:
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.
Uses for Method Overloading
public
public class
class ShirtTwo
ShirtTwo {{
public
public int
int shirtID
shirtID == 0;
0; //
// Default
Default ID
ID for
for the
the shirt
shirt
public
public String description = “-description required-”; //
String description = “-description required-”; // default
default
// The color codes are R=Red, B=Blue, G=Green,
// The color codes are R=Red, B=Blue, G=Green, U=Unset U=Unset
public
public char
char colorCode
colorCode == „U‟;
„U‟;
public
public double price
double price == 0.0;
0.0; // // Default
Default price
price for
for all
all items
items
public
public int quantityInStock = 0; // Default quantity for
int quantityInStock = 0; // Default quantity for all
all items
items
public
public void
void setShirtInfo(
setShirtInfo(int
int ID,
ID, String
String desc,
desc, double
double cost,
cost, char color){
char color ){
shirtID
shirtID == ID;
ID;
description
description == desc;
desc;
price
price == cost;
cost;
colorCode
colorCode == color;
color;
}}
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.
Uses for Method Overloading
public
public void
void setShirtInfo(
setShirtInfo(intint ID,
ID, String
String desc,
desc, double
double cost,
cost, char
char color,
color,
int quantity){
int quantity ){
shirtID
shirtID == ID;
ID;
description
description == desc;
desc;
price
price == cost;
cost;
colorCode
colorCode == color;
color;
quantityInStock
quantityInStock == quantity;
quantity;
}}
//
// This
This method
method displays
displays the
the values
values for
for anan item
item
public
public void
void display()
display() {{
System.out.println(“Item
System.out.println(“Item ID: ID: ““ ++ shirtID);
shirtID);
System.out.println(“Item
System.out.println(“Item description:” ++ description);
description:” description);
System.out.println(“Color
System.out.println(“Color Code: Code: ““ ++ colorCode);
colorCode);
System.out.println(“Item
System.out.println(“Item 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 ofof class
class
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.
Uses for Method Overloading
public
public class
class ShirtTwoTest
ShirtTwoTest {{
public
public static void
static void main
main (String
(String args[])
args[]) {{
ShirtTwo shirtOne = new ShirtTwo();
ShirtTwo shirtOne = new ShirtTwo();
ShirtTwo
ShirtTwo shirtTwo
shirtTwo == new
new ShirtTwo();
ShirtTwo();
ShirtTwo
ShirtTwo shirtThree = new
shirtThree = 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(
shirtThree.setShirtInfo( 102, “Shirt Sleeve T-Shirt”, 9.99, „B‟,
102, “Shirt Sleeve T-Shirt”, 9.99, 50);
„B‟, 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:
232
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. One
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.
Lab Exercises. Two.
234
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. Two.
235
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. Three.
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.
Lab Exercises. Three.
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:
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
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.
The public Modifier
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.
The public Modifier
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.
The public Modifier
• Example:
public
public class
class PublicElevator
PublicElevator {{
public
public boolean doorOpen=false;
boolean doorOpen=false;
public
public int
int currentFloor
currentFloor == 1;
1;
public
public final
final int
int TOP_FLOOR
TOP_FLOOR == 5;
5;
public
public final int BOTTOM_FLOOR == 1;
final int BOTTOM_FLOOR 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.
The public Modifier
• Example:
public
public class
class PublicElevatorTest
PublicElevatorTest {{
public
public static void
static void main(String
main(String args[])
args[]) {{
PublicElevator
PublicElevator pubElevator = new PublicElevator();
pubElevator = new PublicElevator();
pubElevator.doorOpen
pubElevator.doorOpen == true;
true; //passengers
//passengers get get on
on
pubElevator.doorOpen = false; //doors
pubElevator.doorOpen = false; //doors close close
//go
//go down
down to
to floor
floor 00 (below
(below bottom
bottom ofof 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
pubElevator.currentFloor = 7;= 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.
The public Modifier
pubElevator.doorOpen
pubElevator.doorOpen == true;
true; //passengers
//passengers get
get on/off
on/off
pubElevator.currentFloor++;
pubElevator.currentFloor++; //elevator moves with
//elevator moves 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.
The private Modifier
}}
pc.privateMethod();
pc.privateMethod(); X
}} public
public class
class PrivateClass
PrivateClass {{
private
private int privateInt;
int
X private
private void
privateInt;
void privateMethod()
privateMethod() {{
System.out.println(privateInt);
System.out.println(privateInt);
}}
}}
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.
The private Modifier
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.
The private Modifier
• Example:
public
public class
class PrivateElevator1
PrivateElevator1 {{
private
private boolean doorOpen=false;
boolean doorOpen=false;
private
private int
int currentFloor
currentFloor == 1;
1;
private
private final
final int
int TOP_FLOOR
TOP_FLOOR == 5;
5;
private
private final int BOTTOM_FLOOR == 1;
final int BOTTOM_FLOOR 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.
249
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
The private Modifier
• Example:
public
public class
class PrivateElevator1Test
PrivateElevator1Test {{
public
public static void
static void main(String
main(String args[])
args[]) {{
PrivateElevator1
PrivateElevator1 privElevator == new
privElevator new PrivateElevator1();
PrivateElevator1();
/**************************************************
/**************************************************
** The
The following
following lines
lines of
of code
code will
will not
not compile
compile **
** because
because they attempt to access private **
they attempt to access private
** variables.
variables.
***************************************************/
***************************************************/
privElevator.doorOpen
privElevator.doorOpen == true;
true; //passengers
//passengers getget on
on
privElevator.doorOpen = false; //doors
privElevator.doorOpen = false; //doors close close
//go
//go down
down to
to currentFloor
currentFloor 00 (below
(below bottom
bottom ofof 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.
The private Modifier
//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 getget 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
privElevator.doorOpen = true; //passengers get on/off
= true; //passengers get 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.
Interface and Implementation
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.
Interface and Implementation
• 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
private double price
double price == 0.0;
0.0; //// Default
Default price
price for
for all
all items
items
private
private int quantityInStock = 0; // Default quantity for
int quantityInStock = 0; // Default quantity 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.
Interface and Implementation
• 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
// price, and quantityInStock would followfollow
}} //
// 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.
Interface and Implementation
• Example:
public
public class
class PrivateShirt1Test
PrivateShirt1Test {{
public
public static void
static 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.
Interface and Implementation
• 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
private double price
double price == 0.0;
0.0; //// Default
Default price
price for
for all
all items
items
private
private int quantityInStock = 0; // Default quantity for
int quantityInStock = 0; // Default quantity 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.
Interface and Implementation
public
public void
void setColorCode(char
setColorCode(char newCode)
newCode) {{
switch (newCode)
switch (newCode) { {
case
case „R‟:
„R‟:
case
case „G‟:
„G‟:
case
case „B‟:
„B‟:
colorCode
colorCode == newCode;
newCode;
break;
break;
default:
default:
System.out.println(“Invalid
System.out.println(“Invalid colorCode.
colorCode. Use
Use R,
R, G,
G, or
or B”);
B”);
}}
}}
//
// Additional
Additional get
get and
and set
set methods
methods for
for shirtID,
shirtID, description,
description,
//
// price,
price, and
and quantityInStock
quantityInStock would
would follow
follow
}} //
// end
end of
of class
class
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 object’s 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.
Interface and Implementation
•public
Example:
public class
class PrivateShirt2Test
PrivateShirt2Test {{
public
public static
static void
void main
main (String
(String args[])
args[]) {{
PrivateShirt2
PrivateShirt2 privShirt
privShirt == new
new PrivateShirt2();
PrivateShirt2();
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 PrivateShirtTest2
PrivateShirtTest2 class
class can
can set
set aa valid
valid colorCode
colorCode
System.out.println(“Color Code: “ + 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.
Interface and Implementation
//
// Set
Set an
an invalid
invalid color
color code
code
privShirt.setColorCode(„Z‟);
privShirt.setColorCode(„Z‟);
colorCode
colorCode == privShirt.getColorCode();
privShirt.getColorCode();
//
// The
The PrivateShirtTest2
PrivateShirtTest2 class
class cannot
cannot set
set an
an invalid
invalid colorCode.
colorCode.
//
// Color
Color code
code is
is still
still RR
System.out.println(“Color
System.out.println(“Color Code:
Code: ““ ++ colorCode);
colorCode);
}}
}} //end
//end class
class
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
private boolean doorOpen=false;
boolean 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 hashas exceeded
exceeded capacity.”);
capacity.”);
System.out.println(“
System.out.println(“Doors
Doors will
will remain
remain open
open until
until someone exits!”);
someone 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
if (!doorOpen) {{
(!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
if (!doorOpen) {{
(!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 onon 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 voidvoid setFloor(int
setFloor(int desiredFloor)
desiredFloor) {{
if((desiredFloor
if((desiredFloor >= BOTTOM_FLOOR) &&
>= BOTTOM_FLOOR) && (desiredFloor<=TOP_FLOOR))
(desiredFloor<=TOP_FLOOR)) {{
while
while (currentFloor != desiredFloor) {{
(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
public static void
static void main(String
main(String args[])
args[]) {{
PrivateElevator2
PrivateElevator2 privElevator == new
privElevator 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.
Describing Variable Scope
public
public void
void displayName()
displayName() {{
//
// begin scope of
begin scope of String
String name
name
String
String name = “Peter Simmons”;
name = “Peter Simmons”;
System.out.println
System.out.println(“My(“My name
name is
is “+
“+ name
name ++ ““ and
and II am age );
am ““ ++ age );
}} //
// end
end scope
scope of
of String
String name
name
public
public String
String getName
getName ()
() {{
return
return name; // this causes
name; // this causes an an error
error
}}
}} //
// end
end scope
scope of
of int
int age
age
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.
Describing Variables Scope
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.
Variable Scope Example
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.
How Instance Variables and Local Variables Appear in Memory
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
public static void
static 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
public static void
static void main(String[]
main(String[] args)
args) {{
MyClassTwo t1 = new MyClassTwo(10);
MyClassTwo t1 = new MyClassTwo(10);
MyClassTwo
MyClassTwo t2t2 == 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;
}}
public void setValues(int sid, String sName) {
public void setValues(int sid, String sName) {
id = sid;
id = sid;
name = sName;
name = sName;
}
}
public static void main(String[] args) {
public static void main(String[] args) {
Student s = new Student(1,"John");
Student s = new Student(1,"John");
}
}
}}
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:
279
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. One.
280
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. Two.
281
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Solution to Lab Exercises:
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.
Creating One-
One-Dimensional Arrays
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.
Creating One-
One-Dimensional Arrays
• 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.
Creating One-
One-Dimensional Arrays
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.
Declaring a One-
One-Dimensional Array
• 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.
Instantiating a One-
One-Dimensional Array
• 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:
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.
Use the following code to instantiate an Array object containing String references called
names and an array of Shirt references called shirts.
290
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.
Instantiating a One-
One-Dimensional Array
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.
Initializing a One-
One-Dimensional Array
• Syntax:
array_identifier[index] = value;
• Examples:
ages[0] = 19;
ages[1] = 42;
ages[2] = 92;
ages[3] = 33;
ages[4] = 46;
shirts[0] = new Shirt();
shirts[1] = new Shirt(„G‟);
shirts[2] = 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.
Initializing a One-
One-Dimensional Array
• 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.
Declaring, Instantiating, and Initializing One-
One-Dimensional Arrays
• Syntax:
type [] array_identifier =
{comma-separated list of values or expressions};
• Examples:
int [] ages = {19, 42, 92, 33, 46};
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:
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.
Declaring, Instantiating, and Initializing One-
One-Dimensional Arrays
• 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.
Accessing a Value Within an Array
• Examples:
status[0] = ‟3‟;
names[1] = "Fred Smith";
ages[1] = 19;
prices[2] = 9.99F;
char s = status[0];
String name = names [1];
int age = ages[1];
double price = prices[2];
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.
Accessing a Value Within an Array
• 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.
Accessing a Value Within an Array
public
public class
class BasicArray
BasicArray {{
final
final static
static int
int LIMIT
LIMIT == 15;
15;
final
final static
static int
int MULTIPLE
MULTIPLE == 10;
10;
public
public static
static void
void main
main (String[]
(String[] args)
args) {{
int[] list = new int[LIMIT];
int[] list = new int[LIMIT];
//
// Initialize
Initialize the
the array
array values
values
for
for (int index = 0; index
(int index = 0; index << LIMIT;
LIMIT; index++)
index++)
list[index] = index * MULTIPLE;
list[index] = index * MULTIPLE;
list[5]
list[5] == 999;
999; //// change
change one
one array
array value
value
for
for (int
(int index
index == 0;0; index
index << LIMIT;
LIMIT; index++)
index++)
System.out.print
System.out.print (list[index]
(list[index] ++ "" ");
");
System.out.println
System.out.println (); ();
}}
}}
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.
Accessing a Value Within an Array
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.
Accessing a Value Within an Array
public
public class
class Calculator
Calculator {{
public
public static double
static double calculateAverage(int[]
calculateAverage(int[] numbers)
numbers) {{
int sum =
int sum = 0; 0;
for
for (int
(int i=0;
i=0; i<numbers.length;
i<numbers.length; i++)
i++)
sum += numbers[i];
sum += numbers[i];
return
return sum/(double)numbers.length;
sum/(double)numbers.length;
}}
public
public static
static intint findMaximum(int[]
findMaximum(int[] numbers)
numbers) {{
int max = numbers[0];
int max = numbers[0];
for
for (int
(int i=0;
i=0; i<numbers.length;
i<numbers.length; i++)
i++)
if
if (numbers[i] >> max)
(numbers[i] max)
max
max == numbers[i];
numbers[i];
return
return max;max;
}}
}}
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.
Accessing a Value Within an Array
public
public class
class CalculatorTester
CalculatorTester {{
public
public static void
static void main(String
main(String args[])
args[]) {{
int
int numbers[] = {23, 54, 88, 98, 23,
numbers[] = {23, 54, 88, 98, 23, 54,
54, 7,
7, 72,
72, 35,
35, 22};
22};
System.out.println("The average is
System.out.println("The average is " + " +
Calculator.calculateAverage(numbers));
Calculator.calculateAverage(numbers));
}}
}}
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.
Storing Primitive Variables and Arrays of Primitives in Memory
Notes:
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.
Storing Reference Variables and Arrays of References in Memory
Notes:
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.
Setting Array Values Using the length Attribute and a Loop
public
public class
class Primes
Primes {{
public
public static void
static void main
main (String[]
(String[] args)
args) {{
int[]
int[] primeNums = {2, 3, 5, 7, 11, 13,
primeNums = {2, 3, 5, 7, 11, 13, 17,
17, 19};
19};
System.out.println ("Array length: " + primeNums.length);
System.out.println ("Array length: " + primeNums.length);
System.out.println
System.out.println ("The
("The first
first few
few prime
prime numbers
numbers are:");
are:");
for
for (int
(int scan
scan == 0;
0; scan
scan << primeNums.length;
primeNums.length; scan++)
scan++)
System.out.print
System.out.print (primeNums[scan]
(primeNums[scan] ++ "" ");
");
System.out.println
System.out.println (); ();
}}
}}
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.
Using the args Array in the main Method
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.
Using the args Array in the main Method
System.out.println(“args[0]
System.out.println(“args[0] is
is ““ ++ args[0]);
args[0]);
System.out.println(“args[1]
System.out.println(“args[1] is ““ ++ args[1]);
is args[1]);
}}
}}
Notes:
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.
Converting String Arguments to Other Types
• Example:
int ID = Integer.parseInt(args[0]);
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.
Describing Two-
Two-Dimensional Arrays
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.
Describing Two-
Two-Dimensional Arrays
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.
Declaring a Two-
Two-Dimensional Array
• Syntax:
• Example:
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:
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.
Instantiating a Two-
Two-Dimensional Array
• 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:
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.
Initializing a Two-
Two-Dimensional Array
• Example:
yearlySales[0][0] = 1000;
yearlySales[0][1] = 1500;
yearlySales[0][2] = 1800;
yearlySales[1][0] = 1000;
yearlySales[2][0] = 1400;
yearlySales[3][3] = 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.
Initializing a Two-
Two-Dimensional Array
• 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.
Initializing a Two-
Two-Dimensional Array
• Example:
public
public class
class TwoDArray
TwoDArray {{
public
public static void
static 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
for (int row=0; row << table.length;
(int row=0; row 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] == rowrow ** 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:
315
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. One.
316
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. Two.
317
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. Three.
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:
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:
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:
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,
seats, and “ + totalComputers + " computers in
and “ + totalComputers + " computers 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 feelfeel "" ++ getMood()
getMood() ++ "" today!");
today!");
}}
}}
public
public class
class HappyObject
HappyObject extends
extends MoodyObject
MoodyObject {{
//
// redefine
redefine class‟s
class‟s 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 class‟s
class‟s 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 thethe 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:
336
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. One
337
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. Two
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:
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:
338
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. Two
339
Fundamentals of the Java Programming Language. Jah Technologies, IT Services. 2006. Version 1.0.0
This manual was developed for educational purposes only.