Sie sind auf Seite 1von 468

D17249GC11

Edition 1.1
August 2004
D39813
Oracle10g: Java Programming
Student Guide - Volume 1
Copyright 2004, Oracle. All rights reserved.
This documentation contains proprietary information of Oracle Corporation. It is
provided under a license agreement containing restrictions on use and disclosure and
is also protected by copyright law. Reverse engineering of the software is prohibited.
If this documentation is delivered to a U.S. Government Agency of the Department of
Defense, then it is delivered with Restricted Rights and the following legend is
applicable:
Restricted Rights Legend
Use, duplication or disclosure by the Government is subject to restrictions for
commercial computer software and shall be deemed to be Restricted Rights software
under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013,
Rights in Technical Data and Computer Software (October 1988).
This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of Oracle Corporation. Any other copying
is a violation of copyright law and may result in civil and/or criminal penalties.
If this documentation is delivered to a U.S. Government Agency not within the
Department of Defense, then it is delivered with Restricted Rights, as defined in
FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you find any
problems in the documentation, please report them in writing to Education Products,
Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.
Oracle Corporation does not warrant that this document is error-free.
All references to Oracle and Oracle products are trademarks or registered trademarks
of Oracle Corporation.
All other products or company names are used for identification purposes only, and
may be trademarks of their respective owners.
Authors
Jeff Gallus
Glenn Stokol
Technical Contributors
and Reviewers
Kenneth Cooper
Peter Driver
Christian Dugas
Craig Hollister
Chika Izumi
Pete Laseau
Glenn Maslen
Monica Motley
Gayathri Rajagopal
Publisher
Poornima G
Preface
I Introduction
Objectives I-2
Course Overview I-3
1 Introducing the Java and Oracle Platforms
Objectives 1-2
What Is Java? 1-3
Key Benefits of Java 1-4
An Object-Oriented Approach 1-6
Platform Independence 1-7
Using Java with Enterprise Internet Computing 1-8
Using the Java Virtual Machine 1-10
How Does JVM Work? 1-12
Benefits of Just-In-Time (JIT) Compilers 1-14
Implementing Security in the Java Environment 1-16
Deployment of Java Applications 1-18
Using Java with Oracle 10g 1-19
Java Software Development Kit 1-20
Using the Appropriate Development Kit 1-21
Integrated Development Environment 1-22
Exploring the JDeveloper Environment 1-23
Oracle10g Products 1-24
Summary 1-25
2 Defining Object-Oriented Principles
Objectives 2-2
What Is Modeling? 2-4
What Are Classes and Objects? 2-5
An Objects Attributes Maintain Its State 2-6
Objects Have Behavior 2-8
Objects Are Modeled as Abstractions 2-9
Defining Object Composition 2-11
The Donut Diagram 2-13
Guided Practice: Spot the Operations and Attributes 2-14
Collaborating Objects 2-15
Objects Interact Through Messages 2-16
What Is a Class? 2-17
How Do You Identify a Class? 2-18
Comparing Classes and Objects 2-19
What Is Encapsulation? 2-21
What Is Inheritance? 2-22
Contents
iii
Using the Is-a-Kind-of Relationship 2-23
What Is Polymorphism? 2-24
Architecture Rules for Reuse 2-26
Engineering for a Black Box Environment 2-27
Order Entry UML Diagram 2-28
Summary 2-29
Practice 2: Overview 2-30
Order Entry System Partial UML Class Model 2-33
3 Basic Java Syntax and Coding Conventions
Objectives 3-2
Examining Toolkit Components 3-4
Exploring Packages in J2SE/J2EE 3-5
Documenting Using the J2SE 3-6
Contents of a Java Source 3-7
Establishing Naming Conventions 3-8
More About Naming Conventions 3-10
Defining a Class 3-12
Rental Class: Example 3-13
Creating Code Blocks 3-15
Defining Java Methods 3-16
Examples of a Method 3-17
Declaring Variables 3-18
Examples of Variables in the Context of a Method 3-19
Rules for Creating Statements 3-20
What Are JavaBeans? 3-21
Managing Bean Properties 3-22
Exposing Properties and Methods 3-23
JavaBean Standards at Design Time 3-24
Compiling and Running a Java Application 3-25
The CLASSPATH Variable 3-26
CLASSPATH: Example 3-27
Summary 3-28
Practice 3: Overview 3-29
4 Exploring Primitive Data Types and Operators
Objectives 4-2
Reserved Keywords 4-4
Variable Types 4-5
Primitive Data Types 4-7
What Are Variables? 4-9
Declaring Variables 4-10
Local Variables 4-11
Defining Variable Names 4-12
What Are Numeric Literals? 4-13
What Are Nonnumeric Literals? 4-15
iv
Guided Practice: Declaring Variables 4-17
What Are Operators? 4-19
Categorizing Operators 4-20
Using the Assignment Operator 4-21
Working with Arithmetic Operators 4-22
More on Arithmetic Operators 4-23
Examining Conversions and Casts 4-24
Incrementing and Decrementing Values 4-26
Relational and Equality Operators 4-27
Using the Conditional Operator (?:) 4-28
Using Logical Operators 4-29
Compound Assignment Operators 4-30
Operator Precedence 4-31
More on Operator Precedence 4-32
Concatenating Strings 4-33
Summary 4-34
Practice 4: Overview 4-35
5 Controlling Program Flow
Objectives 5-2
Categorizing Basic Flow Control Types 5-4
Using Flow Control in Java 5-6
Using the if Statement 5-7
Nesting if Statements 5-8
Guided Practice: Spot the Mistakes 5-9
Defining the switch Statement 5-10
More About the switch Statement 5-12
Looping in Java 5-13
Using the while Loop 5-14
Using the dowhile Loop 5-15
Using the for Loop 5-16
More About the for Loop 5-17
Guided Practice: Spot the Mistakes 5-18
The break Statement 5-19
Summary 5-20
Practice 5: Overview 5-21
6 Building Applications with Oracle JDeveloper 10g
Objectives 6-2
What Is Oracle JDeveloper 10g? 6-3
Exploring the JDeveloper Environment 6-4
Examining Workspaces 6-5
What Are Projects? 6-7
Creating JDeveloper Items 6-8
Creating an Application Workspace 6-9
Specifying Project Details 6-10
Selecting Additional Libraries 6-11
v
Adding a New J2SE 6-12
Looking at the Directory Structure 6-13
Exploring the Skeleton Java Application 6-14
Finding Methods and Fields 6-15
Supporting Code Development with Profiler and Code Coach 6-16
Customizing JDeveloper 6-17
Using the Help System 6-18
Obtaining Help on a Topic 6-19
Oracle JDeveloper 10g Debugger 6-20
Setting Breakpoints 6-22
Using the Debugger Windows 6-24
Stepping Through a Program 6-25
Watching Data and Variables 6-26
Summary 6-27
Practice 6: Overview 6-28
7 Creating Classes and Objects
Objectives 7-2
Using Java Classes 7-4
Comparing Classes and Objects 7-5
Creating Objects 7-6
Using the new Operator 7-7
Comparing Primitives and Objects 7-8
Using the null Reference 7-9
Assigning References 7-10
Declaring Instance Variables 7-11
Accessing public Instance Variables 7-12
Defining Methods 7-13
Calling a Method 7-14
Specifying Method Arguments: Examples 7-15
Returning a Value from a Method 7-16
Calling Instance Methods 7-17
Applying Encapsulation in Java 7-18
Passing Primitives into Methods 7-19
Passing Object References into Methods 7-20
What Are Class Variables? 7-21
Initializing Class Variables 7-22
What Are Class Methods? 7-23
Guided Practice: Class Methods or Instance Methods 7-24
Examples in Java 7-25
Creating Classes Using the Class Editor 7-26
What Are Java Packages? 7-27
Grouping Classes in a Package 7-28
vi
Setting the CLASSPATH with Packages 7-29
Access Modifiers 7-30
Summary 7-32
Practice 7: Overview 7-33
8 Object Life Cycle and Inner Classes
Objectives 8-2
Overloading Methods 8-4
Using the this Reference 8-5
Initializing Instance Variables 8-6
What Are Constructors? 8-7
Defining and Overloading Constructors 8-8
Sharing Code Between Constructors 8-9
final Variables, Methods, and Classes 8-10
Reclaiming Memory 8-11
Using the finalize() Method 8-12
What Are Inner Classes? 8-13
Using Member Inner Class 8-14
Using Local Inner Class 8-15
Defining Anonymous Inner Classes 8-16
Using the Calendar Class 8-17
Summary 8-18
Practice 8: Overview 8-19
9 Using Strings, String Buffer, Wrapper, and Text-Formatting Classes
Objectives 9-2
What Is a String? 9-3
Creating a String 9-4
Concatenating Strings 9-5
Performing Operations on Strings 9-6
Performing More Operations on Strings 9-7
Comparing String Objects 9-8
Producing Strings from Other Objects 9-9
Producing Strings from Primitives 9-10
Producing Primitives from Strings 9-11
Wrapper Class Conversion Methods 9-12
Changing the Contents of a String 9-13
Formatting Classes 9-14
Using the SimpleDateFormat Class 9-15
Using the MessageFormat Class 9-16
Using DecimalFormat 9-17
Guided Practice 9-18
Using Regular Expressions 9-20
vii
About System.out.println 9-23
About OutputStream and PrintStream 9-24
What Is Object Serialization? 9-25
Serialization Streams, Interfaces, and Modifiers 9-28
Summary 9-29
Practice 9: Overview 9-30
10 Reusing Code with Inheritance and Polymorphism
Objectives 10-2
Key Object-Oriented Components 10-3
Example of Inheritance 10-4
Specifying Inheritance in Java 10-5
Defining Inheritance by Using Oracle JDeveloper 10g 10-6
What Does a Subclass Object Look Like? 10-7
Default Initialization 10-8
The super Reference 10-9
The super Reference Example 10-10
Using Superclass Constructors 10-11
Specifying Additional Methods 10-13
Overriding Superclass Methods 10-15
Invoking Superclass Methods 10-17
Example of Polymorphism in Java 10-19
Treating a Subclass as Its Superclass 10-20
Browsing Superclass References by Using Oracle JDeveloper 10g 10-21
Acme Video and Polymorphism 10-22
Using Polymorphism for Acme Video 10-23
Using the instanceof Operator 10-25
Limiting Methods and Classes with final 10-26
Ensuring Genuine Inheritance 10-27
Summary 10-28
11 Using Arrays and Collections
Objectives 11-2
What Is an Array? 11-3
Creating an Array of Primitives 11-4
Declaring an Array of Primitives 11-5
Creating an Array Object for an Array of Primitives 11-6
Initializing Array Elements 11-8
Creating an Array of Object References 11-9
Initializing the Objects in the Array 11-10
Using an Array of Object References 11-11
Arrays and Exceptions 11-12
Multidimensional Arrays 11-13
main() Revisited 11-14
viii
Working with Variable-Length Structures 11-15
Modifying a Vector 11-16
Accessing a Vector 11-17
Java Collections Framework 11-18
Collections Framework Components 11-20
Using ArrayList and Hashtable 11-21
Using Iterators 11-22
Summary 11-23
Practice 11: Overview 11-24
12 Structuring Code by Using Abstract Classes and Interfaces
Objectives 12-2
Defining Abstract Classes 12-3
Creating Abstract Classes 12-4
What Are Abstract Methods? 12-5
Defining Abstract Methods 12-7
Defining and Using Interfaces 12-8
Examples of Interfaces 12-9
Creating Interfaces 12-10
Implementing Interfaces 12-12
Sort: A Real-World Example 12-13
Overview of the Classes 12-14
How the Sort Works 12-15
The Sortable Interface 12-16
The Sort Class 12-17
The Movie Class 12-18
Using the Sort 12-19
Using instanceof with Interfaces 12-20
Summary 12-21
Practice 12: Overview 12-22
13 Throwing and Catching Exceptions
Objectives 13-2
What Is an Exception? 13-3
How Does Java Handle Exceptions? 13-4
Advantages of Java Exceptions: Separating Error Handling Code 13-5
Advantages of Java Exceptions: Passing Errors Up the Call Stack 13-7
Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13-8
Checked Exceptions, Unchecked Exceptions, and Errors 13-9
What to Do with an Exception 13-11
Catching and Handling Exceptions 13-12
Catching a Single Exception 13-13
Catching Multiple Exceptions 13-14
ix
Cleaning Up with a finally Block 13-15
Catching and Handling Exceptions: Guided Practice 13-16
Allowing an Exception to Pass to the Calling Method 13-18
Throwing Exceptions 13-19
Creating Exceptions 13-20
Catching an Exception and Throwing a Different Exception 13-21
Summary 13-22
Practice 13: Overview 13-23
14 User Interface Design: Swing Basics Planning the Application Layout
Objectives 14-2
Running Java UI Applications 14-3
AWT, Swing, and JFC 14-4
Swing Features 14-6
Lightweight or Heavyweight Components? 14-8
Planning the UI Layout 14-9
The Containment Hierarchy 14-10
Top-Level Containers 14-12
Intermediate Containers 14-14
Atomic Components 14-15
Layout Management Overview 14-16
Border Layout 14-18
GridBag Layout 14-19
GridBag Constraints 14-20
Using Layout Managers 14-22
Combining Layout Managers 14-24
Using Frames or Dialogs 14-25
Using JPanel Containers 14-27
Adding Borders to Components 14-29
Using Internal Frames 14-30
Swing Text Controls 14-32
Adding Components with Oracle JDeveloper 10g 14-33
Creating a Frame 14-34
Adding Components 14-35
Setting Pluggable Look and Feel 14-37
Summary 14-39
Practice 14: Overview 14-40
15 Adding User Interface Components and Event Handling
Objectives 15-2
Swing Components 15-3
Swing Components in JDeveloper 15-5
Invoking the UI Editor 15-7
How to Add a Component to a Form 15-8
Edit the Properties of a Component 15-9
Code Generated by JDeveloper 15-10
x
Creating a Menu 15-12
Using JDeveloper Menu Editor 15-13
Practice 15-1: Overview 15-14
UI for Java Application 15-15
Java Event Handling Model 15-20
Event Handling Code Basics 15-21
Event Handling Process: Registration 15-22
Event Handling Process: The Event Occurs 15-24
Event Handling Process: Running the Event Handler 15-25
Using Adapter Classes for Listeners 15-26
Swing Model View Controller Architecture 15-27
Basic Text Component Methods 15-30
Basic JList Component Methods 15-31
What Events Can a Component Generate? 15-32
How to Define an Event Handler in JDeveloper 15-33
Default Event Handling Code Style Generated by JDeveloper 15-34
Completing the Event Handler Method 15-35
Summary 15-36
Practice 15-2: Overview 15-37
16 Using JDBC to Access the Database
Objectives 16-2
Java, J2EE, and Oracle 10g 16-3
Connecting to a Database with Java 16-4
What Is JDBC? 16-5
Preparing the Environment 16-6
Steps for Using JDBC to Execute SQL Statements 16-8
Step 1: Registering the Driver 16-9
Connecting to the Database 16-10
Oracle JDBC Drivers: Thin Client Driver 16-11
Oracle JDBC Drivers: OCI Client Drivers 16-12
Choosing the Right Driver 16-13
Step 2: Getting a Database Connection 16-14
About JDBC URLs 16-15
JDBC URLs with Oracle Drivers 16-16
Step 3: Creating a Statement 16-17
Using the Statement Interface 16-18
Step 4a: Executing a Query 16-19
The ResultSet Object 16-20
Step 4b: Submitting DML Statements 16-21
Step 5: Processing the Query Results 16-23
Step 6: Closing Connections 16-24
A Basic Query Example 16-25
xi
Mapping Database Types to Java Types 16-26
Handling an Unknown SQL Statement 16-28
Handling Exceptions 16-29
Managing Transactions 16-30
The PreparedStatement Object 16-31
How to Create a PreparedStatement 16-32
How to Execute a PreparedStatement 16-33
Maximize Database Access 16-34
Connection Pooling 16-35
Summary 16-38
Practice 16: Overview 16-39
17 Deploying Applications by Using Java Web Start
Objectives 17-2
What Is Java Web Start? 17-3
Running a Web Start Application 17-4
Advantages of Web Start 17-5
Examining the JNLP File 17-6
Deploying Applications with JDeveloper 17-7
Creating the Deployment Profile File 17-8
Saving the Deployment Profile 17-9
Selecting Files to Deploy 17-10
Making an Executable .jar File 17-11
Creating and Deploying the Archive File 17-12
Using JDeveloper to Deploy an Application to Java Web Start 17-13
Step 1: Generate Deployment Profiles and Archive Application 17-14
Step 2a: Start OC4J 17-15
Step 2b: Creating a Connection 17-16
Step 3: Use Web Start Wizard to Create a JNLP File 17-17
Step 4: Archive and Deploy the Application to the OC4J Server 17-18
Summary 17-19
Practice 17: Overview 17-20
Appendix A: Practice Solutions
Appendix B: Java Language Quick-Reference Guide
Appendix C: Order Entry Solution
xii
Preface
Preface - 3
Profile
Prerequisites
Required: Previous experience with another 3GL programming language, preferably a structured
language such as Pascal or C
Suggested: Familiarity with basic HTML
How This Course Is Organized
Oracle 10g: Java Programming is an instructor-led course featuring lectures and hands-on exercises.
Online demonstrations and written practice sessions reinforce the concepts and skills introduced.
Preface - 4
Related Publications
Oracle Publications
Title Part Number
Oracle 10g: Build J2EE Applications (inClass course) D17247GC10
Oracle JDeveloper 10g: Build Applications with Oracle ADF (inClass course) D16975GC10
Oracle JDeveloper Handbook (Oracle Press)
Additional Publications
System release bulletins
Installation and users guides
Read-me files
International Oracle Users Group (IOUG) articles
Oracle Magazine
Preface - 5
Typographic Conventions
Typographic Conventions In Text
Convention Element Example
Bold Emphasized words and phrases
in Web content only
To navigate within this application, do not
click the Back and Forward buttons.
Bold italic Glossary terms (if there is a
glossary)
The algorithminserts the new key.
Brackets Key names Press [Enter].
Caps and
lowercase
Buttons,
check boxes,
triggers,
windows
Click the Executable button.
Select the Registration Required check
box.
Assign a When-Validate-Item trigger.
Open the Master Schedule window.
Carets Menu paths Select File > Save.
Commas Key sequences Press and release these keys one at a
time:
[Alt], [F], [D]
Preface - 6
Typographic Conventions (continued)
Typographic Conventions In Text (continued)
Convention Object or Term Example
Courier New,
case sensitive
Code output,
SQL and PL/SQL
code elements, Java
code elements,
directory names, file
names, passwords,
path names,
user input,
usernames
Code output: debug.seti (I,300);
SQL code elements: Use the SELECT command to view
information stored in the last_name column of the emp
table.
Java code elements: Java programming involves the
String and StringBuffer classes.
Directory names: bin (DOS), $FMHOME (UNIX)
File names: Locate the init.ora file.
Passwords: Use tiger as your password.
Path names: Open c:\my_docs\projects.
User input: Enter 300.
Usernames: Log on as scott.
Initial cap Graphics labels
(unless the term is a
proper noun)
Customer address (but Oracle Payables)

Italic Emphasized words
and phrases in print
publications, titles
of books and
courses, variables
Do not save changes to the database.
For further information, see Oracle7 Server SQL
Language Reference Manual.
Enter user_id@us.oracle.com, where user_id is
the name of the user.
Plus signs Key combinations Press and hold these keys simultaneously:
[Control] + [Alt] + [Delete]
Quotation
marks
Lesson and chapter
titles in cross
references, interface
elements with long
names that have
only initial caps

This subject is covered in Unit II, Lesson 3, Working
with Objects.

Select the Include a reusable module component and
click Finish.

Use the WHERE clause of query property.


Preface - 7
Typographic Conventions (continued)
Typographic Conventions in Navigation Paths
This course uses simplified navigation paths, such as the following example, to direct you through
Oracle Applications.
Example:
Invoice Batch Summary
(N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve
This simplified path translates to the following:
1. (N) From the Navigator window, select Invoice > Entry > Invoice Batches Summary.
2. (M) From the menu, select Query > Find.
3. (B) Click the Approve button.
Notation:
(N) = Navigator (I) = Icon
(M) = Menu (H) = Hyperlink
(T) = Tab (B) = Button
Copyright 2004, Oracle. All rights reserved.
Introduction
Oracle10g: Java Programming I-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this course, you should be able to do
the following:
Write stand-alone applications with the Java
programming language
Develop and deploy an application
Build, generate, and test application components
by using Oracle JDeveloper 10g
Oracle10g: Java Programming I-3
Copyright 2004, Oracle. All rights reserved.
Course Overview
This course teaches you how to write Java
applications.
You also learn how to build, debug, and deploy
applications by using Oracle JDeveloper 10g.
The development environment is Oracle
JDeveloper 10g and the Oracle Database.
Copyright 2004, Oracle. All rights reserved.
Introducing the Java
and Oracle Platforms
Oracle10g: Java Programming 1-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Identify the key elements of Java
Describe the Java Virtual Machine (JVM)
Examine how Java is used to build applications
Identify the key components of the J2SE Java
Development Kit (known as JDK or SDK)
Describe Java deployment options
Lesson Aim
This lesson introduces the background and usefulness of the Java language. It discusses Javas
position with the Oracle10g. Java is the programming language of choice for Internet
applications. It has gained this status because of its robust nature, the object-orientation of the
language, the depth of its predefined classes, and its write once, run anywhere deployment
model. You learn how Java supports object-oriented programming and architectural neutral
deployment.
Oracle10g: Java Programming 1-3
Copyright 2004, Oracle. All rights reserved.
What Is Java?
Java:
Is a platform and an object-oriented language
Was originally designed by Sun Microsystems for
consumer electronics
Contains a class library
Uses a virtual machine for program execution
What Is Java?
Designed by Sun Microsystems
Java is a platform and an object-oriented programming language, which was originally
developed by Sun Microsystems, Inc. It was created by James Gosling for use in consumer
electronics. Because of the robustness and platform-independent nature of the language, Java
soon moved beyond the consumer electronics industry and found a home on the World Wide
Web. Java is a platform, which means that it is a complete development and deployment
environment.
Class Libraries
Java contains a broad set of predefined classes, which contain attributes and methods that handle
most of the fundamental requirements of programs. Window management, input/output, and
network communication classes are included in the Java Developers Kit (JDK). The class
library makes Java programming significantly easier and faster to develop when compared with
other languages. JDK also contains several utilities to facilitate development processes. These
utilities handle operations, such as debugging, deployment, and documentation.
Java Uses a Virtual Machine
One of the key elements of the Java language is platform independence. A Java program that is
written on one platform can be deployed on any other platform. This is usually referred to as
write once, run anywhere (WORA). This task is accomplished through the use of the Java
Virtual Machine (JVM). JVM runs on a local machine and interprets the Java bytecode and
converts it into platform-specific machine code.
Oracle10g: Java Programming 1-4
Copyright 2004, Oracle. All rights reserved.
Key Benefits of Java
Object-oriented
Interpreted and platform-independent
Dynamic and distributed
Multithreaded
Robust and secure
Key Benefits of Java
Object-Oriented
An object is an entity that has data attributes, plus a set of functions that are used to manipulate
the object. Java is a strongly typed language, which means that almost everything in Java is an
object. The main exceptions are the primitive data types, such as integers and characters.
Interpreted and Platform Independent
Java programs are interpreted to the native machines instruction set at run time. Because Java
executes under the control of a JVM, Java programs can run on any operating system that
provides a JVM.
Dynamic and Distributed
Java classes can be downloaded dynamically over the network when required. In addition, Java
provides extensive support for client-server and distributed programming.
Oracle10g: Java Programming 1-5
Key Benefits of Java (continued)
Multithreaded
Java programs can contain multiple threads to carry out many tasks in parallel. Multithreading
capability is built into Java and is under the control of the platform-dependent JVM.
Robust and Secure
Java has built-in capabilities to prevent memory corruption. Java automatically manages the
processes of memory allocation and array bounds checking. It prohibits pointer arithmetic, and
restricts objects to named spaces in memory.
Oracle10g: Java Programming 1-6
Copyright 2004, Oracle. All rights reserved.
An Object-Oriented Approach
Objects and classes
An object is a run-time representation of a thing.
A class is a static definition of things.
Class models elaborate:
Existing classes and objects
Behavior, purpose, and structure
Relationships between classes
Relationships between run-time objects
Same models exist throughout the project.
Analysis Implementation
Integration
and testing
Design
CLASS MODELS
An Object-Oriented Approach
Object-oriented programming is a powerful and natural paradigm that is used to write
application programs. The approach ensures that programs survive the changes accompanying
the growth of a business and its systems. After you understand the function of each object and
develop clean, reliable interfaces between the functions, you can decommission older parts of an
application system without concern.
Classes provide a means to capture the structure and behavior of a real-world person, place, or
thing, and represent a one-to-one mapping between the real-world object and its implementation.
This one-to-one mapping tends to eliminate the typical transformations that are found in
nonobject-oriented design approaches.
Oracle10g: Java Programming 1-7
Copyright 2004, Oracle. All rights reserved.
Platform Independence
Java source code is stored as text in a .java file.
The .java file is compiled into .class files.
A .class file contains Java bytecodes
(instructions).
The bytecodes are interpreted at run time.
The Java .class file is the executable code.
Compile
Movie.java
JVM
Running program Movie.class
(javac) (java)
Platform Independence
Java Is an Interpreted Language
Java program source code is stored in .java files. For example, a Java program dealing with
movies in a video rental company may have files called Movie.java, Customer.java, and
Rental.java.
Each .java file is compiled into a corresponding .class file with the same name. For
example, a Movie.java compiles to at least one class file. (Inner classes is quite common.)
But, the public Movie.java compiles to one Movie.class. These .class files contain
Java bytecodes, which are platform-independent machine instructions.
Java Virtual Machine (JVM)
JVM provides the environment for running Java programs. The JVM interprets Java bytecodes
into the native instruction set for the machine on which the program is currently running.
The same .class files can be executed unaltered on any platform for which a JVMis provided.
For this reason, JVM is sometimes referred to as a virtual processor.
Traditional Compiled Languages
When compiling a traditional language such as C, the code written by the programmer is
converted into machine instructions for the platform on which the compilation takes place. This
compiled program can then run only on machines that have the same processor as that on which
it was compiled, such as Intel, SPARC, or Alpha.
Oracle10g: Java Programming 1-8
Copyright 2004, Oracle. All rights reserved.
Using Java with Enterprise
Internet Computing
Web
server
Application
server
Presentation
Business
logic
Servlets
JavaServer
Pages (JSPs)
Enterprise
JavaBeans (EJB)
CORBA
Client Data
Java and Enterprise Internet Computing
You can design Java programs as server-based components that form scalable Internet
applications.
The currently accepted model for Java Internet computing divides the end-to-end application
process into several logical tiers. To utilize this model, JavaSoft defined the Java2, Enterprise
Edition (J2EE). There are four logical tiers:
Client Tier
When Java is needed to execute on client machines, it is typically implemented as a browser-
based application. But a thin client can be just Web pages that are delivered from a server as
HTML.
Presentation Tier
This is executed on a Web server. Code in this tier handles the applications presentation to the
client. Common Java features for this function are servlets and JavaServer Pages (JSPs). Servlets
and JSPs can each generate dynamic HTML for display as Web pages to clients.
Oracle10g: Java Programming 1-9
Java and Enterprise Internet Computing (continued)
Application (Business Logic) Tier
You can use Java on an application server to implement shareable, reusable business logic as
application components. A common way to implement this is to use component models, such as
Enterprise JavaBeans (EJB) and Common Object Request Broker Architecture (CORBA)
objects. These two components are also to be considered during design time, when a distributed
environment is required.
Data Tier
The data server not only stores data, but can also store and execute Java code, particularly where
this code is data intensive or enforces validation rules pertaining to the data. You can also use
Business Components, from Oracles Application Development Framework (ADF), to support
the data access of your application.
Oracle10g: Java Programming 1-10
Copyright 2004, Oracle. All rights reserved.
Using the Java Virtual Machine
Operating system
JVM
Application
Running Java Applications
All Java applications run within a Java Virtual Machine (JVM). JVM is invoked differently
depending on whether the Java program is an application or an applet.
Applications
You can run stand-alone applications by invoking a local JVM directly from the operating
system command line and supplying the name of the main class for the application. After loading
the applications main class file, JVM runs the program by calling a known entry point in the
class; that is, a public static method called main(...). JVM runs the code by interpreting the
bytecodes in the Java program and converting bytecode into platform-specific machine
instructions.
Oracle10g: Java Programming 1-11
Running Java Applications (continued)
Running Java Applets
A Java applet is a special type of Java program that is used in Web pages. When a Web browser
reads an HTML page with an applet tag, it downloads the applet over the network to the local
system and runs the applet in a JVM that is built into the browser. The browser invokes a
specific call sequence of known methods in the Java applet class to execute the Java code in the
context of the browsers JVM. The applet entry points differ from the entry point that is used by
JVM to run stand-alone applications.
In the case of an applet, the presentation server is not necessarily used. A Java application is
quite capable, and typically is configured, to connect directly to the business logic.
Applets are not covered in this course, and are only presented here for completeness. In this
course, during deployment of your application, you use the Java Web Start product.
Oracle10g: Java Programming 1-12
Copyright 2004, Oracle. All rights reserved.
How Does JVM Work?
The class loader loads all required classes.
JVM uses a CLASSPATH setting to locate class files.
JVM Verifier checks for illegal bytecodes.
JVM Verifier executes bytecodes.
JVM may invoke a Just-In-Time (JIT) compiler.
Memory Manager releases memory used by the
dereferenced object back to the OS.
JVM handles Garbage collection.
How Does JVM Work?
JVM Class Loader
When a .class file is run, it may require other classes to help perform its task. These classes
are loaded automatically by the class loader in JVM. The required classes may reside on the
local disk or on another system across the network. JVM uses the CLASSPATH environment
variable to determine the location of local .class files. The classpath can be added in run time
by using the java -cp or -classpath option.
Classes that are loaded from the network are kept in a separate namespace from those on the
local system. This prevents name clashes and the replacement or overriding of standard classes,
malicious or otherwise.
JVM Verifier
It is the job of the verifier to make sure that the Java code that is being interpreted does not
violate any of the basic rules of the Java language and that the code is from a trusted source. A
trusted source is an option; and if used, the check is not performed.
This validation ensures that there are no memory access violations or other illegal actions
performed.
Oracle10g: Java Programming 1-13
How Does JVM Work? (continued)
Bytecode Interpreter
JVM is the bytecode interpreter that executes the bytecodes for the loaded class. If enabled, JVM
can use just-in-time (JIT) technology to translate Java bytecodes into native machine
instructions.
Memory Management
JVM keeps track of all instances in use. After an instance is no longer in use, JVM is allowed to
release the memory that is used by that object. It performs the release of memory after the object
is no longer needed, but not necessarily immediately. The process (thread) that JVM uses to
manage dereferenced objects is called garbage collection.
Oracle10g: Java Programming 1-14
Copyright 2004, Oracle. All rights reserved.
Benefits of Just-In-Time (JIT) Compilers
JIT compilers:
Improve performance
Are useful if the same bytecodes are executed
repeatedly
Translate bytecodes to native instruction
Optimize repetitive code, such as loops
Use Java HotSpot VM for better performance and
reliability
Just-In-Time (JIT) Compilers
JVMs translate Java bytecodes into native machine instructions. What happens if the same code
is executed again, later in the program? In an environment without JIT compilers, the code is
interpreted every time it is encountered, even if it has already been interpreted earlier in the
program.
The compilers are designed to easily translate bytecode into machine code, which is optimized to
run on the target platform.
Benefits of Just-In-Time Compilers
Most JVMs now support JIT compilation. JIT compilers translate bytecodes only the first time
that they are encountered; if the same code is executed later, then it is automatically mapped to
the corresponding native machine instruction.
JIT compilers enable Java programs to run more quickly because they obviate the need for
repeated translation of bytecodes to native machine instructions. This is especially effective in
repetitive code, such as loops or recursive functions. Some JIT compilers are intelligent enough
to optimize groups of related bytecodes into more efficient native machine instructions.
Oracle10g: Java Programming 1-15
Just-In-Time (JIT) Compilers (continued)
Java HotSpot
The Java HotSpot virtual machine (VM) is a key component in maximizing the deployment of
enterprise applications. It is a core component of Java 2, Standard Edition (J2SE) software,
which is supported by leading application vendors and technologies. Java HotSpot VM supports
virtually all aspects of development, deployment, and management of corporate applications.
Oracle10g: Java Programming 1-16
Copyright 2004, Oracle. All rights reserved.
Implementing Security
in the Java Environment
Interface-specific access
Class loader
Bytecode verifier
Language and compiler
Java Security Layers
Language and Compiler
The Java language was designed to be a safe language. The constructs that allow direct
manipulation of memory pointers have been eliminated, thereby reducing or even eliminating
run-time program crashes and, as a consequence, memory leaks.
Class Loader
The class loader ensures that each class coming from a local source (built-ins) and the classes
from each network source are stored separately. During execution, the run-time system first
looks up the built-ins for referenced classes; if they are not found, then it consults the referencing
class. This ensures that built-in classes are not overridden by network-loaded classes. This
prevents spoofing, or overriding the expected and trusted behavior of a built-in class. Inside a
JVM, there can be several classloaders controlling each applications namespace.
Oracle10g: Java Programming 1-17
Java Security Layers (continued)
Bytecode Verifier
During the execution of a Java program, JVM can import code from anywhere. Java must make
sure that the imported code is from a trustworthy source. To accomplish this task, the run-time
system performs a series of checks called bytecode verification.
Interface-Specific Access
Built-in classes and methods control access to the local file system and network resources. These
classes are restrictive by default. If imported code tries to access the local file system, then the
security mechanism prompts the user.
Oracle10g: Java Programming 1-18
Copyright 2004, Oracle. All rights reserved.
Deployment of Java Applications
Client-side deployment:
JVM runs stand-alone applications from the
command line.
Classes load from a local disk, eliminating the need
to load classes over a network.
Server-side deployment:
Serves multiple clients from a single source
Is compatible with a multitier model for Internet
computing.
Java Applications
Java originally gained popular acceptance because of the success of its applets. Today, however,
it is also possible to write stand-alone applications in Java. A Java application is invoked by
using a JVM and is not run from within a browser.
Client-Side Deployment
Java applications can be deployed to run stand-alone applications within a local operating
system, from the command line. For example, Java applications can access the local file system
or establish connections with other machines on the network.
Server-Side Deployment
Java applications can also execute on the server machine, as long as a JVM is available on that
platform. The use of server-side Java applications is compatible with the multitier model for
Internet computing.
Oracle10g: Java Programming 1-19
Copyright 2004, Oracle. All rights reserved.
Using Java with Oracle 10g
Oracle
database
Web
server Client
Application
server
Presentation
Business
logic
Data
Oracle
Application Server
Java and Oracle 10g
Oracle 10g is a complete and integrated platform, which supports all the server-side
requirements for Java applications. Oracle 10g comprises the following:
Oracle Database 10g
In addition to its database management features, the Oracle Database (currently, version 10g)
provides support for a variety of Java-based structures including Java components and Java
stored procedures. These Java structures are executed in the database by its built-in Java Virtual
Machine, called the Enterprise Java Engine (EJE).
Oracle Application Server 10g
The Oracle Application Server 10g maintains and executes all your application logic, including
Enterprise JavaBeans, through its own built-in JVM. Oracle Application Server 10g uses the
OC4J J2EE server to execute servlets and JSPs. Oracle Application Server 10g Enterprise
Manager is the tool that is used to manage and distribute applications, for ease of use.
Oracle10g: Java Programming 1-20
Copyright 2004, Oracle. All rights reserved.
Java Software Development Kit
Sun Java J2SE (known as JDK and Java SDK)
provides:
Compiler (javac)
Core class library
classes.zip
rt.jar
Debugger (jdb)
Bytecode interpreter: The JVM (java)
Documentation generator (javadoc)
Java Archive utility (jar)
Others
J2SE
Java Software Development Kit
Sun provides the Java 2, Standard Edition (J2SE), which is also known as Java Software
Development Kit (Java SDK) or the Java Development Kit (JDK). The components that are
provided by the J2SE include the following:
The Java compiler is javac. It compiles Java source code into Java bytecodes.
The Java bytecode interpreter, java, is the engine that runs Java applications.
The program that generates documentation in HTML from Java source code comments is
javadoc.
Core Class Library
The J2SE provides core Java class in the following class library files:
classes.zip located in the jdk_home\lib for JDK 1.1.x or earlier
rt.jar located in the jdk_home\jre\lib for Java SDK 1.2.x or later
Other Java J2SE Tools
jdb is the Java class debugger. It is similar to the dbx or gdb debuggers on UNIX.
jar is used to create Java Archive (JAR) files, which are zipped Java programs.
javah is used to generate C files for native methods.
javakey supports the generation of certification keys for trusted Java code.
javap is used to disassemble Java bytecodes into human-readable format.
native2ascii converts Java source code to Latin 1 characters.
serialver is used to generate version numbers for classes.
Oracle10g: Java Programming 1-21
Copyright 2004, Oracle. All rights reserved.
Using the Appropriate Development Kit
Java2 comes in three sizes:
J2ME (Micro Edition): Version specifically targeted
at the consumer space
J2SE (Standard Edition): Complete ground-up
development environment for the Internet
J2EE (Enterprise Edition): Everything in the J2SE
plus an application server and prototyping tools
A Size for Every Need
Java 2, Micro Edition
The technology that Java 2, Micro Edition (J2ME) uses covers the range of extremely tiny
commodities, such as smart cards or a pager, all the way up to the set-top box, which is an
appliance that is almost as powerful as a computer. Like the other editions, the J2ME platform
maintains the qualities for which Java technology has become famous.
Java 2, Standard Edition
The J2SE technology has revolutionized computing with the introduction of a stable, secure, and
feature-complete development and deployment environment that is designed from the ground up
for the Web. It provides cross-platform compatibility, safe network delivery, and smart card to
supercomputer scalability. It provides software developers with a platform for rapid application
development.
Java 2, Enterprise Edition
The J2EE platform is intended as a proof of concept, and a guide for implementations in the
application server marketplace. The J2EE SDK includes a J2EE application server and various
tools to help developers prototype J2EE applications.
Oracle10g: Java Programming 1-22
Copyright 2004, Oracle. All rights reserved.
Integrated Development Environment
Development
UML
ADF
XML
SCM
Debug
Exchange
Database
HTML
Deployment
Synchronized changes
Integrated Development Environment
The add-in API architecture of Integrated Development Environment (IDE) means that all the
tool components (for example, navigator, editor, and modeller) share memory models and event
systems. In this way, an update in one tool is notified to another tool so that it can refresh its
image or take other appropriate actions.
In Oracle 10g, the JDeveloper IDE was developed in pure Java. Synchronization between model
and code can be set so that you can decide to work by using one or the other user interface.
Customizable Environment
You can customize the JDeveloper Integrated Development Environment and arrange its look to
better suit your project needs and programming style. To suit the IDE to your individual taste,
you can:
Change the look and feel of the IDE
Create and manipulate custom navigators
Customize the Component Palette
Customize the IDE environment
Select JDevelopers embedded J2EE server
Arrange the windows in the IDE
Oracle10g: Java Programming 1-23
Copyright 2004, Oracle. All rights reserved.
Exploring the JDeveloper Environment
System Navigator Code Editor Property Inspector
Component Palette
The Oracle JDeveloper 10g Environment
JDeveloper contains four major user interface components. These components are what you use
to edit code, design and manage the user interface, and navigate around your program.
Component Palette
Properties are attributes that define how a component appears and responds at run time. In
JDeveloper, you set a components initial properties during design time, and your code can
change those properties at run time.
System Navigator
System Navigator is made up of two components. The Navigator pane shows a list of files or
classes in a project. The files may be Java source files, .class files, graphics files, HTML,
XML documents, and so on. The Structure pane lists all the methods, fields, and graphical user
interface (GUI) components in a selected class.
Code Editor
Editors are where most of the work takes place; this is where you write code and design user
interfaces. Open an editor by double-clicking the item you want to edit or view.
Property Inspector
Property Inspector is the window that shows the properties and events associated with a selected
component in the design region of a viewer.
Oracle10g: Java Programming 1-24
Copyright 2004, Oracle. All rights reserved.
Oracle10g Products
Oracle 10g Products
Oracle Database 10g
The Oracle Database manages all your information: Word documents, Excel spreadsheets, XML,
images, and so on. Oracle Development Suite 10g tools can automatically reuse the database
structure and its integrity constraints, which reduces the amount of manual coding.
Oracle Application Server 10g
The Oracle Application Server 10g runs all your applications: J2EE applications, Forms,
wireless, portals, and business intelligence. Using Oracle Application Server 10g, all applications
that are developed with Oracle Development Suite 10g can be deployed and managed in a single
application server.
Oracle Developer Suite 10g
Oracle Developer Suite 10g leverages the infrastructure that is offered by Oracle Application
Server 10g and Oracle Database 10g enabling developers to build scalable, secure, and reliable
e-business applications quickly and easily. The suite provides a complete and highly productive
development environment for building applications. Oracle JDeveloper 10g is now available as a
separate product and not just as part of the developer suite product.
Oracle10g: Java Programming 1-25
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
Java code is compiled into platform-independent
bytecodes.
Bytecodes are interpreted by JVM.
Java applications can be stand-alone or
implemented across an Internet-computing model.
Copyright 2004, Oracle. All rights reserved.
Defining Object-Oriented Principles
Oracle10g: Java Programming 2-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Define objects and explain how they are used
Associate objects so that they can communicate
and interact via messages
Define classes and explain how they are used
Describe object-oriented (OO) principles: classes,
objects, and methods
Describe the value of Reusable Software
Components
Examine the OO model that is used in this course
Lesson Aim
This lesson introduces the concepts of classes and objects, which are the foundation to the
object-oriented approach to building applications. It explains the benefits and implementation of
object-oriented principles. It introduces Classes, Objects, and Methods and contrasts OO
principles with traditional programming techniques. This lesson defines the terms Abstraction,
Encapsulation, Inheritance, and Polymorphism, and explains the benefits of each of these
principles. The course application class structure is presented and a simple use case scenario is
discussed to provide context for using an object defined by the class model.
Oracle10g: Java Programming 2-3
Overview of Object-Oriented Programming
Object-oriented programming (OOP) is a relatively new paradigm for creating computer
programs that are adaptable, reusable, and can stand the test of time. The functionality comes
from the design of discrete classes that contain information about objects as well as expected
behaviors. In an OO program, objects send messages to one another and expect certain behaviors
or messages in return.
A good example of object orientation is the personal computer (PC). Although this is not a
programming example, it serves as an example of what OOP can deliver in a programming
environment.
Each PC is made up of components that are manufactured by several unrelated companies. Each
component is built to a specification that includes information and behaviors. A CD drive, for
example, is expected to return data from a CD when the operating system asks for it. The PC
manufacturer does not need to be concerned with the internal workings of the CD drive, only that
it responds to requests appropriately.
In the same way, an OO program may make calls to objects without knowing all the details of
the objects. The program simply expects to get information or produce a specific behavior. By
defining each of these objects separately, the internal workings of each object can change as long
as the way they are called and how they behave stay the same.
OOP uses a number of techniques to achieve adaptability including abstraction, encapsulation,
inheritance, and polymorphism. Each of these topics is discussed in the next few pages.
Oracle10g: Java Programming 2-4
Copyright 2004, Oracle. All rights reserved.
What Is Modeling?
Models perform the following functions:
Describe exactly what the business needs
Facilitate discussion
Prevent mistakes
Modeling and implementation are treated
separately.
Before coding can begin, the model must be
correct.
The House-Building Metaphor
Imagine someone who wants to have a house built. Initially, the house exists only in the minds of
the future home owners as ideas, or pieces of various dreams. Sometimes, the future inhabitants
may not even know what they want, or know whether what they want is even feasible. Dreams
may be full of internal contradictions and impossibilities. This is not a problem in the dream
world; in the physical realm, any inconsistencies and obstacles must be resolved before someone
can construct the house.
A building contractor needs a solid set of blueprints of the house with a description of the
materials to be used, the size of the roof beams, the capacity of the plumbing, and so on. The
contractor follows the plan, and has the knowledge to construct what is on the blueprint. But how
do the ideas of the home owner become the blueprint for the contractor? This is where the
architect comes in.
The architect is the intermediary between the sponsor and the contractor. He or she is trained in
the skills of translating ideas into models. The architects skills in extracting ideas, putting them
down in a format that enables discussion and analysis, giving advice, describing sensible options,
documenting them, and confirming them with the home owners, are the cornerstones to
providing the future home owners with a plan of the home they want.
Oracle10g: Java Programming 2-5
Copyright 2004, Oracle. All rights reserved.
What Are Classes and Objects?
A class:
Models an abstraction of objects
Defines the attributes and behaviors of
objects
Is the blueprint that defines an object
An object:
Is stamped out of the class mold
Is a single instance of a class
Retains the structure and behavior
of a class
What Is an Object?
An object is something tangible, something that can be seen or touched, or something
that can be alluded to and thought about.
Object-oriented programs consist of several objects. These objects communicate with each other
by sending messages from one object to another. In a true object-oriented program, that is all you
have: a coherent group of communicating objects. New objects are created when needed, old
ones are deleted, and existing objects carry out operations by sending messages.
Some examples of objects in an OO program are Customer, Invoice, RentalAgreement, Video,
and so on. Each of these objects holds information about itself and performs certain behaviors. A
customer has a name, address, and phone number. A customer may also rent a video, return a
video, pay a bill, and have other behaviors.
What Are Classes?
A class is a model of abstraction from real-world objects. A class defines the properties and
behavior of a set of objects. A class denotes a category of objects and acts as a blueprint for
creating that type of object.
Oracle10g: Java Programming 2-6
Copyright 2004, Oracle. All rights reserved.
An Objects Attributes Maintain Its State
Objects have knowledge about their current state.
Each piece of knowledge is called an attribute.
The values of attributes dictate the objects state.
Attribute: Ink amount
Attribute: Cash available
Object: My blue pen
Object: Acme Bank ATM
An Objects Attributes Maintain Its State
All the data that an OO system requires must be located in attributes of the existing objects.
Some objects have little or no data, whereas other objects have a lot of data; it depends entirely
on the operations that the object is to perform.
The collection attributes that are defined in an object determine its internal structure; in essence,
the object is a composite data structure, which is often called a user-defined type.
The values that are held in the attributes, at a given point in time, represent the current state of
the object. As the values of attributes change, over time, the state of the object changes. The state
of an object is remembered as long as the object exists in the system (memory). The attribute
values are typically altered by executing an object method in response to some internal or
external event. It is the job of the object code to maintain the integrity of the objects state; that
is, to ensure that the object state is valid for that object.
Oracle10g: Java Programming 2-7
An Objects Attributes Maintain Its State (continued)
Typical Attributes
As with operations, different objects store different attributes. For example, the Acme Bank
ATM object has attributes such as cash available, cards recognized, ATM code, and so on. The
blue pen object has attributes such as amount of ink remaining, diameter of nib, length of
stem, and so on.
Attributes are often deduced after you have decided what operations the object will supply. After
you know what the object must do, you are much better positioned to decide what attributes the
object must store to support these operations. Often, the attributes of an object are initially
known and can be used to define the type of operations that are required to maintain their value.
Oracle10g: Java Programming 2-8
Copyright 2004, Oracle. All rights reserved.
Objects Have Behavior
An object exists to provide behavior (functionality)
to the system.
Each distinct behavior is called an operation.
Operation: Write
Operation: Withdraw
Object: My blue pen
Object: Acme Bank ATM
Objects Have Behavior
The major purpose that is served by objects is performing operations in the system in which they
exist. Object technology decomposes a system entirely into objects; all the interactions between
the system and the outside world, and all the internal computations of the system, are carried out
by the operations (or methods) of objects.
Typical Operations
Different objects naturally perform different operations. For example, the Acme Bank ATM
object has operations such as withdraw, print receipt, swipe card, and so on. Alternatively, the
my blue pen object has operations such as write, leak ink, and so on.
For each object, you have to ask yourself: What does this object do for me? In other words,
what services does this object supply for the other objects in the system? To do this, you must
have an idea about how the object will be used in the system; otherwise, you may end up
defining several operations for each object, which is clearly unsatisfactory. It is important to
understand how the object will be used in the system and to specify only the operations that are
relevant for that mode of usage.
You must also ask how the state of the object is changed; that is, How do the values that are
held in the object attribute get modified? This question enables you to define operations to
maintain the internal details of an object.
Oracle10g: Java Programming 2-9
Copyright 2004, Oracle. All rights reserved.
Objects Are Modeled as Abstractions
A Java object is modeled as an abstract
representation of a real-world object.
Model only those attributes and operations that
are relevant to the context of the problem.
Real-world attributes/operations that you may not want to model:
Attributes: Ink color
Operations: Refill, change color, point, write
Context: Product catalog
Real-world attributes/operations that you may want to model:
Attributes: Model, manufacturer, price
Operations: Change price
Objects Are Modeled as Abstractions
How do you decide what operations and attributes are relevant to the model of the my blue
pen object? The answer is simple. You must understand how the object will be used by the other
objects in the context of this particular system. You model the object as an abstraction of the
real-world example in the context in which it exists.
For example, in the context of a product catalog, the relevant attributes of a pen are reported,
such as the model or name, price, and the manufacturer (for example, Mont Blanc). The
operations that are relevant to this catalog would be to change the price of this pen.
You may need to know whether the pen can be used to write text, be refilled, or have its ink
color changed by replacing a cartridge. However, these latter operations are more relevant to the
way the pen is used by the customer who is purchasing the pen, and therefore the refill, write,
change ink operations are not relevant to the catalog application context and must not be
modeled. When deciding on the attributes and operations for an object, always ask whether they
have relevance in the domain of the application; always evaluate the attributes and operations in
the application context; that is, Are they required to successfully implement the system to meet
business requirements?
Oracle10g: Java Programming 2-10
Objects Are Modeled as Abstractions (continued)
Every Object Is Unique
By definition, each object instance has a unique identity; even if two or more objects have
identical states, that is, if their attribute values are the same, the system always treats them as
different objects. When you create objects in software, you are given a handle to the object,
called an object reference in the Java language. In Java, this handle or object reference is given a
name by which it can refer to the object.
Oracle10g: Java Programming 2-11
Copyright 2004, Oracle. All rights reserved.
A PC may be
an object.
A PC may have a
CD drive, which
may be an object.
A PC may have a
keyboard, mouse, and
network card, all of which
may be objects.
Defining Object Composition
Objects can be composed of other objects.
Objects can be part of other objects.
This relationship between objects is known as
aggregation.
Defining Object Composition
For example, when you talk about writing or reading from a CD drive, you consider the CD
drive as a single object. You may also discuss how the CD drive interacts with the personal
computer system; you treat the computer systems as a single object as well.
When an engineer is called in to repair a CD drive problem, his or her perspective of a CD drive
is more detailed. The engineer visualizes the CD drive spindle, the drive tray, and the laser beam
or reader.
Each of these are components of the CD drive object, and are objects in their own right. Each of
these views of the CD drive is equally valid, and each can be expressed at different times.
When discussing objects, it is useful to use as high a level of abstraction as possible. In this way,
you can conceptualize more of the important objects, and understand more about how the system
works.
Oracle10g: Java Programming 2-12
Defining Object Composition (continued)
Aggregation
This concept of objects being composed of many subobjects is known as aggregation.
When you break a big object down into several low-level objects, these low-level objects can
often be reused in subsequent projects. For example, ATMs use keypads, but so do cash
registers, telephones, and television remote controls.
Note: An aggregation is a special type (closely coupled) of association known as a composition.
To make a distinction, think of an association as a collaborates with relationship. Think of an
aggregation as a made of or composed of relationshipfor example, an account is made of
transactions, whereas an order is made of order lines. There are two types of aggregation, strong
and weak. Strong aggregation is also called composition. Both are implemented by using
references in Java.
Oracle10g: Java Programming 2-13
Copyright 2004, Oracle. All rights reserved.
The Donut Diagram
getAge()
Client or
sender
Person
Message
name
address
birthdate
getName
setBirthdate getAge
getAddress setAddress
The Donut Diagram
The donut diagram provides a visible reminder that an object presents an external interface in
the form of methods and that its instance variables (in this case, name, address, and birthdate) are
private and hidden inside.
Client objects interact with this Person object by sending messages to it; that is, by invoking
its public methods. The client does not know how the getAge method works, nor should the
client care. There could be an age variable in the place of the calculation based on the birthdate
variable. Or perhaps this kind of object returns a constant 39.
Note: This style of diagram has been a very popular one that is useful for conveying concepts.
However, for real-world projects, it quickly becomes limiting: Real objects could have many
methods, which would not fit very well. A similar diagram, which is part of Unified Modeling
Language (UML), is known as an interaction diagram. An interaction diagram is a generic term
that applies to several types of diagrams, such as collaboration diagrams, activity diagrams, and
sequence diagrams. They all represent in different ways where objects are drawn simply as
circles, and messages among them are drawn as arrows.
Oracle University provides an inClass course on UML techniques and notation named Object-
Oriented Analysis and Design using the Unified Modeling Language (UML).
For further information, refer to http://education.oracle.com.
Oracle10g: Java Programming 2-14
Copyright 2004, Oracle. All rights reserved.
Guided Practice:
Spot the Operations and Attributes
Spot the Operations and Attributes
For each graphic, specify at least three attributes and three operations.
Objects Operations Attributes
My pencil Write, erase Lead color
My pen Write, refill Ink color, ink amount
Jaws Eat, swim Capacity, speed
Car
Truck
Satellite


Oracle10g: Java Programming 2-15
Copyright 2004, Oracle. All rights reserved.
Collaborating Objects
Collaborating objects work together to complete a task
and form the basis of an application system.
All methods are defined within a class and are not
defined globally as in traditional languages.
All objects are created from classes and contain
all the attributes and methods of that class.
Objects must associate with each other to
collaborate on common tasks.
Associated objects communicate by sending
messages.
A System Is a Collection of Collaborating Objects
An object system is made up of a collection of different types of objects. If the system is
organized to perform some task, then it must ensure that appropriate objects collaborate with
each other to complete the task. In an object-oriented application, collaboration is necessary
because all code and data are held in some class or object; there is no concept of global methods
or variables.
Objects must first be associated with each other before they can collaborate. After objects are
associated, communication is done by one object sending a message to another object; that is, the
sending object must know the recipient of the message. A message is a request to perform part of
the functionality that is required to support the task.
The association between objects is achieved dynamically through a reference. (That is, two
classes may associate with each other, and two objects may have a link between them.) A
reference forms a link or simply a relationship between the objects. In programming terms, a
reference can be implemented in various ways. For example, a variable in one object contains a
reference to the other object. In Java, one way to create an object is to use the new operator.
Movie m1 = new Movie()
In this example, the class definition is called Movie that is used as a data type for the variable
m1. The variable m1 is defined to hold a reference to the new movie object. Another example of
a link between collaborating objects may be: The customer is the owner of the account, and the
account is owned by the customer.
Oracle10g: Java Programming 2-16
Copyright 2004, Oracle. All rights reserved.
Objects Interact Through Messages
Objects communicate by sending messages.
A sending object must be associated with or
linked to the receiving object.
The message sender requests the receiver to
perform the operation that is named in the
message.
This communication is similar to calling a
procedure:
The sender calls a method of the receiver.
The receiver executes the called method.
Calling a method is always in the context of a
particular object:
myPen.write( ): Object-oriented programming
write (myPen): Traditional structured
programming
Objects Interact Through Messages
Methods are named blocks of code similar to procedures or functions. The OO terminology
sending a message indicates that an object communicates with another object by requesting a
behavior and the associated object is invoked. Before one object can send a message to another,
the sender must be linked, or associated, with the receiver, via an object reference. Therefore,
when a message is sent to a receiver, it executes a method in response.
The receiver responsible for executing the method must have an interface matching the behavior
that is requested in the message to carry out a particular task or algorithm.
The process of message-sending is analogous to calling a procedure in a traditional language.
The sender transfers control to the receiver and resumes execution when the receiver returns
control. One key difference is that when you call a procedure, the call is bound to a specific
piece of code (some subroutine). For example, using the Pen example in the slide:
Pen myPen = new Pen(); // get reference to a pen object
myPen.write(); // Send write() message to myPen
When you send a message, the specific piece of code that gets executed depends on the class (the
type) of the receiver object. This is required to enable the principle of polymorphism, to exist.
Remember, you send a message to an object. This notion of a targeted recipient is different from
calling a procedure.
Oracle10g: Java Programming 2-17
Copyright 2004, Oracle. All rights reserved.
When you create my blue pen, you do not have to
specify its operations or attributes. You simply
say what class it belongs to.
What Is a Class?
A class is a template for objects.
A class definition specifies the operations and
attributes for all instances of that class.
A class is used to manage complexity.
A Class Is a Template for All Objects of That Type
In an object-oriented application, a class is a specification of all the operations and attributes for
that type of object. When you create a particular object (or instance) of that class, you must
initialize the attributes and links with specific values. This can be done either when you create
the object or at a later stage by carrying out some operation on the object.
If you view a class definition as a cookie-cutter, then each class creates cookies (objects) of the
same shape (set of operations, attributes, and links).
Examples of Classes and Objects
To describe the characteristics of all pens, you may define a pen class and specify operations,
such as write and refill, and attributes, such as ink color and ink remaining. You can then create
individual pen objects to represent my blue pen, teachers red pen, and so on.
When you create a pen object, you may initialize the ink amount to be full (or empty) and
specify the color of the ink. The write operation for the pen would presumably check the value of
ink amount and refuse to write if the pen was empty.
Classes Are a Natural Way of Describing Similar Objects
The concept of classes is something that you use every day, without realizing it. For example,
when you sat down in this classroom, presumably you sat on a chair. You probably did not care
which particular chair object you used, as long as the object exhibited all the structure and
behavior of an object belonging to the chair class. The use of chair objects comes naturally to
you after you have grasped the concept of chair, because all chairs exhibit the same properties
although they may each have differing attributes.
Oracle10g: Java Programming 2-18
Copyright 2004, Oracle. All rights reserved.
How Do You Identify a Class?
Identify the common behavior and structure for a
group of objects.
Recognize a single coherent concept.
Caution: A common misconception is the use of
the words classes and objects interchangeably.
Classes define objects.
My blue pen ops: write, refill
attribs: ink amount, color of ink
Your blue pen ops: write, refill
attribs: ink amount
How Do You Classify Objects?
The dictionary defines a class as a set, collection, group, or configuration containing members
having or thought to have at least one attribute in common.
Most objects in the real world do not have names; you usually identify them by the class that
they belong to. For example, the large woody leafy thing at the bottom of your garden is usually
referred to as a tree. The object is the thing at the bottom of your garden, but the class it belongs
to is tree.
Object-oriented software development is all about identifying classes and defining what you
mean by them; that is, Which of all its possible operations, attributes, and links are you
interested in for our system?
It is not always as easy as spotting the trees from the woods; sometimes you get many objects
that do not seem to have much in common, and you have to work at identifying the similarities
between the objects.
Classification Is Not Just a Computer Science Concept
Classification is not a new computer science technique; classification has been going on since
the time of Plato. Most of the objects in the real world are referred to by using a classification
system, and you often use different classifications for the same objects depending on your
current viewpoint.
Oracle10g: Java Programming 2-19
Copyright 2004, Oracle. All rights reserved.
Comparing Classes and Objects
Classes are static definitions that you can use to
understand all the objects of that class.
Objects are the dynamic entities that exist in the
real world and your simulation of it.
Caution: OO people almost always use the words
classes and objects interchangeably; you must
understand the context to differentiate between
the two meanings.
Comparing Classes and Objects
Objects exist only at run time; they hold attribute values, provide operations to be executed, and
communicate by sending messages to each other. There can be many instances of a particular
type of object.
Classes are loaded into the run-time environment and used as a template to create the object
instances, similar to a cookie-cutter. Although they are static definitions, they must be available
at run time to be able to manufacture objects with all the qualities (for example, structure and
function) defined in the class.
A loose analogy from a purely structural perspective: A database table is a definition of a row;
that is, the table structure can be loosely thought of as a class definition, and each row holds
specific values as a separate instance with a structure that is defined by the table (the class). Both
the table definition and its rows must exist in the database. There are many rows, but only one
table definition.
Oracle10g: Java Programming 2-20
Comparing Classes and Objects (continued)
How Many Objects of a Particular Class Exist?
Some classes may have several objects (or instances) in existence. An example of such a class is
String; a typical program contains many String objects at any moment in time.
Other classes may have only one or two instances. For example, high-level classes such as bank
and hotel reservation manager typically have only a single instance.
Note: There need not be any objects of a particular class at any particular point in time. For
example, if you have a banking system, you will not have any bank account objects until
someone opens a bank account.
Oracle10g: Java Programming 2-21
Copyright 2004, Oracle. All rights reserved.
What Is Encapsulation?
Encapsulation hides the internal structure and
operations of an object behind an interface.
A bank ATM is an object that gives its users cash.
The ATM hides (encapsulates) the actual operation
of withdrawal from the user.
The interface (way to operate the ATM) is provided
by the keyboard functions, screen, cash dispenser,
and so on.
Bypassing the encapsulation is bank robbery.
Bypassing encapsulation in object-oriented
programming is impossible.
The Benefits of Encapsulation
With encapsulation, the developer can use an object and ignore the low-level details about how
the object is structured and how it works internally. This frees the developer to think at a higher
level of abstraction.
This results in the ability to comprehend more objects, and to understand more complex systems.
Comparing this with real life, if you had to understand how things worked before being able to
use them, then you would not be able to deal with real-life objects such as ATMs, airplanes,
microwave ovens, computers, or video recorders. To use these things, you deal with them by
using their interfaces and ignoring their implementations.
An added benefit is that the implementation of the operations may change, and you should still
be able to use them in the usual manner.
Think again about the ATM. If the bank rewrites the software or changes the hardware of the
ATM, then it does not have to inform everyone how to use the new system. This is because the
interface has not changed; you still use the ATM in the same manner. When you see minor
changes to the interface of the ATM, it probably means that the software behind it has been
completely rewritten.
In software terms, encapsulation is a mechanism to hide information and functionality, and it
enforces security to control access to internal data and functionality. Programming rules prevent
the encapsulation of an object from being violated.
Oracle10g: Java Programming 2-22
Copyright 2004, Oracle. All rights reserved.
What Is Inheritance?
There may be a commonality between different
classes.
Define the common properties in a superclass.
The subclasses use inheritance to include those
properties.
Savings account Checking account Account
Inheritance Is a Relationship Between Classes
Inheritance is a relationship between classes, where one class declares another as its parent.
When an object of the child class is created, it inherits all the properties of the parent class in
addition to those defined in the child class itself. The child class can provide additional attributes
and behavior that are relevant to it and can also redefine operations that are specified in the
parent class if a different implementation is required.
Inheritance Clarifies Your Design
The use of classes to divide the world into a relatively small number of types is intuitive because
humans naturally think that way. However, the model of the world is not flat. When you define
two classes, you may notice that the classes share a lot of common attributes and operations. For
example, imagine that you are implementing an air-traffic control system, and you define an
airplane class and a helicopter class; these two classes have certain characteristics in common,
and it makes sense to factor the common features into a parent class called aircraft. The airplane
and helicopter classes can then inherit from aircraft; all you must specify in these classes is how
they differ from the aircraft class.
Inheritance Also Improves Productivity
As well as improving the clarity of your design, inheritance can also improve productivity
because new classes can be created quickly, based on existing classes. Where a class exists, but
does not quite meet your needs, the original class need not be modified at all; instead, a new
subclass can be defined, and the differences can be specified in this new class.
Oracle10g: Java Programming 2-23
Copyright 2004, Oracle. All rights reserved.
Using the Is-a-Kind-of Relationship
A subclass object
is-a-kind-of
superclass
object.
A subclass must
have all the
attributes and
behaviors of the
superclass.
Savings account
Account Pen
Pencil
A Subclass Object Is-a-Kind-of Superclass Object
Inheritance is often called the is-a-kind-of relationship. This is because an object of the
subclass is a kind of object of the superclass.
The Account and Savings account example in the slide can be read as follows: A savings account
is a kind of account. This is a very important statement; it implies that all operations of the
superclass also apply to the subclass because each object of the subclass is also an object of the
superclass.
The corollary of this is that if an object of the subclass does not have all the operations of the
superclass, then it should not be a subclass. The Pen and Pencil example in the slide is incorrect
because the refill operation of the superclass, Pen, does not apply to objects of the subclass.
Pencil therefore is not a valid subclass of Pen.
Oracle10g: Java Programming 2-24
Copyright 2004, Oracle. All rights reserved.
What Is Polymorphism?
Polymorphism refers to:
Many forms of the same operation
The ability to request an operation with the same
meaning to different objects. However, each object
implements the operation in a unique way.
The principles of inheritance and object
substitution.
Load passengers
What Is Polymorphism?
Polymorphism (Greek for many forms), as applied to object technology, means that the same
operation can be defined for different classes, and each can implement it in its own way. The
implementation of an operation is called a method, and so polymorphism means that there may
be many ways to implement methods for one operation. In the example in the slide, there is one
operation to load passengers, but each class has a different method to implement the operation.
Why Is Polymorphism Important?
The importance of polymorphism is that the load passengers operation can be invoked on an
object of any of the three classes, and the correct method is called automatically. This frees the
caller from interrogating the object to determine its precise class. Polymorphism requires that an
object can send the same or a common message to different objects, allowing the different
objects to respond in their own way.
Another example: If you have a superclass InventoryItem and Movie, VCR, Toys, and so on as
subclasses, you can easily extend the store with new goods by subclassing from InventoryItem.
The developer creating the OrderEntry application gets an array of InventoryItems and only
knows about the API of this class. By calling abstract methods getDescription() and
getPrice(), he or she will be able to render the Order page without any detailed knowledge
of all the subclasses.
Oracle10g: Java Programming 2-25
What Is Polymorphism? (continued)
Each Polymorphic Method Must Have the Same Logical Behavior
There is a small price to pay for the benefits of polymorphism. Each object implementing the
load passengers operation must have the same semantics. For example, if you define a load
passengers method for a cruise ship such that it means get the passengers drunk, then this is
not polymorphic in meaning with other methods that may mean get the passengers aboard.
Polymorphic Methods Must Have the Same Signature
Polymorphic methods must have the same signature; in other words, the arguments that are
passed into the method, and the value that is returned, must be consistent in all the polymorphic
methods.
Oracle10g: Java Programming 2-26
Copyright 2004, Oracle. All rights reserved.
Architecture Rules for Reuse
Write code that contains:
Events that can interact with your Java application
Properties that can be exposed
Methods that can be invoked
Write code that supports:
Introspection or reflection
Customization
Persistence
Using a Standard Protocol
Good Java code must adhere to standards. JavaBeans are an example of the type of standards you
can incorporate into your code. A JavaBean is simply a Java class that obeys a strict protocol and
usually consists of a group of support classes and resource files, which are packaged into an
archive file. Consider a JavaBean as a black box, where all you need to know is the functionality
of the box, and not the functionality of its contents. Individual JavaBeans will vary in the
functionality that they support, but the typical features of the unifying architecture that
distinguish a JavaBean are support for:
Events, as a simple communication metaphor than can be used to connect beans
Properties, both for customization and for programmatic use
Public methods to be fired by an event
Introspection and reflection, so that at design time, a builder tool can analyze how a bean
works. Introspection and reflection enable a Java class to dynamically determine the basic
structure of the bean through its public interface definitions. This depends on the bean
having been written by using a structured coding pattern.
Customization, so that when using an application builder a user can customize the
appearance and behavior of a bean
Persistence, so that a bean can be customized in an application builder and then have the
state of its customized objects saved and reloaded later, using serialization
Oracle10g: Java Programming 2-27
Copyright 2004, Oracle. All rights reserved.
Engineering for a Black Box Environment
JavaBeans follow the black box approach which
enables you to:
Simplify something of arbitrary complexity down
to a single object that everyone can understand
Think of large systems as a collection of
interconnected entities (black boxes)
communicating via their interfaces
Leveraging the Black Box
By thinking of large systems as communication networks by using black boxes, you can see how
this approach enables you to control the systems complexity by ignoring the details of the
system that resides in the black box. Then, by organizing the connections between the black
boxes in a hierarchical way, you can more easily design a system that will be flexible and easy to
conceptualize.
JavaBeans is a great example in support of black box engineering. A set of standards is used such
that everything the designer needs to know about how an object operates is available within the
class.
Oracle10g: Java Programming 2-28
Copyright 2004, Oracle. All rights reserved.
Order Entry UML Diagram
UML in Oracle JDeveloper 10g
This diagram of the course classes was created by using JDeveloper.
The italic class Product is an abstract class, and the lavendar class Taxable is an interface. The
solid line with an arrow is a Generalization and is used for all dependencies between sub- and
super-types, and generates an extends statement in the class. A generalization is the
relationship between a more specific element and a less specific element, and defines the
inheritance structure in the model. Generalization relationships can be created between two Java
classes, between two Java interfaces or between two entity objects.
The dotted line with the arrow represents a Realization, and is used between an interface and a
class, and generates an implements statement in the class. A realization relationship identifies
which Java class, or classes, implements a Java interface.
The solid line with no arrow is an association, which signifies a call or a reference from one class
to another. The type of relationship between OrderItem and Order is composition.
The Plus (+) next to attributes means that they are public. The - means that they are private.
Oracle10g: Java Programming 2-29
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
An object is an abstraction of a real-world object.
A class is a template or blueprint for objects.
Classes form inheritance trees: Operations that
are defined in one class are inherited by all
subclasses.
Polymorphism frees the caller from knowing the
class of the receiving object.
Oracle10g: Java Programming 2-30
Copyright 2004, Oracle. All rights reserved.
Practice 2: Overview
This practice covers:
Identifying business objects for the Order Entry
system
Identifying methods for the classes
Identifying attributes for the classes
Searching for inheritance in the classes
Examining UML class model for course
application
Oracle10g: Java Programming 2-31
Practice 2: Working with Object-Oriented Principles
Goal
The goal of this practice is to become familiar with object-oriented concepts, including classes,
methods, and attributes. You also learn how to read a UML class model showing the business
objects for the course application.
A description of the business rules contains information to enable you to determine the classes,
methods, attributes, and associations that make up objects in the system. At the end of the
practice, you will have created a design model that includes the major classes in the business.
The aim is to create a simple UML class model to show these objects.
Note that a model is a representation of something, and is subject to interpretation. Remember
that no model is basically wrongbut some models are more usable than others.
Description of the Order Entry Area of the Business
The Order Entry component of the business is now becoming automated. In most respects, the
process of ordering products is rather simple. The customers select the items that they want from
a list of products. Your customers must be included in your system.You keep information about
your customers such as name, address, and telephone number. You also assign a unique
customer ID to each new customer. For customers that are companies, you track a contact person
and provide for a discount on company purchases. You identify individual customers by their
license number.
The order is not very complicated. Each order has a unique number that you can use to keep
track of it and has information such as the customer who is responsible for the order, the order
date, shipping mode (air or ground), and an order status. Each order can have multiple line items.
You currently limit your customers to 10 items per order. Each item on an order has the product
being purchased, the price, quantity, and the product category. A product category can be a
composite category consisting of additional categories, or a leaf category.
You track many things about your products, and the key things include the name, description,
and list price. Additionally, you want to include a warranty period, the supplier who distributes
the product, a catalog URL to reference it on the Web, and a weight classification that is used
when you calculate shipping costs. It is important for you to also track information about the
products that are available, and where they are located. You have many warehouses to hold all
your products.
Oracle10g: Java Programming 2-32
Practice 2: Working with Object-Oriented Principles (continued)
Understanding Object-Oriented Principles
1. Define the following terms:
a. Class
b. Object
c. Encapsulation
d. Inheritance
e. Polymorphism
Identifying Business Classes, Attributes, and Methods
2. Identify some of the classes in the Order Entry business, limiting yourself to three. The
process of identifying a class is to look for nouns that classify a group of things from the
business description. Some nouns will describe the attributes of a class. Write a simple
sentence or two describing each class to make sure that it is of interest to the business.
3. Identify a few attributes for each of the new classes. Remember that attributes may be other
classes.
4. Define some behaviors (methods or operations) for each of the classes that you have
discovered.
If you have time:
5. Look for classes that can inherit structure (attributes) and behavior (methods) from other
classes. Modify your definitions to reflect the inheritance model.
Oracle10g: Java Programming 2-33
Copyright 2004, Oracle. All rights reserved.
Order Entry System
Partial UML Class Model
Order
id: int
orderDate: Date
shipDate: Date
shipMode: String
orderTotal: double
addItem()
removeItem()
setOrderDate()
getOrderDate()
setShipDate()
:
OrderItem
lineNo: int
quantity: int
price: double
getQuantity()
setQuantity()
setPrice()
getPrice()
getItemTotal()
:
Customer
name: String
address: String
phone: String
getName()
setName()
setAddress()
getAddress()
:
Company
contact: String
discount: int
getContact()
setContact()
:
Individual
licNumber: String
setLicNumber()
getLicNumber()
:
Product
id: int
name: String
description: String
retailPrice: double
getPrice()
:
Copyright 2004, Oracle. All rights reserved.
Basic Java Syntax and Coding
Conventions
Oracle10g: Java Programming 3-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Identify the key components of the Java language
Identify the three top-level constructs in a Java
program
Identify and describe Java packages
Describe basic language syntax and identify Java
keywords
Identify the basic constructs of a Java program
Compile and run a Java application
Examine the JavaBean architecture as an example
of standard coding practices
Use the CLASSPATH variable and understand its
importance during compile and run time
Lesson Aim
This lesson introduces the basic constructs of the Java language. You learn conventions,
standards (that is, capitalization, spacing, and so on), compiling, and running applications.
You become familiar with the basic language constructs so that you can recognize and
manipulate them with or without using Oracle JDeveloper. The lesson explores JavaBeans as
an example of good coding practices.
Oracle10g: Java Programming 3-3
Lesson Aim (continued)
Overview
Java Components
The Java environment is made up of a run-time engine, documentation tools, debugging
utilities, and predefined classes and methods that are designed to decrease development time.
Conventions
When programming in Java, you must use established naming, capitalization, indenting, and
commenting conventions.
Classes, Objects, and Methods
In Java, almost everything is an object. Objects are created from blueprints called classes. The
objects contain attributes (data) that can be accessed by functions that are contained within the
object. Functions that act on the data are called methods.
Using Javadoc
Javadoc is a facility that is provided within J2SE and produces HTML documentation from
your program. It reads the source code and parses specially formatted and positioned
comments into documentation.
Compiling and Running Java
Java is an interpretive language, which means that the code is interpreted to machine code
only at run time. This is what makes the write once, run anywhere (WORA) concept work.
There are several steps in the process of interpreting program source code into a running
program. Java code is first compiled into bytecodes by the Java compiler. Bytecodes are
interpretable, intermediate representation of the Java program. The resulting bytecodes are
interpreted and converted into machine-specific instructions by the Java Virtual Machine
(JVM) at run time.
Security Concerns
Using the jad.exe, you can make the code so confused or opaque as to be difficult to
perceive or understand. Obfuscation of your code can make field debugging more difficult.
For example, stack traces are often very useful in isolating bugs. After compression or
obfuscation by one of these tools, however, the stack trace may no longer contain the original
method names. In general, refrain from using obfuscation, unless you really want to make it
difficult to modify your code.
Oracle10g: Java Programming 3-4
Copyright 2004, Oracle. All rights reserved.
Examining Toolkit Components
The J2SE/J2EE from Sun provides:
Compiler
Bytecode interpreter
Documentation generator
J2SE
Examining Toolkit Components
Sun J2SE Components
The Java compiler is javac; it compiles Java source code into Java bytecodes.
The Java bytecode interpreter is the engine that runs Java applications.
The program that generates documentation in HTML from Java source code comments
is javadoc.
Other J2SE Tools
jdb : Used as a Java class debugger and it is similar to the dbx or gdb debuggers on
UNIX
jar : Used to create Java Archive (JAR) files, which are zipped Java programs
javah : Used to generate C files for native methods
javakey : Provides support for generating certification keys for trusted Java code
javap : Used to disassemble Java bytecodes into human-readable format
native2ascii : Used to convert Java source code to Latin 1 characters
Oracle10g: Java Programming 3-5
Copyright 2004, Oracle. All rights reserved.
Exploring Packages in J2SE/J2EE
The J2SE/J2EE from Sun provides standard packages
for:
Language
Windowing
Input/output
Network communication
J2SE
Java Packages
The Java language includes a series of classes that are organized into packages, depending on
functional groups. For example, there is a set of classes that helps create and use network
connections; these classes are contained in the java.net package. The basic package for
the Java language is named classes.zip in 1.1.x and is renamed rt.jar since 1.2.x.
Standard Java Packages
These packages contain the classes that form the foundation for all Java applications.
Built-in Classes That Are Distributed with Java Language
java.lang: Basic language functions
javax.swing: Parent package to all Swing-related packages
java.util: Facility supporting interfacing, implementing, sorting, and searching on
collections
java.awt: Utility to managing layout, handling events, and rendering graphics for
AWT
java.io: General interface for all I/O operations
Oracle10g: Java Programming 3-6
Copyright 2004, Oracle. All rights reserved.
Documenting Using the J2SE
The J2SE/J2EE from Sun provides documentation
support for:
Comments
Implementation
Documentation
Documentation generator
J2SE
Documentation
There are two types of documentation methods in Java that you can specify in your source
code. One is for the internal documentation, and the other is for external documentation.
Comments
Implementation comments are included in the source code. They are useful for
programmers who are examining the code. When writing implementation comments,
you must explain the code and any special processes that may need detailed
explanations. Use:
- // to start comments up to the end of the line
- /* to start comments across multiple lines, and end with */
Documentation comments are created using javadoc. Javadoc is a utility that is provided
with J2SE and that creates an HTML document from the documentation comments in
Java source code. You can use the javadoc utility to document classes and methods, so
that they can be better understood when used by other programmers. Use:
- /** to start documentation comments across multiple lines, and end with */
Documentation Generator
Javadoc is a documentation generator that is part of J2SE.
Oracle10g: Java Programming 3-7
Copyright 2004, Oracle. All rights reserved.
Contents of a Java Source
A Java source file can contain three top-level
constructs:
Only one package keyword followed by the package
name, per file
Zero or more import statements followed by fully
qualified class names or * qualified by a package
name
One or more class or interface definitions
followed by a name and block
File name must have the same name as the public
class or public interface.
RentalItem.java
package practice16; // collection of classes of similar
functionality
import java.util.*; // import for Date class
public class RentalItem {
private InventoryItem inventoryItem;
private String dueDate;
private Date dateReturned;
public RentalItem(int aInventoryItemId) {
try {
inventoryItem =
DataMan.fetchInventoryItemById(aInventoryItemId);
}
catch (ItemNotFound e2) {
System.out.println("Invalid Item ID");
}
dueDate = calcDueDate();
} // end constructor
Oracle10g: Java Programming 3-8
Copyright 2004, Oracle. All rights reserved.
Establishing Naming Conventions
Naming conventions include:
Class names
Customer, RentalItem, InventoryItem
File names
Customer.java, RentalItem.java
Method names
getCustomerName(), setRentalItemPrice()
Package names
oracle.xml.xsql, java.awt, java.io
Naming Conventions
File Names
Java source code is stored in files with the .java extension. Use the name of the class held
within the file as the file name. Remember that Java is case sensitive, and the names must
match exactly, including case. Compiled Java code, or bytecodes, is stored in files with the
.class extension.
The name of the Java source file must be the name of the public class in the file; otherwise,
the code will not compile. You may have source code for more than one class in the file, but
only one can be public, and the file name must be the same name as the public class.
Class Names
Use descriptive nouns or noun phrases for class names. Capitalize the first letter of each word
in the class name, including the first word (for example, MyFirstClassName).
Oracle10g: Java Programming 3-9
Naming Conventions (continued)
Method Names
Use verbs or verb clauses for method names. Make the first letter of the method name
lowercase with the first letter of each internal word capitalized (for example,
getSomeInformation() ).
Packages
The Java documentation states that package names must nearly always be in lowercase, and
resemble a reverse notation of a Domain name. For example, when Oracle Corporation
develops class libraries, package names begin with oracle. followed by a descriptive
name. The naming convention ensures that a package name is unique to avoid clashing when
using APIs from multiple vendors in the same application.
Oracle10g: Java Programming 3-10
Copyright 2004, Oracle. All rights reserved.
More About Naming Conventions
Variables:
customerName, customerCreditLimit
Constants:
MIN_WIDTH, MAX_NUMBER_OF_ITEMS
Uppercase and lowercase characters
Numerics and special characters
Naming Conventions (continued)
Variables
Use short, meaningful names for variables. Use mixed-case letters with the first letter
lowercase and begin all internal words with uppercase letters (for example, int
squareFootage). Choose names that indicate the intended use of the variable. Avoid using
single-character variable names except for temporary variables. Common names for
temporary variables are c, d, and e for character fields and i, j, k, m, and n for integers.
String customerName; // string variable
int customerCreditLimit; // integer variable
Constants
Declare constants with descriptive names in all uppercase. Separate internal words with
underscores (for example, int MIN_WIDTH).
Oracle10g: Java Programming 3-11
Naming Conventions (continued)
Uppercase and Lowercase
Java is case sensitive. You must adopt and follow a strict capitalization scheme. The scheme
that is presented above is a generally accepted practice.
Numerics and Special Characters
Numbers, underscores, and dollar signs may be used for names in addition to uppercase and
lowercase letters. The only syntactic restriction is that identifiers must not begin with a
number. This rule prevents them from being confused with numeric literals. Underscores are
not generally used except for private and local variables.
Oracle10g: Java Programming 3-12
Copyright 2004, Oracle. All rights reserved.
Defining a Class
Class definitions typically include:
Access modifier
Class keyword
Instance fields
Constructors
Instance methods
Class fields
Class methods
Class Definition
A class is an encapsulated collection of data and methods to operate on the data. A class
definition, data and methods, serves as a blueprint that is used in the creation of new objects
of that class.
A class definition typically consists of:
Access modifier: Specifies the availability of the class from other classes
Class keyword: Indicates to Java that the following code block defines a class
Instance fields: Contain variables and constants that are used by objects of the class
Constructors: Are methods having the same name as the class, which are used to
control the initial state of any class object that is created
Instance methods: Define the functions that can act upon data in this class
Class fields: Contain variables and constants that belong to the class and are shared by
all objects of that class
Class methods: Are methods that are used to control the values of class fields
The order of the fields, constructors, and methods does not matter in Java. Ordering the parts
of a Java program consistently will, however, make your code easier to use, debug, and share.
The order listed in the slide is generally accepted.
Oracle10g: Java Programming 3-13
Copyright 2004, Oracle. All rights reserved.
Rental Class: Example
public class Rental {
//Class variable
static int lateFee;
// Instance variables
int rentalId;
String rentalDate;
float rentalAmountDue;

// Instance methods
float getAmountDue (int rentId) {

}

}
Declaration
Instance
variable
Instance
method
Access modifier
Rental Class: Example
This slide shows the syntax of a class definition. Every Java program needs at least one class
definition, even if the class contains only a static main() method.
The First Line
The class definition usually starts with the public access modifier. If you omit the public
modifier, then the class is visible only to other classes within the same package. The access
modifier is followed by the class keyword, followed by the class body enclosed in braces.
Instance Variables
The class body contains declarations of instance variables and instance methods. Instance
variables constitute the state of an object. Instance variables are usually declared private;
if no access level is specified, then they can be accessed by any class in the same package.
The access modifier is followed by the class keyword, followed by the class name then the
class body enclosed in braces.
Oracle10g: Java Programming 3-14
Rental Class: Example (continued)
Instance Methods
Instance methods define the operations that can be performed on objects of this class type.
Each instance method has a name, an optional list of arguments, and a return type. If no
access level is specified, then instance methods can be accessed by any class in the same
package.
Class Variables and Class Methods
Class fields and class methods are defined by using the static keyword.
Oracle10g: Java Programming 3-15
Copyright 2004, Oracle. All rights reserved.
Creating Code Blocks
Enclose all class declarations.
Enclose all method declarations.
Group other related code segments.
public class SayHello {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Code Blocks
Enclose class declarations within braces { }. The class declaration contains variables,
constants, and methods. The class body must begin on a new line following the class
declaration and the opening brace. Indicate the end of the class declaration by a single closing
brace on a new line. There is another coding convention, which puts the opening brace on the
next line even with the closing brace from the previous statement.
Method declarations follow the same form with the opening brace on the same line as the
method definition and the closing brace on a new line. All statements and declarations within
the braces are part of the method.
You can also group code segments within a method declaration by using braces. Grouping
enhances the readability of your code. The easier it is to read and follow your code, the easier
it will be to debug and reuse.
Variables that are defined within a code block are available during the execution of that code
block and are discarded at the completion of execution.
main() Method
The interpreter looks for a specific method to start the program, and that method is called
main(). It is simply the starting place for the interpreter to begin. Only one class will need to
have a main method to get things started. You only need a main method for an application. If
you are writing an applet, then the main method is not needed, because the browser has its
own way to start or bootstrap the program.
Oracle10g: Java Programming 3-16
Copyright 2004, Oracle. All rights reserved.
Defining Java Methods
Always define within a class.
Specify:
Access modifier
Static keyword
Arguments
Return type
[access-modifiers] [static] "return-type"
"method-name" ([arguments]) {
"java code block }
return
Method Definition
When you define a class for an object-oriented program, you implement all the behavior of
that class in one or more methods. A Java method is equivalent to a function, procedure, or
subroutine in other languages, except that it must be defined within a class definition.
Methods consist of the following:
Access modifier: You can specify a method as either public, private, or protected.
Public methods can be known and used by external users, whereas private methods can
be seen or used only by methods within the class. Protected methods are accessible from
any class that extends or inherits from the class.
Static keyword: Variables and methods are usually accessed for a particular object. If
the method or variable is defined with the static keyword, then it becomes a class
method or variable, which means that it applies to the class of objects as a whole and not
as individual objects. Static variables are shared by all objects of that class.
Arguments: The arguments that are listed for a method are those parameters that are
required for the method to perform its function.
Return type: A return type is required for all method definitions. There is no default
return type in Java. The return type specifies the object type that will be returned when
the method has completed its task. It can be an integer, a string, any defined object type,
or void.
Oracle10g: Java Programming 3-17
Copyright 2004, Oracle. All rights reserved.
Examples of a Method
public float getAmountDue (String cust){
// method variables
int numberOfDays;
float due;
float lateFee = 1.50F;
String customerName;
// method body
numberOfDays = getOverDueDays();
due = numberOfDays * lateFee;
customerName = getCustomerName(cust);
return due;
}
Declaration
Method
variables
Method
statements
Return
Method Example
Declaration
In this example, the defined method returns a float primitive type. The method name is
declared as getAmountDue. The method name begins with a lowercase letter with the
beginning letter of each subsequent word in uppercase letters. The next item is the declaration
of the expected parameter list. The parameter list consists of the argument data type and
argument name.
Method Variables
The next set of statements defines any method-specific variables. These variables are used
only during the execution of the method and are discarded when control is passed back to the
object that called this method. The float data type is used for real numbers (numbers with
decimal points).
Method Statements
The executable body of the method comes next. This section contains the Java statements that
are used to act upon data. It can include conditional statements, data manipulation operations,
or any other valid Java statements.
Return
The return statement accomplishes two things. The return causes the execution to branch back
to the caller of the method, and then it passes back the specified value, if there is one.
Oracle10g: Java Programming 3-18
Copyright 2004, Oracle. All rights reserved.
Declaring Variables
You can declare variables anywhere in a class
block, and outside any method.
You must declare variables before they are used
inside a method.
It is typical to declare variables at the beginning of
a class block.
The scope or visibility of variables is determined
in the code block.
You must initialize method variables before using
them.
Class and instance variables are automatically
initialized.
Declaring Variables
Declaration
Java requires that variables be declared before they can be accessed. Declare variables and
constants by placing each statement on a separate line, so that the code is clear and easy to
understand. You can declare multiple variables of the same type within one statement.
Scope
If variables or constants are required only within a code block, then declare them at the top of
the code block. Variables that are defined within a code block will be discarded when the
execution of the code block is complete. This is useful for temporary variables or those
needed to hold specific information during a calculation or process. After the process is
complete, they are no longer needed.
Initialization
Whenever possible, initialize variables at declaration. This provides some insight into the use
or purpose of the variable. The only reason for not initializing at declaration is if the value is
dependent on a calculation that is not yet performed.
When you declare primitive instances or class variables, they are automatically initialized to a
default value depending on their type.
Oracle10g: Java Programming 3-19
Copyright 2004, Oracle. All rights reserved.
Examples of Variables
in the Context of a Method
public float getAmountDue (String cust) {
float due = 0;
int numberOfDays = 0;
float lateFee = 1.50F;
{int tempCount = 1; // new code block
due = numberOfDays * lateFee;
tempCount++;

} // end code block
return due;
}
Method
variables
Temporary
variables
Examples of Variables in the Context of a Method
Method Variables
In this example, the numberOfDays and lateFee variables are defined at the beginning
of the method. Both of these variables are method variables; that is, they are used while the
method is being executed and are discarded at the return of execution control to the caller.
Temporary Variables
The tempCount variable is defined within a subblock of the getAmountDue method. The
tempCount variable is available only during the execution of this block of code. When the
block of code is complete, the variable is discarded, whether or not the method maintains
execution control.
Oracle10g: Java Programming 3-20
Copyright 2004, Oracle. All rights reserved.
Rules for Creating Statements
Use a semicolon to terminate statements.
Define multiple statements within braces.
Use braces for control statements.
Statements
Java statements cause some action to occur, such as setting a value, sending output, reading a
database, and so on. They always end with a semicolon. Compound statements are a list of
related statements that are contained within a set of braces. Indent the statements one level
below the enclosing statement for clarity. Place the opening brace on the line that begins the
compound statement. Place the closing brace on a separate line, indented to the correct level.
Use braces around all statements when they are part of a control (if-else) structure.
public float getAmountDue (String cust) {
float due = 0;
int numberOfDays = 0;
float lateFee = 1.50F;
If () { {int tempCount = 1; // new code block
due = numberOfDays * lateFee;
tempCount++; //nested compound statement
}
// end code block
} //end if
return due;
}
Oracle10g: Java Programming 3-21
Copyright 2004, Oracle. All rights reserved.
What Are JavaBeans?
A JavaBean is a platform-neutral reusable software
component that:
Can be manipulated visually in a builder tool
Communicates with other JavaBeans via events
Comprises visible components that must inherit
from other visible components
Provides an architecture for constructing the
building blocks of an application
About JavaBeans
A JavaBean is a reusable platform-independent software component that can be manipulated
visually in a builder tool such as JDeveloper. The JavaBeans standard is a low-level
component model, tailored to the Java language. It does not specify the kind of component
document or application framework such as CORBA, OpenDOC, or Taligent). JavaBeans
focuses purely on the interface that a Java building block must represent.
A JavaBean consists of a single class or a group of classes. At a minimum, a bean must have a
public class declaration and a no-parameter constructor. Any classes can be part of a bean.
There is no specific superclass that a bean must extendunlike, for example, an applet, which
must extend the Applet class. However, a JavaBean must conform to certain basic architecture
rules.
Beans are not a special type of component. A bit of Java code does not have a special bean
type or label that makes it a bean. A JavaBean has a set of criteria that makes it flexible and
reusable to others. It is not about, for example, different types of coffee, such as French Roast
or Columbian. Rather, it is about the packaging of the coffee meat so that it can be used as a
bean in a variety of environments (for example, used in a grinder for a beverage or covered in
chocolate as an after-dinner treat).
Oracle10g: Java Programming 3-22
Copyright 2004, Oracle. All rights reserved.
Managing Bean Properties
Properties are the bean class member variables.
(Variables can be primitive types or objects.)
A property can be:
Unbound, which is a simple property
Bound, which triggers an event when the field is
altered
Constrained, in which changes are accepted or
vetoed by interested listener objects
Properties
Properties are the bean variables. They can be of any Java data type; that is, primitives or
objects. In the context of a bean, variables or properties can have a binding that is stated as
any of the following:
Unbound: Unbound properties are simple properties that are accessed or modified by
using the associated get and set methods.
Bound: Bound properties are like simple properties, but when modified by using the set
method they trigger the PropertyChangeEvent event. The
PropertyChangeEvent object contains the old value and new value of the
property, so that listeners can react appropriately to the change. For example, changing
the connection property of a JClient SessionInfo object fires an event that redraws
JDevelopers structure pane.
Constrained: Constrained properties are an extension to bound properties, in that they
generate a PropertyChangeEvent when the property is modified, but the listeners
handling the event can veto (prevent) the change by throwing
PropertyVetoException if the change violates some rule or constraint. For
example, resizing a visual component can be vetoed by other components based on
layout management rules. The differentiating characteristic between bound and
constrained is what occurs when their property values are altered.
Oracle10g: Java Programming 3-23
Copyright 2004, Oracle. All rights reserved.
Exposing Properties and Methods
Getter
methods
(public)
Setter
methods
(public void)
T getVar()
T[] getArr()
boolean isVar()
setVar(T val)
setArr(T[] val)
setVar(boolean val)
private
T var;
T[] arr;
Property and Method Naming Conventions
Good naming conventions apply to the methods that an application calls to access and alter
the properties of a class. In JavaBean classes, the name of the set and get methods are
formed from the prefix get or set, followed by the uppercased name of the property or
variable that is accessed.
The properties are commonly declared private, forcing users to invoke the access methods
to interact with the bean. The following is an example of a String property and its
corresponding setter and getter methods:
private String text;
public String getText() { return text };
public void setText(String newtext) { text = newtext; }
Note: The property name starts with a lowercase letter, but the method names are setText
and getText, (using the uppercased form of the property name). The return type of the
getter method, and the single argument of the setter method must be the same type as the
property. For indexed properties, such as arrays, it is common to provide two additional
methods to get and set a value at a specified index, for example:
private String[] name;
public String[] getName() {...} ;
public void setName(String[] values) {...};
public String getName(int index) {...};
public void setName(int index, String value) {...};
Oracle10g: Java Programming 3-24
Copyright 2004, Oracle. All rights reserved.
JavaBean Standards at Design Time
The benefits at design time include:
A facilitated interaction between designer, tool,
and bean
Instantiated and functioning beans in a visual tool
Highly iterative development environment
Building applications in small bits that plug in and
out
Storage and recovery of instantiated
objects
Benefits of JavaBeans Standards During Design
The JavaBeans architecture makes the bean easier to use during the design phase. At design
time, the JavaBean is alive or hot, and exhibits all the behavior found in the deployed
application. A JavaBean displaying the time, when included in an application, will start
ticking away as soon as it has been placed into the application. The designer can see how the
application will behave, as its application is being built, rather than after compiling. This
pseudo-live functionality of JavaBeans facilitates a more iterative approach, with the
developer building small bits while getting immediate feedback. The system evolves more
easily.
For JavaBeans to be running during design time, the bean must adhere to a set of standards
and protocols that describe how they work. If the protocol is followed, a visual development
tool can interrogate the bean structure, understand its interactions, and present them to the
developer.
All instantiated objects, present at design time, are serialized with the design and, when
recovered, retain their values, making them persistent. This functionality is supported through
a tools Load, Save, Copy, Cut, and Paste functions.
Oracle10g: Java Programming 3-25
Copyright 2004, Oracle. All rights reserved.
Compiling and Running
a Java Application
To compile a .java file:
To execute a .class file:
Remember that case matters.
prompt> javac SayHello.java
compiler output
prompt> java SayHello
Hello world
prompt>
Java Development Kit (JDK) Tools
J2SE includes javac.exe and java.exe, two executables for compiling and executing a
Java program.
Compiling Java Code
Run javac.exe from the command prompt to compile .java files into .class files. For
example, to compile SayHello.java into a bytecodes file named SayHello.class,
enter the following at the command prompt:
javac SayHello.java
Running a Java Application from the Command Line
The java.exe executable loads the class, verifies the bytecodes, interprets it into machine
language, and executes the code. Start the interpreter by entering the following command at
the command prompt:
java SayHello
This starts JVM, which loads SayHello.class and tries to call its main() method. JVM
expects the SayHello.class to have a main() method, where the program execution
will start. If SayHello.class calls methods in other classes, then JVM loads these other
classes only when they are required.
Oracle10g: Java Programming 3-26
Copyright 2004, Oracle. All rights reserved.
The CLASSPATH Variable
Is defined in the operating system
Directs the JVM and Java applications where to
find .class files
References built-in libraries or user-defined
libraries
Enables interpreter to search paths, and loads
built-in classes before user-defined classes
Can be used with javac and java commands
Setting the CLASSPATH
If the CLASSPATH variable is not set, then a default is used. The default includes the absolute
path to the jdk1.4.2_03\bin, \lib\, and \classes\ directories, which house
the J2SE packages (contained in the rt.jar file). You can create a /classes/ directory,
add your class files, and CLASSPATH will find them.
CLASSPATH examines individual class files, or those stored in .zip or .jar files. Set the
CLASSPATH variable by using the commands: setenv in UNIX (in a C-Shell), and set in
NT. Separate directories with a semicolon ; (for example,
c:\myClasses;d:\myOtherClasses). Set CLASSPATH to include the directory
containing the .class files.
The interpreter looks for classes in the directory sequence as they are found in the
CLASSPATH variable. If the interpreter cannot find the named class in the first directory, then
it searches the second and all the others in the list.
If you want the CLASSPATH to point to class files that belong to a package, then you must
specify a path name that includes the path to the directory one level above the directory that
has the name of your package.
You can override the CLASSPATH setting in the javac and java commands, by using the
classpath option.
Oracle10g: Java Programming 3-27
Copyright 2004, Oracle. All rights reserved.
CLASSPATH: Example
C:\>set CLASSPATH=D:labs\les03\classes\oe
Setting CLASSPATH
Location of .class files in the oe package
Oracle10g: Java Programming 3-28
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
J2SE provides basic Java tools.
J2SE provides a rich set of predefined classes and
methods.
Java programs are made up of classes, objects,
and methods.
Adhering to programming standards makes code
easier to read and reuse.
Oracle10g: Java Programming 3-29
Copyright 2004, Oracle. All rights reserved.
Practice 3: Overview
This practice covers:
Examining the Java environment
Writing and running a simple Java application
Examining the course solution application
Inspecting classes, methods, and variables
Creating class files and an application class with a
main( ) method
Compiling and running an application
Practice 3: Overview
Note: If you close a DOS window or change the location of the .class files, then you must
modify the CLASSPATH variable.
The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and
structure of the Java language. Their sole purpose is to instruct and is not intended to reflect
any set of application development best practices.
The purpose of the practices from lesson 6 to the end of the course, is different. Starting in
lesson 6, you use JDeveloper to build an application employing techniques you will use
during real-world development. The practices continue to support the technical material
presented in the lesson, while incorporating some best practices that you will use while
developing a Java application.
Oracle10g: Java Programming 3-30
Practice 3-1: Introducing the Java and Oracle Platforms
Goal
The goal of this practice is to use the Java Development Kit and examine the development
environment. You write, compile, and run a simple Java application.
Note: If you close a DOS window or change the location of the .class files, then you must
set the CLASSPATH variable again.
The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and
structure of the Java language. Their sole purpose is to instruct and is not intended to reflect
any set of application development best practices.
Edit and Run a Simple Java Application
1. Open a DOS window and navigate to the E:\labs\temp directory and create a file
called HelloWorld.java by using Notepad with the following commands:
E:
cd \labs\temp
notepad HelloWorld.java
2. In Notepad, enter the following code, placing your name in the comments (after the
double slashes). Also, make sure that the case of the code text after the
comments is preserved, because Java is case sensitive:
// File: HelloWorld.java
// Author: <Enter Your Name>
public class HelloWorld {
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
3. Save the file to the E:\labs\temp directory, using the File > Save menu option, but
keep Notepad running, in case compilation errors occur requiring you to edit the source
to make corrections.
4. Compile the HelloWorld.java file (file name capitalization is important)
a. In the DOS window, ensure that the current directory is E:\labs\temp.
b. Check whether the Java source file is saved to disk.
(Hint: Type the command dir Hello*. )
c. Compile the file by using the command: javac HelloWorld.java
d. Name the file that is created if you successfully compiled the code.
(Hint: Type the command dir Hello*. )
Oracle10g: Java Programming 3-31
Practice 3-1: Introducing the Java and Oracle Platforms (continued)
5. Run the HelloWorld application (again capitalization is important).
a. Run the file by using the command: java HelloWorld
b. What was displayed in the DOS window?
6. Modify the CLASSPATH session variable to use the directory where the .class file is
stored. In the DOS window, use the set CLASSPATH=E:\labs\temp command to
set the variable. The variable will be set for the duration of the DOS session. If you open
another DOS window, you must set the CLASSPATH variable, again.
7. Again, run the HelloWorld application (capitalization is important).
a. Run the file by using the command: java HelloWorld
b. What was displayed in the DOS window?
8. Close Notepad, but do not exit the DOS window, because you continue to work with this
environment for some time.
Oracle10g: Java Programming 3-32
Practice 3-2: Basic Java Syntax and Coding Conventions
Goal
The goal of this practice is to create, examine, and understand Java code. You create a class
representing a command-line application for the Order Entry system that contains the
application entry point in the form of a main() method.
You use the UML model from the lesson titled Defining Object-Oriented Principles as a
guide to creating additional class files for your application. You run some simple Java
applications, fixing any errors that occur.
Creating Order Entry Class Files (Examining the Customer Class)
Using the UML model from the lesson titled Defining Object-Oriented Principles, create
class files to be used in the application.
1. Copy the Customer.java file from the e:\labs directory to your
E:\labs\OrderEntry\src\oe directory.
2. In the DOS window, change your current working directory to:
E:\labs\OrderEntry\src\oe
3. Using Notepad, review the Customer class and answer these questions:
a. Name all the instance variables in Customer.
b. How many instance methods are there in Customer?
c. What is the return type of the method that sets the customers name?
d. What is the access modifier for the class?
4. Close the file, and at the DOS prompt compile the Customer.java file by using the
following command as a guide:
javac -d E:\labs\OrderEntry\classes Customer.java
Where is the compiled .class file created?
(Hint: Type cd ..\..\classes\oe, and then type dir.)
Incorporate the Order.java into Your Application Files
5. Add the Order.java file to your application structure, review the code and compile it.
a. In Notepad, open the \labs\Order.java file and save it to the directory for
your OE package source code (E:\labs\OrderEntry\src\oe).
b. The attributes are different from those in the UML model. The customer and item
information will be incorporated later.
c. Notice two additional attributes (getters and setters) have been added.
shipmode (String): Used to calculate shipping costs
status (String): Used to determine the orders place in the order fulfillment
process
d. Ensure that you are in the E:\labs\OrderEntry\src\oe directory. Use the
following command to compile the Order.java file which will place the
.class file in the directory with the compiled version of the Customer class:
javac d E:\labs\OrderEntry\classes Order.java
Oracle10g: Java Programming 3-33
Practice 3-2: Basic Java Syntax and Coding Conventions (continued)
Create and Compile the Application Class with a main() Method
6. Create a file called OrderEntry.java containing the main method, as shown below.
Place the source file in the same source directory as all the other java files
(E:\labs\OrderEntry\src\oe). This file is a skeleton that will be used for
launching the course application.
package oe;
public class OrderEntry {
public static void main(String[] args)
{
System.out.println("Order Entry Application");
}
}
7. Save and compile OrderEntry.java with the following command line:
javac -d E:\labs\OrderEntry\classes OrderEntry.java
8. Run the OrderEntry application.
a. Open a DOS window and use the cd command to change the directory to:
E:\labs\OrderEntry\classes
b. Run the file by using the command: java oe.OrderEntry
Copyright 2004, Oracle. All rights reserved.
Exploring Primitive Data Types
and Operators
Oracle10g: Java Programming 4-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Distinguish between reserved words and other
names in Java
Describe Java primitive data types and variables
Declare and initialize primitive variables
Use operators to manipulate primitive variables
Describe uses of literals and Java operators
Identify valid operator categories and operator
precedence
Use String object literals and the concatenation
operator
Lesson Aim
This lesson introduces Javas decision-making and repetition constructs. You learn how to
use those constructs to build nonlinear applications. Java provides eight primitive data types
and a large number of operators to manipulate these types. This lesson introduces the
primitive types and describes how to use the most common operators to construct simple
algorithms.
Oracle10g: Java Programming 4-3
Lesson Aim (continued)
Primitive Data Types in Java
Java is an object-oriented programming language, which means that a Java program is made
up of objects. For example, a Java program dealing with video rentals may have objects
representing the various videos and games that are available, the customers who have rented
videos, the numerous titles that are available, and so on.
If you take a look at one of these objects in more detail, however, you see that it contains
fundamental values such as whole numbers, fractions, and characters. Java provides eight
predefined data types to represent these atomic entities; the Java community calls these the
primitive types, as opposed to object types (user-defined types) that you may define
yourself, such as Customer or Title.
Declaring and Initializing Primitive Variables
Declaring primitive variables is quite straightforward. For example, to declare and initialize
an integer variable to hold the number of days that a video can be rented, you can write a
statement, such as the following:
int numOfDays = 3;
This lesson describes how to declare and initialize variables of each of the eight primitive
types.
Oracle10g: Java Programming 4-4
Copyright 2004, Oracle. All rights reserved.
Reserved Keywords
abstract
final
native
private
protected
public
static
synchronized
transient
volatile
strictfp
break
case
catch
continue
default
do
else
finally
for
if
return
switch
throw
try
while
boolean
byte
char
double
float
int
long
short
void
true
false
null
class
extends
implements
interface
throws
instanceof
new
super
this
import
package
Reserved Keywords in Java
All the words in this slide are keywords in the Java language. These reserved words must not
be used as variable names. There are 51 reserved words in Java2.
Additional Reserved Keywords
In addition to the keywords listed in the slide, const and goto are reserved and cannot be
used as identifiers.
Oracle10g: Java Programming 4-5
Copyright 2004, Oracle. All rights reserved.
Variable Types
Eight primitive data types:
Six numeric types
A character type
A Boolean type (for truth values)
User-defined types:
Classes
Interfaces
Arrays
a
b
c
Variable Types
Variables are the basic storage unit in Java. A variable is a symbolic name for a chunk of
memory. Variables can be defined to hold primitive values (which are not real objects in
Java) or to hold object references. The object references that they hold can be user-defined
classes or Java-defined classes.
Primitive Data Types
A variable declaration consists of a type and a name. Consider the following example:
double balanceDue;
This statement declares a variable called balanceDue, whose type is double. double
is one of the eight primitive data types that are provided in the Java language. These types
are called primitive because they are not objects and they are built into the Java language.
Unlike similar types in other languages, such as C and C++, the size and characteristics of
each primitive data type are defined by the Java language and are consistent across all
platforms.
Oracle10g: Java Programming 4-6
Variable Types (continued)
Classes, Interfaces, and Arrays
Classes, interfaces, and arrays are user-defined types with specific characteristics. After they
are defined, you can declare variables of the new type just as you declare primitive
variables.
Oracle10g: Java Programming 4-7
Copyright 2004, Oracle. All rights reserved.
Primitive Data Types
Append uppercase or lowercase L or F to the number
to specify a long or a float number.
Integer
Floating
Point
Character
True
False
byte
short
int
long
float
double
char boolean
1, 2, 3, 42
07
0xff
0
3.0F
.3337F
4.022E23
0.0f
'a' '\141'
'\u0061'
'\n'
\u0000
true
false
false
Primitive Data Types
Integer
Java provides four different integer types to accommodate different size numbers. All the
numeric types are signed, which means that they can hold positive or negative numbers.
The integer types have the following ranges:
byte range is 128 to +127. Number of bits = 8.
short range is 32,768 to +32,767. Number of bits = 16.
int range is 2,147,483,648 to +2,147,483,647; int is the most common integer
type. Number of bits = 32.
long range is 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. Number
of bits = 64.
Floating Point
The floating-point types hold numbers with a fractional part and conform to the IEEE 754
standard. There are two types: float and double. double is so called because it
provides double the precision of float. float uses 32 bits to store data, whereas
double uses 64 bits.
Oracle10g: Java Programming 4-8
Primitive Data Types (continued)
Character
The char type is used for individual characters, as opposed to a string of characters, which
is implemented as a String object. Java supports Unicode, an international standard for
representing a character in any written language in the world in a single 16-bit value. The
first 256 characters coincide with the ISO Latin 1 character set, part of which is ASCII.
Boolean
The boolean type can hold either true or false.
If a value is not specified, a default one is used. The values in red in the slide are the defaults
used. The default char value is null, represented as ?\u0000?, and the default value for
boolean is false.
Oracle10g: Java Programming 4-9
Copyright 2004, Oracle. All rights reserved.
What Are Variables?
A variable is a basic unit of storage.
Variables must be explicitly declared.
Each variable has a type, an identifier, and a
scope.
There are three types of variables: class, instance,
and method.
int myAge;
boolean isAMovie;
float maxItemCost = 17.98F;
Type
Identifier
Initial value
Title: Blue
Moon
What Is a Variable?
A variable is a symbolic name for a chunk of memory in which a value can be stored.
Because Java is a strongly typed language, all variables must be declared before they can be
used.
Variables also have a scope that determines where you can use the variable. Scope also
determines the life span of the variable. When a variable is defined within a method, the
variable is available only within the execution of the method. When the method ends, the
variable is released and is no longer accessible. When defining a variable with a local scope
use braces.
Variables can also be explicitly initialized; that is, given a default value.
Oracle10g: Java Programming 4-10
Copyright 2004, Oracle. All rights reserved.
Declaring Variables
Basic form of variable declaration:
type identifier [ = value];
Variables can be initialized when declared.
public static void main(String[] args) {
int itemsRented = 1;
float itemCost;
int i, j, k;
double interestRate;
}
Declaring Variables
As mentioned earlier, you must declare all variables before using them. The declaration
consists of the type, followed by the variable name. Do not forget to terminate the statement
with a semicolon. You can declare a variable anywhere within a block, although it is often
preferable to declare it at the start.
You can declare several variables in one statement. All the variables that are declared in one
statement must be of the same type, such as int, char, float, and so on. The syntax is as
follows:
int itemsRented, numOfDays, itemId;
Initializing Variables
You can declare and initialize a variable in the same statement by using the assignment
operator (=). Even though they are in the same statement, each variable is initialized
independently. Each variable needs its own assignment and value.
int itemsRented = 0, numOfDays, itemId = 0;
In this case, itemsRented and itemId are initialized, whereas numOfDays is not. The
compiler accepts this statement as valid.
Oracle10g: Java Programming 4-11
Copyright 2004, Oracle. All rights reserved.
Local Variables
Local variables are defined only within a method
or code block.
They must be initialized before their contents are
read or referenced.
class Rental {
private int instVar; // instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3; // local variable
}
}
What Is a Local Variable?
A local variable is one that is defined inside a method and can therefore be accessed only
inside that method. In contrast, a variable that is defined outside a method can be accessed
by any method in that class. Consider the following example:
class Rental {
private int memberId; // Use in any method in the class
public void addItem() {
float itemCost = 3.50F; // Accessible only in addItem()
int numOfDays = 3; // Accessible only in addItem()
}
}
Local Variables Must Be Assigned a Value Before They Can Be Used
A local variable that is declared inside a method must be given a value before it can be used
in an expression. If you use a local variable that has not been assigned a value, then the
compiler issues an error.
Local variables are also known as method variables or even method local variables. In this
course, they are referred to as local variables.
Oracle10g: Java Programming 4-12
Copyright 2004, Oracle. All rights reserved.
Defining Variable Names
Variable names must start with a letter of the
alphabet, an underscore, or a $ symbol.
Other characters may include digits.
Use meaningful names for variables, such as
customerFirstName and ageNextBirthday.
a item_Cost
itemCost _itemCost
item$Cost itemCost2
item#Cost item-Cost
item*Cost abstract
2itemCost
Rules for Legal Variable Names
A variable name must start with a letter of the alphabet, an underscore, or a dollar sign,
although most Java programmers avoid the use of underscores and dollar signs. Subsequent
characters can include the digits 0 through 9. Note that the Java language is case sensitive,
and so lowercase letters are different from uppercase letters.
There is a 64 K restriction on the length of variable names, and so it is recommended that
you choose meaningful names that combine several words. By convention, the first word
must be set in lowercase, and subsequent words must start with uppercase letters, such as
customerFirstName.
Examples of Illegal Variable Names
The variables in the box on the right in the slide are illegal for the following reasons:
item#Cost is illegal because # is not allowed.
item-cost is illegal because (minus sign, not underscore) is not allowed.
item*Cost is illegal because * is an operator.
abstract is illegal because abstract is a keyword.
2itemCost is illegal because it starts with a digit.
Oracle10g: Java Programming 4-13
Copyright 2004, Oracle. All rights reserved.
What Are Numeric Literals?
0 1 42 -23795 (decimal)
02 077 0123 (octal)
0x0 0x2a 0X1FF (hex)
365L 077L 0x1000L (long)
1.0 4.2 .47
1.22e19 4.61E-9
6.2f 6.21F
Integer literals
Floating-point
literals
Six types: byte, short, int, long, float, double
What Is a Literal?
Variables hold values, whereas literals are the values themselves.
float itemCost = 4.95F;
The variable is itemCost, and 4.95 is the literal. Literals can be used anywhere in a Java
program, just like a variable. The difference is that literals cannot be stored or held without
the use of variables.
Integer Literals
By default, integer literals are 32-bit signed numbers. Integer literals can be specified in
decimal, octal, or hexadecimal. When assigning values to a variable, do not use commas to
separate thousands. To specify a literal in decimal form, simply use a number (12317.98).
Literals with a leading zero are in octal form. Octal numbers are in base 8 and can contain
the digits 0 through 7. To specify a hexadecimal value, use a leading 0x or 0X. The valid
characters are 0 through 9 and A through F (which can be set in uppercase or lowercase).
Oracle10g: Java Programming 4-14
What Is a Literal? (continued)
Integer Literals (continued)
A long integer is a 64-bit type. It can hold a larger number than the 32-bit version (int).
Remember that the 32-bit version can hold up to 2,147,483,647. If you need to store or use a
number larger than that, then you must use a long integer. You can force any integer to be
treated as long by appending an uppercase or lowercase L.
Floating-Point Literals
Floating-point literals can be specified in standard format, such as 123.4, or in scientific
notation, such as 1.234e2. By default, floating-point literals are taken as double
precision. You can obtain single precision by appending an uppercase or lowercase F.
Oracle10g: Java Programming 4-15
Copyright 2004, Oracle. All rights reserved.
What Are Nonnumeric Literals?
true false
'a' '\n' '\t' '\077' '\u006F'
"Hello, world\n"
Boolean literals
String literals
Character literals
What Are Nonnumeric Literals?
Boolean Literals
A Boolean literal can be either true or false, which are Java keywords. Note that true
and false are not numeric values and cannot be converted to integers, or vice versa.
Character Literals
Character literals are normally printable characters that are enclosed in single quotation
marks, such as a, b, and c. To specify a nonprintable character, such as a new
line or a tab, you must specify either its octal or hexadecimal Unicode value, or use its
corresponding escape sequence. An escape sequence consists of the backslash character,
followed by another character.
Character Escape Sequence
New Line '\n'
Tab '\t'
Single quote '\''
Backslash '\\'
Unicode values '\u006F'


Oracle10g: Java Programming 4-16
What Are Nonnumeric Literals? (continued)
String Literals
String literals consist of any number of characters inside double quotation marks. String
literals are different from character literals in that the character primitive holds only one
character. String literals hold multiple characters and are delimited by double quotation
marks.
Oracle10g: Java Programming 4-17
Copyright 2004, Oracle. All rights reserved.
Guided Practice: Declaring Variables
Find the mistakes in this code and fix them:
byte sizeof = 200;
short mom = 43;
short hello mom;
int big = sizeof * sizeof * sizeof;
long bigger = big + big + big // ouch
double old = 78.0;
double new = 0.1;
boolean consequence = true;
boolean max = big > bigger;
char maine = "New England state";
char ming = 'd';
1
2
3
4
5
6
7
8
9
10
11
Problems That You May Encounter
This slide highlights some of the problems that you may encounter when declaring variables
in Java. Hopefully, you will never write code like this. The following lines are illegal:
Line 1
The problem here is that 200 may not be assigned to a byte because 200 is treated as an
int. The proper assignment is: byte b1 = (byte)200; in this case, b1 = 56.
Line 3
A token is needed between hello and mom, such as an assignment operator to copy the
value of mom into hello. It can be that both these variables are of the same type. In that
case, all that is missing is a comma.
Oracle10g: Java Programming 4-18
Problems That You May Encounter (continued)
Line 5
There is no statement terminator (;) at the end of the statement. The // ouch comment is
valid.
Line 7
This statement is illegal because new is a reserved word in Java.
Line 10
char variables can hold only a single character. Declare a String object instead:
String maine = "New England state";
The string literal is not a primitive, but is here for completeness of specifying literals that
Java allows. String is really an object, whose reference to the literal is copied to the variable
to which it is assigned.
Oracle10g: Java Programming 4-19
Copyright 2004, Oracle. All rights reserved.
What Are Operators?
Operators manipulate data and objects.
Operators take one or more arguments and
produce a value.
There are 44 different operators.
Some operators change the value of the operand.
Operators in Java
Operators are used to manipulate the values that are stored in variables; these variables can
be in expressions or they may contain literal values. Most programs that do anything do so
by manipulating data. To calculate the due date of a video rental, the program must take the
day that the video was rented and add some number of days. This is data manipulation. It is
hard to imagine a program that does not use and manipulate data in some way, with the
exception of raw queries of the database.
Java operators take one or more arguments, or operands, and produce a value. Java provides
44 different operators that manipulate data in one way or another. Some of those operators
are more complex than others, and some are used more often.
This lesson focuses on the more important operators.
Note: It is not possible to extend the functionality of the operators. For example, in C++,
you can define your own new meaning for the operator; in Java, you cannot do this.
However, the + sign in Java is actually the only overloaded operator in Java. It is used as
both an arithmetic addition operator and also for String concatenation.
Oracle10g: Java Programming 4-20
Copyright 2004, Oracle. All rights reserved.
Categorizing Operators
There are five types of operators:
Assignment
Arithmetic
Integer bitwise
Relational
Boolean
Operators
Operators are special characters that are used to instruct the Java compiler to perform an
operation on an operand. Java includes a set of 44 different operators. Most programs need
only part of the 44 distinct operators.
Assignment Operators
Assignment operators set the value of a variable to a literal value or the value of another
variable or expression.
Arithmetic Operators
Arithmetic operators perform mathematic computations on operands. Arithmetic operators
operate on all numeric types.
Integer Bitwise Operators
Bitwise operators are provided to inspect and modify the internal bits that make up integer
numeric types, whereas arithmetic operators modify the values of a variable as a whole unit.
Relational Operators
Relational operators compare two values. You can use relational comparison to set other
values or to control program flow.
Boolean Logical Operators
Boolean operators can be used only on Boolean variables or expressions. The result of a
Boolean operator is always a Boolean value.
Oracle10g: Java Programming 4-21
Copyright 2004, Oracle. All rights reserved.
Using the Assignment Operator
The result of an assignment operation is a value and
can be used whenever an expression is permitted.
The value on the right is assigned to the identifier
on the left:
The expression on the right is always evaluated
before the assignment.
Assignments can be strung together:
int var1 = 0, var2 = 0;
var1 = 50; // var1 now equals 50
var2 = var1 + 10; // var2 now equals 60
var1 = var2 = var3 = 50;
Using the Assignment Operator
After a variable has been declared, you can assign a value by using the assignment operator.
First, the value of the expression on the right side of the assignment operator is determined
or evaluated, and then the result is assigned to the variable on the left.
Note the following example:
var1 = 10;
var2 = var1 + 10; // the right side is evaluated first
var2 now equals 20.
Assignments Can Be Strung Together in the Same Statement
Multiple assignment operators can be used within a single statement as follows:
var1 = var2 = var3 = 50;
The assignment operator has right associativity, which means that the rightmost
assignment operator is performed first in this statement. The other assignments are evaluated
moving from the right to the left. The statement can be rewritten as follows, to emphasize
the order in which the assignments are carried out and to make the code clearer:
var1 = (var2 = (var3 = 50));
The net result is that the value 50 is assigned to all three variables.
Oracle10g: Java Programming 4-22
Copyright 2004, Oracle. All rights reserved.
Working with Arithmetic Operators
Perform basic arithmetic operations.
Work on numeric variables and literals.
int a, b, c, d, e;
a = 2 + 2; // addition
b = a * 3; // multiplication
c = b - 2; // subtraction
d = b / 2; // division
e = b % 2; // returns the remainder of division
Simple Arithmetic Operators
Most of the arithmetic operators in Java are similar to those in other languages. Both
operands must be of numeric types and the result of the operation is always numeric. The
important things to remember when using the simple arithmetic operators are:
Integer division results in an integer, and any remainder is ignored.
The multiply, divide, and modulus operators have higher precedence than the add and
subtract operators. In other words, multiplication, division, and modulus operations are
evaluated before addition and subtraction operations.
Arithmetic operations can be performed on variables and literals.
Modulus (mod) returns the remainder of a division operation.
Oracle10g: Java Programming 4-23
Copyright 2004, Oracle. All rights reserved.
More on Arithmetic Operators
Most operations result in int or long:
byte, char, and short values are promoted to
int before the operation.
If either argument is of the long type, then the
other is also promoted to long, and the result is of
the long type.
byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2; // ERROR: result is an int
// b3 is byte
Integer Arithmetic in Java Is Always Performed by Using int or long
In Java, all integer arithmetic is performed with int or long values; byte, char, and
short values are automatically widened (promoted) to int before an arithmetic operation
commences, and the result is also int. Similarly, if the argument on one side of an
arithmetic operator is a long, then the argument on the other side is automatically
promoted to a long as well, and the result is a long.
Consequently, if the result is to be assigned to a variable of a smaller type, then the compiler
signals an error.
Promoting floats
If an expression contains a float, the entire expression is promoted to float. All literal
floating-point values are viewed as doubles.
Oracle10g: Java Programming 4-24
Copyright 2004, Oracle. All rights reserved.
Examining Conversions and Casts
Java automatically converts a value of one
numeric type to a larger type.
Java does not automatically downcast.
byte
short
char
int
long
byte long int
short
char
Examining Conversions and Casts
The method that is used to force one variable type to be stored as another variable type is
called casting.
Java Can Convert Small Numeric Types into Wider Types Automatically
Java automatically converts or casts a variable or expression from one numeric type to a
wider type if necessary. For example, if you try to assign a byte to a short, then the
compiler automatically converts the byte into a short before making the assignment.
Java Does Not Convert Large Numeric Types into Narrower Types Automatically
Java does not provide an automatic conversion from large numeric types to narrower types
because this may result in loss of information. If you assign the value of a larger type to a
smaller type, then the compiler will issue an error. However, you can force the compiler to
convert a variable of one numeric type to a narrower type by using an explicit cast.
Oracle10g: Java Programming 4-25
Examining Conversions and Casts (continued)
Java Does Not Convert Large Numeric Types into Narrower Types Automatically
(continued)
Casting takes the internal bit pattern of the source variable and places it in the target
variables type. This can result in a loss of data and unpredictable results. If you need to cast
a variable, then you must be aware of the possibility of data loss.
The syntax for an explicit cast is to put the target type in parentheses in front of the
expression or variable. For example,
byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2; // error: the result is automatically int
b3 = (byte) (b1 + b2);
// this corrects it but may
// result in data loss
// if the added value is
// greater than positive 127
Remember that casts stop the compiler from performing useful checks on the validity of
your code.
Casting and Arithmetic Operations
Be careful when performing arithmetic operations while casting to a smaller type. Note that
performing a narrowing conversion, such as int to byte, may produce the wrong
arithmetic result. For example, if you add a byte with the value 100 to another byte with
the value 100, the int result is 200. However, if this result is cast to a byte, the value
becomes -56 because this is how the bit pattern for 200 is treated in a byte.
Oracle10g: Java Programming 4-26
Copyright 2004, Oracle. All rights reserved.
Incrementing and Decrementing Values
The ++ and -- operators increment and decrement
by 1, respectively:
The ++ and -- operators can be used in two ways:
int var1 = 3;
var1++; // var1 now equals 4
int var1 = 3, var2 = 0;
var2 = ++var1; // Prefix: Increment var1 first,
// then assign to var2.
var2 = var1++; // Postfix: Assign to var2 first,
// then increment var1.
Increment and Decrement Operators
Incrementing or decrementing a value by one is a very common operation in any language.
Like C and C++, Java provides special operators for this purpose. Both the increment (++)
and decrement (--) operators can be prefixed or postfixed; that is, they can be placed before
or after the operand. The placement of the operators affects when the operation takes place.
Prefixed Operator
When an increment or decrement operator is placed in front of a variable, the variable is
incremented before any assignment operation. In other words, the value in the variable is
adjusted by 1 (either up or down), and then it is used in the assignment.
Postfixed Operator
When the operator is placed after the variable, the variable is adjusted after the assignment
operation. The value that is assigned is the value of the variable before it is incremented or
decremented.
Oracle10g: Java Programming 4-27
Copyright 2004, Oracle. All rights reserved.
greater than
greater than or equal to
less than
less than or equal to
equal to
not equal to
>
>=
<
<=
==
!=
Relational and Equality Operators
int var1 = 7, var2 = 13;
boolean res = true;
res = (var1 == var2); // res now equals false
res = (var2 > var1); // res now equals true
Relational and Equality Operators
Java provides a set of relational and equality operators for comparing the values of two
variables or expressions. Unlike many languages, other than C and C++, the equality
operator is a double equals sign, ==. The inequality operator is !=.
Remember that the assignment operator, the equals sign, sets the value of the variable on the
left of the sign to the value of the expression or variable on the right side of the equals sign.
The double equals sign tests for equality of both sides. For example:
int goodCreditRating = 3;
boolean goodCredit = false;
goodCredit = (custRating == goodCreditRating);
In the example, if the customers rating is not 3, then goodCredit will be assigned
false, which is the result of comparing the value of goodCreditRating with the
customers actual rating. If the actual rating was 3, then the result will be true.
Oracle10g: Java Programming 4-28
Copyright 2004, Oracle. All rights reserved.
Using the Conditional Operator (?:)
Useful alternative to ifelse:
If boolean_expr is true, the result is expr1;
otherwise, the result is expr2:
boolean_expr ? expr1 : expr2
int val1 = 120, val2 = 0;
int highest;
highest = (val1 > val2) ? val1 : val2;
System.out.println("Highest value is " + highest);
The Conditional Operator (?:)
The conditional operator (?:) is the only ternary operator in Java, which means it has three
operands. The conditional operator is an expression that returns a value and is a useful
alternative to ifelse.
The Boolean expression evaluates first and, if true, returns the value of the first expression
(expr1) or if false, returns the value of the second expression (expr2).
For example, consider the conditional operator:
max = (10 > 8) ? 100: 200;
Because 10 is greater than 8, max is set to 100. The values of the expressions (100 and
200) can be any valid Java expressions including literals.
A similar effect can be achieved by using an ifelse statement, as follows. Use
whichever approach you find more intuitive.
if (10 > 8)
max = 100;
else
max = 200;
Oracle10g: Java Programming 4-29
Copyright 2004, Oracle. All rights reserved.
Using Logical Operators
Results of Boolean expressions can be combined by
using logical operators:
and (with or without short-circuit evaluation)
or (with or without short-circuit evaluation)
exclusive or
not
&& &
|| |
^
!
int var0 = 0, var1 = 1, var2 = 2;
boolean res = true;
highest = (val1 > val2)? val1 : val2;
res = !res;
Logical Operators
Boolean values and expressions that result in Boolean values can be combined by using the
logical operators &, |, and !, which represent AND, OR, and NOT operations, respectively.
Short-Circuit Evaluation
The && and ||operators provide support for short-circuit evaluation; if the expression on
the left of the operator has already determined the outcome of the whole logical expression,
then the expression on the right of the operator is not performed.
Consider the following example using the && operator:
if (test1() && test2())
If test1 returns false, then there is no need to carry out test2 because a logical AND
requires both tests to yield true; therefore, test2 is not performed.
Likewise, consider the following example using the || operator:
if (test1() || test1())
If test1 returns true, there is no need to carry out test2 because a logical OR only
requires one of the tests to yield true; therefore, test2 is not performed.
Non-Short-Circuit Evaluation
If you have a Boolean expression involving two tests and you want the second test to be
performed regardless of the outcome of the first test, use the & operator instead of &&, and
the | operator instead of ||. Also, note that there is a ^ operator that performs the exclusive
OR operation.
Oracle10g: Java Programming 4-30
Copyright 2004, Oracle. All rights reserved.
Compound Assignment Operators
An assignment operator can be combined with any
conventional binary operator:
double total=0, num = 1;
double percentage = .50;

total = total + num; // total is now 1
total += num; // total is now 2
total -= num; // total is now 1
total *= percentage; // total is now .5
total /= 2; // total is now 0.25
num %= percentage; // num is now 0
Compound Assignment Operators
Expressions such as var1 = var1 + 20 are so common that Java provides compound
assignment operators as a shorthand equivalent. You can form these compound operators by
combining the assignment operator with any of the conventional binary operators. Binary
operators are those operators that use two arguments such as +, -, *, / and so on.
For example, the expression
rentalDueDate = rentalDueDate + 3;
can be rewritten as follows:
rentalDueDate += 3;
This expression takes the current value of rentalDueDate and adds 3. It then places the
result into rentalDueDate.
The %= operator computes the remainder of dividing the first variable by the second, and
then assigns it to the first variable.
Oracle10g: Java Programming 4-31
Copyright 2004, Oracle. All rights reserved.
Operator Precedence
Operators
++ -- + - ~
! (type)
* / %
+ - +
<< >> >>>
< > <= >=
instanceof
== !=
&
^
|
&&
||
?:
= op=
Comments
Unary operators
Multiply, divide, remainder
Add, subtract, add string
Shift (>>> is zero-fill shift)
Relational, type compare
Equality
Bit/logical AND
Bit/logical exclusive OR
Bit/logical inclusive OR
Logical AND
Logical OR
Conditional operator
Assignment operators
Order
1
2
3
4
5
6
7
8
9
10
11
12
13
Assoc.
R
L
L
L
L
L
L
L
L
L
L
R
R
Java Operators
Precedence refers to the order in which operators are executed. For example, multiplication
is always performed before addition or subtraction. The table in the slide shows the Java
operators in order of precedence, where row 1 has the highest precedence. With the
exception of the unary, conditional, and assignment operators, which are right associative,
operators with the same precedence are executed from left to right.
Associativity
Operators with the same precedence are performed in order, according to their associativity.
In the slide, the final column in the table shows the associativity for each operator:
L indicates left-to-right associativity. Most operators fall in this category.
R indicates right-to-left associativity. Only the unary operators (row 1), the conditional
operator (row 12), and the assignment operators (row 13) fall in this category.
For example, consider the following statement:
int j = 3 * 10 % 7;
The * and % operators have the same precedence, but have left-to-right associativity.
Therefore, the * is performed first, as though you had used parentheses as follows:
int j = (3 * 10) % 7; // Same result, 30%7, which is 2
If you choose to place parentheses in a different place, then you get a different result:
int j = 3 * (10 % 7);// Different result, 3*3, which is 9
Oracle10g: Java Programming 4-32
Copyright 2004, Oracle. All rights reserved.
More on Operator Precedence
Operator precedence determines the order in
which operators are executed:
Operators with the same precedence are executed
from left to right (see note in text below):
Use parentheses to override the default order.
int var1 = 0;
var1 = 2 + 3 * 4; // var1 now equals 14
int var1 = 0;
var1 = 12 - 6 + 3; // var1 now equals 9
Using the Precedence Table
The precedence table defines the order in which operators are evaluated. If you have a
complex expression containing many operators, then refer to the precedence table to make
sure that the operators are being performed in the order that you expect.
To make things simpler, you can use parentheses to override the default order in which
operators are executed. Many programmers also use parentheses where they are not strictly
necessary to make the code more readable.
Note: The second bullet in the slide states that operators with the same precedence are
evaluated from left to right. This is true for all operators except the unary operators, the
conditional operator, and the assignment operators, which are evaluated from right to left as
described on the previous page.
Using Parentheses
Use parentheses to control the order of statement evaluation exactly. Consider the following
variations:
var1 = 12 - 6 + 3; // var1 now equals 9
var1 = 12 - (6 + 3); // var1 now equals 3
Oracle10g: Java Programming 4-33
Copyright 2004, Oracle. All rights reserved.
Concatenating Strings
The + operator creates and concatenates strings:
String name = "Jane ";
String lastName = "Hathaway";
String fullName;
name = name + lastName; // name is now
//"Jane Hathaway"
// OR
name += lastName; // same result
fullName = name;
Using Operators with Strings
Only three operators can be used with strings: the assignment operator (=), the addition
operator (+), and the compound addition assignment operator (+=).
Using the Assignment Operator
You can use the assignment operator to create a new String object or to set the value of an
existing String reference to refer to a String object:
String firstName = "John";
firstName = "John";
Using the Addition Operator
The addition operator is very useful with strings because it creates a new String object by
concatenating the contents of two String objects. Consider the following code:
String firstName = "John";
String lastName = "Doe";
fullName = firstName + " " + lastName
fullName is now "John Doe".
If part of a String expression is not a String, then Java automatically converts that part into a
String object and then concatenates its contents with the other String object to form a new
String as a result.
Using the Compound Assignment Operator
You can also use the += operator to concatenate a String to an existing String.
Oracle10g: Java Programming 4-34
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
Java has eight primitive data types.
A variable must be declared before it can be used.
Java provides a comprehensive set of operators.
Explicit casting may be necessary if you use data
types smaller than int.
The + and += operators can be used to create and
concatenate strings.
Oracle10g: Java Programming 4-35
Copyright 2004, Oracle. All rights reserved.
Practice 4: Overview
This practice covers:
Declaring and initializing variables
Using various operators to compute new values
Displaying results on the console
Practice 4: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les03 directory, and continue with
this practice.
Remember that if you close a DOS window or change the location of the .class files, then
you must set the CLASSPATH variable again.
Oracle10g: Java Programming 4-36
Practice 4: Exploring Primitive Data Types and Operators
Goal
The goal of this practice is to declare and initialize variables, and use them with operators to
calculate new values. You will also be able to categorize the primitive data types and use
them in code.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want move on to this practice, then change to the les03 directory, and continue with
this practice.
Your Assignment
You are now ready to add some code to the simple main() method in the OrderEntry
application class created in the last exercise. In the following steps, you declare some
variables to hold the costs of some rental items. After displaying the contents of these
variables, you perform various tests and calculations on these variables and display the
results.
Modify the OrderEntry Class and Add Some Calculations
1. Declare variables in the main() method.
a. Declare and initialize two variables to hold the cost of two rental items. The
values of the two items must be 2.95 and 3.50. Name the items anything you like,
but do not use single-character variable names; instead, use longer meaningful
names such as item1 and item2. Also, think about your choice of variable
type.
Note: Recompile the class after each step, fix any compiler errors that may arise,
and run the class to view any output.
b. You may have used four different statements: two to declare your variables, and
two more to initialize them. Now try to declare and initialize the variables in a
single line. Finally, see whether you can combine the declaration and
initialization of both variables into a single statement.
c. Use System.out.println() to display the contents of your variables. After
recompiling the class, run the class and see what is displayed.
d. Modify the code you have just written to display more meaningful messages,
such as Item 1 cost 2.95.
(Hint: Use the + operator.)
e. Now that you have the total for the items, calculate the total for the rental by
adding the tax. The tax rate is 8.25%. Create a variable to hold this value.
Calculate the total charge for the rental. Also declare and initialize a variable to
hold the number of days and to track the line numbers. This variable holds the
number of days for which the customer rents the items, and initializes the value
to 2 for two days.
f. Display the total in a meaningful way such as Total cost:6.982125.
Oracle10g: Java Programming 4-37
Practice 4: Exploring Primitive Data Types and Operators (continued)
2. Calculate the total cost, and display the result.
a. Extend the item total to be the item cost * the number of rental days, displaying:
Item 1 is 2.95 * 2 days = 5.9
b. Display the results in a meaningful way. Your result must look like the
following:
Total cost: 13.96425.
3. Compile and run the OrderEntry class. Make sure the .class file has been placed in
the correct directory (E:\labs\OrderEntry\classes\oe).
Note: Make sure the CLASSPATH variable points to the location of your .class
files (E:\labs\OrderEntry\src\oe).
Copyright 2004, Oracle. All rights reserved.
Controlling Program Flow
Oracle10g: Java Programming 5-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Use decision-making constructs
Perform loop operations
Write switch statements
Lesson Aim
This lesson introduces Javas decision-making and repetition constructs. You learn how to
use those constructs to build nonlinear applications. Like other block-structured languages,
Java supports statements to control the flow of execution in a program. This lesson explains
how to use decision-making constructs and how to use the loop statements that are provided
in Java.
Oracle10g: Java Programming 5-3
Lesson Aim (continued)
What Is Program Flow?
By default, computer programs start execution at, or near, the beginning of the code and
move down the code until the end. This is fine if your program does one thing, always in the
same order, and never needs to deviate from this path. Unfortunately, this does not happen
very often in most businesses.
Program control constructs are designed so that the programmer can design and build
programs that perform certain parts of code conditionally. There are also constructs so that
code can be executed repetitively. These coding structures give you infinite control of what,
when, and how many times your program performs a particular task.
By providing standard control mechanisms, Java gives programmers control over the exact
execution order of their program code.
Oracle10g: Java Programming 5-4
Copyright 2004, Oracle. All rights reserved.
Categorizing Basic Flow Control Types
Flow control can be categorized into four types:
Sequential
Transfer Selection
Iteration
Categorizing Basic Flow Control Types
Sequential
Sequential is the flow control type where the program flow follows a simple sequential path,
executing one statement after another. The primary sequential structure is a compound block
statement, which is a series of statements inside braces.
Selection
Selection is the flow control type where only one path out of a number of possibilities is
taken. Simple selection involves the conditional execution of a statement or block of code,
which is guarded by an expression that will have the value true if the guarded code is to be
executed. This is the if statement. An ifelse statement provides an alternate path of
execution: The true or false evaluation of a control expression determines which branch is
taken. A switch statement supports a multiway branch based on the value of a control
expression.
Oracle10g: Java Programming 5-5
Categorizing Basic Flow Control Types (continued)
Iteration
Iteration is the type where one statement or block of code is executed repeatedly. A simple
loop executes the same code whereas a control expression has a true value, terminating
execution when the expression evaluates to false. Java provides three loop forms: while,
dowhile, and for loops.
Transfer
Transfer is the type where the point of execution jumps to a different point in the program.
Transfer is generally considered poor programming style, because it is hard to follow the
logic and therefore difficult to maintain the code.
Goto
The Java language does not have a goto statement. This allows the language to be less
complex and eliminates rules about how the goto must operate in for statements. The
break and continue statements work in the majority of occasions where a goto would
normally be used.
Oracle10g: Java Programming 5-6
Copyright 2004, Oracle. All rights reserved.
Using Flow Control in Java
Each simple statement terminates with a
semicolon (;).
Group statements by using the braces { }.
Each block executes as a single statement within
the flow of control structure.
{
boolean finished = true;
System.out.println("i = " + i);
i++;
}
Using Flow Control in Java
Simple Statements
A simple statement is any expression that terminates with a semicolon. For example:
var1 = var2 + var3;
var3 = var1++;
var3++;
Compound Statements (Blocks)
Related statements can be grouped in braces to form a compound statement or block:
{
int i;
boolean finished = true;
System.out.println("i = " + i);
i++;
}
Semantically, a block behaves like a single statement and can be used anywhere a single
statement is allowed. There is no semicolon after the closing brace. Java does not use
matched block delimiters, such as if and end if, like PL/SQL. Any variables that are
declared in a block remain in scope up to the closing brace. After the block is exited, the
block variables cease to exist.
Blocking improves readability of program code and can help to make your program easier to
control and debug.
Oracle10g: Java Programming 5-7
Copyright 2004, Oracle. All rights reserved.
Using the if Statement
if ( boolean_expr )
statement1;
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");

if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
General:
Examples:
The if Statement
The if statement provides basic selection processing. A Boolean control expression
determines which branch is taken, as follows:
If the expression evaluates to true, the first branch is taken; that is, the if body is
executed.
If the expression evaluates to false, the second branch is taken; that is, the else
body is executed. The else clause is optional; if it is omitted, nothing is executed if
the control expression evaluates to false.
Example
if (orderIsPaid) {
System.out.println("send with receipt");
}
else {
System.out.println("collect funds");
}
Common Mistakes When Using if Statements
Use the equality operator (==) rather than the assignment operator (=) in the control
expression.
Oracle10g: Java Programming 5-8
Copyright 2004, Oracle. All rights reserved.
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed >= 25 but <= 65");
else
System.out.println("Speed under 25");
if (speed > 65)
System.out.println("Speed over 65");
else if (speed >= 25)
System.out.println("Speed greater to 65");
else
System.out.println("Speed under 25");
Nested if Statements
Where multiple tests are necessary, if statements can be nested. However, this approach is
generally not recommended because you have to maintain a mental stack of the decisions
that are being made; this becomes difficult if you have more than three levels of nested if
statements.
Also, it is very easy to forget that an else clause always binds to the nearest if statement
above it that is not already matched with an else, even if the indentation suggests
otherwise. This is sometimes referred to as the dangling else problem.
The ifelseif Construct
The dangling else problem can be solved with a prudent use of braces, but a cleaner
approach is to use the ifelse if construct, as shown in the second example in the
slide. Note that these are two separate keywords; unlike some languages, Java does not have
an elseif keyword.
Oracle10g: Java Programming 5-9
Copyright 2004, Oracle. All rights reserved.
Guided Practice: Spot the Mistakes
int x = 3, y = 5;
if (x >= 0)
if (y < x)
System.out.println("y is less than x");
else
System.out.println("x is negative");
int x = 7;
if (x = 0)
System.out.println("x is zero");
int x = 14, y = 24;
if ( x % 2 == 0 && y % 2 == 0 );
System.out.println("x and y are even");
1
2
3
Guided Practice: Spot the Mistakes
Example 1: Use braces to associate or bind statements and make the code easier to follow.
if (x >= 0) {
if (y < x)
System.out.println("y is less than x");}
else
System.out.println("x is negative");
It is the last if that pairs with an else. Although it does not become a compiler error, it
becomes a logic error.
Example 2: The second example uses an assignment operator (=) rather than an equality
operator (==) in the if test. Fortunately, Java compilers detect this mistake and indicate a
compiler error because the expression in the if test must evaluate to a Boolean.
Example 3
The third example has an extra semicolon at the end of the if test. This is not a compiler
error; the compiler treats the semicolon as an empty if body, as follows:
if ( x % 2 == 0 && y % 2 == 0 )
; // Null "if" body
Oracle10g: Java Programming 5-10
Copyright 2004, Oracle. All rights reserved.
Defining the switch Statement
The switch
statement is useful
when selecting an
action from several
alternative integer
values.
Integer_expr must
be byte, int, char,
or short.
switch ( integer_expr ) {
case constant_expr1:
statement1;
break;
case constant_expr2:
statement2;
break;
[default:
statement3;]
}
The switch Statement
The switch statement provides a clean way to dispatch to different sections of your code,
depending on predefined values. It can be used to choose among many alternative actions,
based on the value.
Anatomy of the switch Statement
The switch statement is useful when selecting some action from several alternatives. The
value inside the test expression must be a byte, char, short, or int. It cannot be a
boolean, long, double, float, String, or any other kind of object.
The value inside the test expression is compared against the case labels, which are constant
expressions.
If a match is found, then the statements following the label are executed. Execution
continues until a break is encountered, which transfers control to the statement
following the switch statement.
If no match is found, then control passes to the statements following the default
label. The default label is optional; if no default label is provided, then the
switch statement does nothing when no match is found. It is a good practice to
always provide a default label, even if no action is required.
Oracle10g: Java Programming 5-11
The switch Statement (continued)
The case Labels
The case labels must be constant expressions and known at compile time. You can use
either literal numbers or final variables (constants).
Oracle10g: Java Programming 5-12
Copyright 2004, Oracle. All rights reserved.
More About the switch Statement
case labels
must be
constants.
Use break to
jump out of a
switch.
It is
recommended
to always
provide a
default.
switch (choice) {
case 37:
System.out.println("Coffee?");
break;
case 45:
System.out.println("Tea?");
break;
default:
System.out.println("???");
break;
}
More About switch
The slide shows a simple example of a switch statement. There are situations where
falling through can be useful. To fall through, simply do not include a break as in the
following example:
char c = 'b';
switch (c) {
case 'a': System.out.println("First letter in alphabet");
break;
case 'b': System.out.println("Second letter in alphabet");
case 'c': System.out.println("Third letter in alphabet");
case 'd': System.out.println("Fourth letter in alphabet");
}
In the above example, the results that are printed displays the following lines because of the
absence of a break statement between each case test for b, c, and d.
Second letter in alphabet
Third letter in alphabet
Fourth letter in alphabet
Oracle10g: Java Programming 5-13
Copyright 2004, Oracle. All rights reserved.
Looping in Java
There are three types of loops in Java:
while
dowhile
for
All loops have four parts:
Initialization
Iteration condition
Body
Termination
Looping in Java
What Is Looping?
Looping in any programming language refers to repeatedly executing a block of code until a
specified condition is met. Java provides three standard loop constructs: while,
dowhile, and for.
All Loops Have Four Parts
All loops contain four parts: initialization, iteration, statement body, and termination.
Initialization: Initialization sets the initial conditions of the loop. This includes any variable
that may be incremented to control execution of the loop.
Iteration: The iteration is the code that you want to execute after the body but before you go
through the loop again. It is used for control of the loop execution.
Body: The body is executed if the termination condition is true.
Termination: Termination is the expression that is evaluated to determine if the body must
be executed. The expression must be a Boolean expression. If the expression evaluates to
true, then the body is executed; if it is false, then the body is not executed.
Choosing the appropriate loop
Use the while loop to ensure that the termination condition is tested before executing the
body of the loop. Use the dowhile to ensure that the body executes once before the
termination condition is made. The for loop is similar to the while loop.
Oracle10g: Java Programming 5-14
Copyright 2004, Oracle. All rights reserved.
Using the while Loop
while is the simplest loop statement and contains the
following general form:
while ( boolean_expr )
statement;
int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Example:
Anatomy of the while Loop
The simplest loop construct in Java is the while loop. In the while loop, the loop body is
executed repeatedly while a boolean control expression evaluates to true. When the
control expression evaluates to false, the loop terminates and control passes to the first
statement after the closing brace of the loop body.
Note that the control expression is evaluated before the loop body is executed. If the control
expression evaluates to false the first time, then it does not enter the loop body.
Common Mistakes When Using while Loops
A common mistake when using while loops is to forget to iterate the variable that is used
in the control expression. This results in an infinite loop. Another common mistake is to put
a semicolon at the end of the first line, between the control expression and the loop body.
This places the incrementing of the counter outside the loop and results in an infinite loop.
Oracle10g: Java Programming 5-15
Copyright 2004, Oracle. All rights reserved.
Using the dowhile Loop
dowhile loops place the test at the end:
do
statement;
while ( termination );
int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
Example:
Anatomy of the dowhile Loop
The dowhile loop is similar to the while loop except that the control expression is
evaluated after the loop body has been executed. This guarantees that the loop body executes
at least once. This construct is useful if you want to execute the statement at least once
without regard to the while condition.
Common Mistakes When Using dowhile Loops
A common mistake when using dowhile loops is to forget one of the braces of a
compound statement or the final semicolon. The compiler detects both of these types of
errors.
Oracle10g: Java Programming 5-16
Copyright 2004, Oracle. All rights reserved.
Using the for Loop
for loops are the most common loops:
How would this for loop look using a while loop?
for (i = 0; i < 10; i++)
System.out.println(i);
for ( initialization; termination; iteration )
statement;
Example:
Anatomy of the for Loop
The for loop combines components of a loop into a single construct with positions for each
component. The three components that are enclosed in parentheses are separated by
semicolons.
Common Mistakes When Using for Loops
A common coding error with for loops is to put a semicolon after the closing parenthesis.
This is equivalent to an empty loop body that does nothing on each iteration.
for Loops and while Loops Compared
The for loop shown in the slide is equivalent to the following while loop:
i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
Oracle10g: Java Programming 5-17
Copyright 2004, Oracle. All rights reserved.
More About the for Loop
Variables can be declared in the initialization part
of a for loop:
Initialization and iteration can consist of a list of
comma-separated expressions:
for (int i = 0; i < 10; i++)
System.out.println("i = " + i);
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
More About the for Loop
Declaring Variables in the Initialization Part of a for Loop
The initialization expression in a for loop can include a declaration, as shown in the first
example in the slide. Any variable that is declared here is local to the for loop itself. After
the execution leaves the loop, the variable is no longer available.
Complex Initialization and Iteration Components
The initialization and iteration components can consist of several comma-separated
expressions, as shown in the second example in the slide, where two indexes are
incremented or decremented in opposite directions.
Empty Initialization, Termination, or Iteration Expressions
Any of the components of a for loop can be omitted. For example, a common way to
implement a do-forever loop is as follows:
for (;;) { // loop forever

}
This kind of loop is common in multithreaded programs, where one of the threads loops
continually doing some dedicated task. For example, a server program may have a thread
that loops forever listening for connections from client programs.
Oracle10g: Java Programming 5-18
Copyright 2004, Oracle. All rights reserved.
Guided Practice: Spot the Mistakes
int x = 10;
while (x > 0);
System.out.println(x--);
System.out.println("We have lift off!");
int x = 10;
while (x > 0)
System.out.println("x is " + x);
x--;
int sum = 0;
for (; i < 10; sum += i++);
System.out.println("Sum is " + sum);
1
2
3
Guided Practice: Spot the Mistakes
Example 1
The first example contains an extra semicolon at the end of while. This is not a compiler
error; the compiler treats the semicolon as an empty loop body, as follows:
while (x > 0)
; // Null loop body
Example 2
The problem with the second example is that x is not changed inside the loop. The x-- term
is deemed to be outside the loop because there are no braces. Therefore, if x is greater than
zero the first time through the loop, it will always be greater than zero, and the loop will
never terminate.
Example 3
The problem with this example is that i is not initialized anywhere. The rest of the loop is
fine. Here is a description of what is happening:
The loop keeps iterating while i is less than 10.
The semicolon at the end of the for line indicates a null loop body.
The iteration expression in the for loop adds i to sum, and then increments i ready
for the next loop iteration.
Oracle10g: Java Programming 5-19
Copyright 2004, Oracle. All rights reserved.
The break Statement
Breaks out of a loop or switch statement
Transfers control to the first statement after the
loop body or switch statement
Can simplify code but must be used sparingly

while (age <= 65) {
balance = (balance+payment) * (1 + interest);
if (balance >= 250000)
break;
age++;
}

Anatomy of the break Statement
You can use a break statement to exit any kind of loop when a specific condition is met.
Control is transferred immediately to the first statement following the closing brace of the
loop body.
Should break Be Used?
Many programmers frown upon the use of break because it is not strictly necessary. For
example, in the code fragment that is shown in the slide, you could have avoided using
break by expanding the control expression as follows:
while (age <=65 && balance < 250000) {

}
Nevertheless, the use of break statements is useful where you need to abort a loop if some
event occurs while executing the loop body. As you have already seen, break statements
are also used in switch statements to prevent falling through to a subsequent case label.
Oracle10g: Java Programming 5-20
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
The primary means of decision-making is the if
statement, with the optional else.
Java also offers the switch statement.
Java provides three loop statements: while,
dowhile, and for.
Use break and continue sparingly.
Oracle10g: Java Programming 5-21
Copyright 2004, Oracle. All rights reserved.
Practice 5: Overview
This practice covers:
Performing tests by using ifelse statements
Using loops to perform iterative operations
Using the break statement to exit a loop
Using the &&, ||, and ! operators in Boolean
expressions
Practice 5: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les04 directory, and continue with
this practice.
Remember that if you close a DOS window or change the location of the .class files, then
you must set the CLASSPATH variable again.
Oracle10g: Java Programming 5-22
Practice 5: Controlling Program Flow
Goal
The goal of this practice is to make use of flow control constructs that provide methods to
determine the number of days in a month, and handle leap years.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les04 directory, and continue with
this practice. Remember that if you close a DOS window or change the location of the
.class files, then you must set the CLASSPATH variable again.
Your Assignment
In this exercise, you create a program that calculates the return date of a rented item based
on the day it was rented and how many days it can be rented. You must determine the
number of days in the month and whether it is a leap year.
Modify the OrderEntry class to calculate dates
1. Determine the number of days in a month. You use a switch statement to set an
integer value to the number of days in the month you specify. For now, add all the
code in the main() method of the OrderEntry.java application.
a. Declare three integers to hold a day, a month, and a year. Initialize these
variables with a date of your choice.
b. Add a simple statement to display the date; choose whichever format you prefer,
such as day/month/year or month/day/year.
c. Declare a variable to hold the number of days in the current month. Then, using a
switch statement, determine the value to store in this variable. Use
daysInMonth as the name of the variable.
Note: The hardest part of this exercise is remembering how many days there
really are in each month. Here is a reminder if you need it: There are 30 days in
September, April, June, and November. All the rest are 31, except for February,
which is 28 (ignore leap years for now).
d. Add a simple statement to display the number of days for the current month:
System.out.println(daysInMonth + " days in month");
2. Ensure your CLASSPATH is set correctly (E:\labs\OrderEntry\src\oe).
Compile and test the program. Experiment with different values for the month. What
happens if you initialize the month with an invalid value, such as 13?
For January 27, 2000, the output should look something like:
27/1/2000
31 days in the month
3. Use a for loop to display dates.
a. Using a for loop, extend your program so that it prints out all the dates between
your specified day/month/year and the end of the month. For example:
if your day variable is 27,
and your month variable is 1 (January),
and your year variable is 2000,
Oracle10g: Java Programming 5-23
Practice 5: Controlling Program Flow (continued)
3. Use a for loop to display dates. (continued)
then your program must display all the dates between 27 January and 31 January
inclusive, as follows:
27/1/2000
28/1/2000
29/1/2000
30/1/2000
31/1/2000
Hint: You must use the result of the switch statement in question 2 to determine the
last day in the month.
b. Compile and test your program making sure it works with a variety of dates.
c. Modify your program so that it outputs a maximum of 10 dates. For example, if
your day/month/year variables are 19/1/2000, the output must now be as follows:
19/1/2000
20/1/2000
21/1/2000
22/1/2000
23/1/2000
24/1/2000
25/1/2000
26/1/2000
27/1/2000
28/1/2000
Make sure your program works for dates near the end of the month, such as
30/1/2000. In this situation, it must output only the following:
30/1/2000
31/1/2000
d. Compile your program, and test it with a variety of dates to make sure it still
works.
4. Determine whether the year you specify is a leap year. You use the boolean
operators && and ||.
a. Build a boolean statement that tests year to see whether it is a leap year. A
year is a leap year if it is divisible by 4, and it is either not divisible by 100, or it
is divisible by 400.
b. Modify your switch statement from question 2, to cater for leap years.
Remember that February has 29 days in a leap year and 28 days in nonleap years.
c. Build and test your program with a variety of dates. The following table includes
some sample leap years and nonleap years you may want to use as test data:
Leap years Non-leap years
1996 1997
1984 2001
2000 1900
1964 1967
Oracle10g: Java Programming 5-24
Practice 5: Controlling Program Flow (continued)
5. You must calculate the date on which each rental is due. The due date is the current
date plus 3 days. For this test, you use a number of different dates for the current date,
not just todays date.
a. Declare three variables to hold the due date (dueDay, dueMth, dueYr).
b. Add a variable to hold the rental period of 3 days.
c. Add the due date calculation to your program that adds the rental period to the
date you used in step 1. Display your original date and the due date in a
meaningful way. The output must look something like:
Rental Date: 27/2/2001
Number of rental days: 3
Date Due back: 2/3/2001
d. Test your routine with several dates; try 29/2/2001.
e. What are the problems you must address?
f. Modify your program to catch input dates with invalid months (not 1 to 12).
6. In building a software solution to a problem, you must determine the size and scope of
the problem and address all the pertinent issues. One of the issues is what to do if the
rental period extends beyond the current month. For example, if the rental date is
August 29 and the rental is for three days, the return date must be September 1, but
with the current solution, it is August 32, which is an obvious error. Acme Video store
rents items only for 10 or fewer days. You must ensure that you take care of the
following:
a. Add code to make sure the calculation results in a valid day.
b. If the rental crosses into a new month, make sure to increment the month.
c. If the rental crosses into a new year, make sure to increment the year.
d. Test your routine with several dates.
e. Modify your program to catch input dates with invalid months (not 1 to 12).
Copyright 2004, Oracle. All rights reserved.
Building Applications with
Oracle JDeveloper 10g
Oracle10g: Java Programming 6-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Create new projects, workspaces, and
applications
Build Java applications in JDeveloper
Enhance user interface frame design
Debug an application by using JDeveloper
debugger
Define classes by using JDeveloper
Describe how JDeveloper can be used to build
enterprise applications
Lesson Aim
This lesson introduces you to Oracle JDeveloper. You learn how to create new projects and
applications, and how to use the various panes in the IDE to edit source code and modify
design of the user interface frame.
Oracle10g: Java Programming 6-3
Copyright 2004, Oracle. All rights reserved.
What Is Oracle JDeveloper 10g?
Oracle JDeveloper 10g provides an integrated
development environment (IDE).
Build, compile, and run Java applications by using
Oracle JDeveloper.
Use wizards to help build source code.
View objects from many perspectives: code,
structure, layout, and so on.
Building Applications with Oracle JDeveloper 10g
You can use Oracle JDeveloper 10g to build a number of different types of Java
components. This lesson focuses on using the JDeveloper IDE for building applications.
Wizard Driven
A wizard is a graphical tool that guides you step-by-step through the process of defining a
new element in the IDE. Oracle JDeveloper 10g provides a number of wizards, including:
Application Workspace Wizard: Defines a new application and associated projects
Applet Wizard: Defines a new Java applet and adds it to the specified project
EJB Wizard: Defines a new Enterprise JavaBean (EJB) and adds it to the specified
project
JSP Wizard: Defines a new JavaServer Page (JSP) and adds it to the specified
project
HTTP Servlet Wizard: Defines a new servlet and adds it to the specified project
Design a User Interface
Oracle JDeveloper 10g provides an interface for designing the visual parts of your program.
JDeveloper enables you to specify the following features of the user interface:
Size and position of controls
Properties for each control, such as labels, enabled or disabled status, font, and so on
Event handler methods
Oracle10g: Java Programming 6-4
Copyright 2004, Oracle. All rights reserved.
Exploring the JDeveloper Environment
System Navigator
Code Editor
Property Inspector
Component Palette
The Oracle JDeveloper 10g Environment
JDeveloper contains four major user interface components. These components are what
you use to edit code, design and manage the user interface, and navigate around your
program.
Component Palette
Properties are attributes that define how a component appears and responds at run time. In
JDeveloper, you set a components initial properties during design time, and your code can
change those properties at run time.
System Navigator
System Navigator is made up of two components. The Navigator pane shows a list of files
or classes in a project. The files may be Java source files, .class files, graphics files,
HTML, XML documents, and so on. The Structure pane lists all the methods, fields, and
graphical user interface (GUI) components in a selected class.
Code Editor
Editors are where most of the work takes place; this is where you write code and design
user interfaces. Open an editor by double-clicking the item you want to edit or view.
Property Inspector
Property Inspector is the window that shows the properties and events associated with a
selected component in the design section of an editor.
Oracle10g: Java Programming 6-5
Copyright 2004, Oracle. All rights reserved.
Examining Workspaces
Contain multiple projects
Enable you to view
currently used objects
Workspace
Navigator
pane
Structure
pane
Application Organization
Oracle JDeveloper 10g uses a well-defined structure to manage Java programming
applications. The structure is hierarchical and supports workspaces, projects, images,
.html files, and so on.
Workspaces
Workspace is the highest level in the control structure. It is a view of all the objects you
currently need, while you are working. A workspace keeps track of the projects you use
and the environment settings while you are developing your Java program. When you open
JDeveloper, the last workspace used is opened by default, so you can resume where you
last stopped working.
Workspaces are stored in files with the extension .jws. You do not edit a workspace file
directly. Whenever you save your workspace, you are prompted to save all the current open
files. To save the open and modified files, select the Save or Save All option from the File
menu.
Note: You can view the content of a workspace file by using any text editor.
Oracle10g: Java Programming 6-6
Application Organization (continued)
Determining Workspaces
Consider workspaces to be a view into the objects currently used. You may choose to
create workspaces, which include projects that were created in different workspaces.
Workspace object groupings can be based around a business area (Accounts Payable,
General Ledger, Accounts Receivable), the phase in a life cycle (analysis, design, deploy)
or the structure of the application (UI, business logic, data structure).
Oracle10g: Java Programming 6-7
Copyright 2004, Oracle. All rights reserved.
What Are Projects?
Contain related
files
Manage project and
environment
settings
Manage compiler
and debug options
Project
Project
files
Projects
JDeveloper projects organize file elements used to create your program. A project file has
the file extension .jpr and keeps track of the source files, packages, classes, images, and
other elements that may be needed for your program. You can add multiple projects to your
workspace to easily access, modify, and reuse your source code. You can view the content
of a project file by using any text editor.
Projects also manage environment variables such as the source and output paths used for
compiling and running your program. Projects also maintain compiler, run time, and
debugging options, so you can customize the behavior of those tools per project.
In the Navigator pane, projects are displayed as the second level in the hierarchy under the
workspace.
When you select a .java or .html file in the System Navigator, the Structure pane
displays the elements of the file in a tree format. For example, when you select a .java
source file, the classes, interfaces, methods, and variables are displayed.
To edit source code, double-click the file in the navigation list to display the contents in the
appropriate editor. The Structure pane can be used to quickly locate specific areas of code
in your Java source files and browse the class hierarchy.
When you are working with the visual designer, the Structure pane displays the
components of your user interface and their associated event handling methods in a
hierarchical tree format.
Note: The italic font is used to indicate the file names that have not been saved yet.
Oracle10g: Java Programming 6-8
Copyright 2004, Oracle. All rights reserved.
Creating JDeveloper Items
JDeveloper items are
invoked by selecting
File > New.
They are categorized by
type:
General
Business Tier
Client Tier
Database Tier
Web Tier
Create any JDeveloper
element.
New Elements
You can create any JDeveloper item from this window. The context for creating the item
must be correct. You must have the correct element selected in the Category column to
create the appropriate Item.
All J2SE libraries, used during development, must be available in the run-time
environment.
While creating the workspace, you can define the paths used for the files stored. All the
files are stored using the following convention:
workspace\project\package
Use the Filter By drop-down list to view specific types of elements.
Oracle10g: Java Programming 6-9
Copyright 2004, Oracle. All rights reserved.
Creating an Application Workspace
In the General
category, select
Application
Workspace to invoke
the Property pane.
Creating an Application Workspace
The aim in this lesson is to create a simple Java application. The first step is to create a new
application workspace that acts as a container for all the files in the application. The
properties to be completed include:
Application Name
Enter a name for the application. This name is used to categorize all the files in your
application.
Directory Name
Enter a top-level directory for the application or click Browse to locate one. This is where
all your application files are stored during development.
Application Package Prefix
Enter a prefix for all packages associated with this application. The prefix you assign
defines the root package for every project in the application.
Application Template
Select a template for the application. Click Manage Templates to edit an existing template
or to create a new one. An application template provides a way to partition the application
into projects that reflect a logical separation of the overall work. Each template provides a
different structure to how the files are organized. For this course, use the Java
Application [Java, Swing] template.
Oracle10g: Java Programming 6-10
Copyright 2004, Oracle. All rights reserved.
Specifying Project Details
Project Properties: Specifying Project Details
A variety of project properties can be created and modified. The properties are categorized
and are accessible from the nodes on the left side of the pane.
The package name is the default for the project, so any Java source created in the project is
automatically put in the specific package, because the package keyword is added to the
source file with the name specified.
Note: The output directory is added as the first path in the classpath parameter for
applications at compile and run time. In addition, together with this output directory, the
libraries selected in the next screen of the wizard form the CLASSPATH for the code in this
project.
In particular, also note that the package name is implicitly appended to the project source
and output directories as the target directories for the saved source (.java) files and for
the compiled (.class) files respectively.
Oracle10g: Java Programming 6-11
Copyright 2004, Oracle. All rights reserved.
Selecting Additional Libraries
Project Properties: Selecting Libraries
In the Libraries Property, select the version of the J2SE you will be using. You can add any
existing libraries and create and add new ones.
The libraries listed here are delivered by Oracle, Sun Microsystems, or third-party
packages and classes. Typically, they are delivered as classes in a .jar file. Use the
existing ones, or add your own.
Note: All the selected libraries become part of the project application CLASSPATH in
addition to the classes compiled into the project output directory. All the classes in the
libraries and output directory will need to be deployed with the application.
Oracle10g: Java Programming 6-12
Copyright 2004, Oracle. All rights reserved.
Adding a New J2SE
New J2SE definitions include:
Java executable
A classpath
A source path
A doc path
Defining a New J2SE in JDeveloper
JDeveloper uses J2SE definitions to describe the installed development kit, or run-time
library. Every JDeveloper project is assigned a specific J2EE version, and each project has
access to any of the defined J2EE versions. Each project then uses this definition to
determine what version of the Java API to use, to compile and run your code.
Each J2EE definition includes:
Java executable used to launch programs
A classpath containing the classes available in the J2SE environment
A source path housing the source files for the J2SE classes
A document path storing the Javadoc files for the J2SE classes
Library Types
A J2SE library can be defined and used as one of the three types:
System: New system libraries will reside with the predefined system libraries,
available to all users of an installation of JDeveloper.
User: These libraries reside in the user home for a particular user, and only the
current user has access to their definitions.
Project: These libraries are associated with a specific project, and are available to
anyone using that project, but only when using that project.
Oracle10g: Java Programming 6-13
Copyright 2004, Oracle. All rights reserved.
Looking at the Directory Structure
JDeveloper creates and stores .java and .class files
by using the following convention:
<ORACLE_HOME>\jdev\mywork
Followed by the workspace
name
Followed by the project name
\classes\<package name>\
\src\<package_name>\
Followed by class and src files
Storing Files in JDeveloper
When installing JDeveloper, the installer creates an JDEV_HOME directory for the
JDeveloper product files. A subdirectory for all the JDeveloper executables and support
code is stored in the \jdev\ directory. One of the directories under \jdev\ is
\mywork\, which is used to store the files you create in JDeveloper.
Each workspace has its own directory, and below it a directory for each project. The name
of the project directory is dependent on the type of application workspace you create. For
Web development, two projects are createdone for the Model and the other for the
View. For a Java\Swing application a single project is created named Client. Each Java
file you create is stored in a \src\<package_name>\ directory under the project it
was created in. All the compiled files are stored in the \classes\<package_name>\
directory. However, you can create your workspace and project directories anywhere in the
file system.
Oracle10g: Java Programming 6-14
Copyright 2004, Oracle. All rights reserved.
Exploring the Skeleton Java Application
Contains application and frame classes
What Files Does the Java Skeleton Application Contain?
To summarize the last few pages, following is a list of the three files that have been
generated by JDeveloper so far:
An <application>.java file containing the application class, which is the top-level
class in the application. The application class contains the main() method for the
program. When the application is executed, Java calls this main() method as the
starting point for the whole application.
A <frame>.java file containing the frame class that specifies the appearance and
the behavior of the GUI window in the application
A <frame_AboutBoxPanel>.java file for the Help/About frame
Oracle10g: Java Programming 6-15
Copyright 2004, Oracle. All rights reserved.
Finding Methods and Fields
Find methods and fields by using the Structure pane.
Using the Structure Pane to Navigate Source Code
As projects evolve, classes can become quite large, containing several methods and fields.
To help you find your way around complex classes, JDeveloper provides the Structure
pane, which is the bottom pane in the System Navigator.
The Structure pane lists all the methods and fields for the currently selected class. If you
double-click an item in the Structure pane, JDeveloper takes you to the definition of that
item in the source code, displaying and highlighting it in the Code Editor. For example, if
you double-click the helpAbout_ActionPerformed entry in the Structure pane, the
start of the helpAbout_ActionPerformed method is highlighted in the Code Editor.
You can also search the Navigator and Structure pane components for strings by using a
[letter]. The search is a hierarchical search based on the first letter of each component. As
you type in subsequent letters, the structure list highlights the first component that begins
with that set of letters. If there is more than one occurrence, use the up and down arrow
keys to scroll through the result set.
Oracle10g: Java Programming 6-16
Copyright 2004, Oracle. All rights reserved.
Supporting Code Development
with Profiler and Code Coach
Improve code quality with Code Coach.
Evaluate execution stack with Execution Sample
profiler.
Examine heap memory usage with Memory
profiler.
Analyze event occurrence and duration with Event
profiler for:
JVM events
Business Components for Java events
Custom events
Code Coach
Code Coach creates more efficient Java programs by helping you write higher quality,
better performing code. You run Code Coach on a class, which returns advice on how to
make your code better.
Profilers
Profilers gather statistics on your program, which enables you to more easily diagnose
performance issues.With Profilers, you can examine and analyze your data.
Code Editor
When you pause momentarily while typing in Code Editor, JDeveloper automatically scans
your code to look for syntax errors. If there are any, you will see them represented in the
Structure pane or in the Log window.
Code Insight
If you pause after typing a . (period), JDeveloper invokes Code Insight. Code Insight
displays valid methods and members from which you can select. JDeveloper also provides
Code Insight for parameters when you pause after typing ( (left parenthesis).
Oracle10g: Java Programming 6-17
Copyright 2004, Oracle. All rights reserved.
Customizing JDeveloper
Customize the IDE
Look and feel
General environment
Dockable windows
Component Palette
Load preset keymaps
Rename classes and packages by using refactoring.
JDeveloper Coding Features
Customizing the IDE
You can customize JDevelopers default display options (such as, whether or not the splash
screen is displayed at start up, or whether dockable windows are always on top), as well as
other general behavior (such as, whether JDeveloper will automatically reload externally
modified files and whether output to the Log window is automatically saved to a file).
Customize the general environment for the IDE.
Customize dockable windows for the IDE.
Customize the Component Palette.
Load preset keymaps and customize individual accelerators. (You can take advantage
of the several existing keymap sets in JDeveloper or begin with an existing keymap
and then customize it to suit your own coding style by changing which keyboard
shortcuts, or accelerators, map to which actions.)
Customize options for the Code Editor.
Add external tools to JDeveloper.
Refactoring
Refactoring is the process of improving an application by reorganizing its internal structure
without changing its external behavior. When you refactor an application, you may want to
move or rename individual classes, or move groups of classes to a different package. In
JDeveloper, you can make these changes without breaking any dependent files on which
your project relies, as these files are automatically updated for you.
Oracle10g: Java Programming 6-18
Copyright 2004, Oracle. All rights reserved.
Using the Help System
Using the Help System
JDeveloper is a comprehensive development tool and provides many features that help you
develop Java code quickly and effectively.
The JDeveloper Help System
To make the best use of the tools, the libraries, and the Java language itself, JDeveloper
provides a comprehensive Help system that covers all aspects of Java development.
Select Help > Help Topics in the main menu to launch the Help system:
From the browser, select one of the topics from the contents hierarchy at the left of
the window. After you select a topic, the topic expands to display subtopics.
Select the topic you are interested in and right-click it, to display the Help text in a
window.
Use hypertext links to navigate within a topic or to related topics.
Oracle10g: Java Programming 6-19
Copyright 2004, Oracle. All rights reserved.
Obtaining Help on a Topic
Use [F1] to invoke
context-specific Help.
Obtaining Help on a Topic
Pressing the [F1] key invokes a context-sensitive Help topic window.
Javadoc
Javadoc is a tool that parses the declarations and documentation comments in a set of
source files and produces a set of HTML pages describing the classes, inner classes,
interfaces, constructors, methods, and fields.
When working in the Java Code Editor, you can quickly access the specific Javadoc entry
for any element in the source file. To browse the specific Javadoc entry for a given class,
member, or method: Select the appropriate code element, right-click, and choose Quick
Javadoc. A pop-up window with Javadoc for just that element now appears.
Oracle10g: Java Programming 6-20
Copyright 2004, Oracle. All rights reserved.
Oracle JDeveloper 10g Debugger
Helps find and fix program errors:
Run-time errors
Logic errors
Allows control of execution
Allows examination of variables
Debugging
Debugging is the process of looking for program errors that keep your program from doing
what you intended. There are two basic types of program errors: run-time errors and logic
errors. Remember that the compiler catches any syntax problems.
If your program successfully compiles but gives run-time exceptions or hangs, then you
have a run-time error. That is, your program contains valid statements but is encountering
errors when they are executed. For example, you may be trying to open a file that does not
exist or you may be trying to divide by zero.
Logic errors are errors in the design and implementation of your program. That is, your
program statements are valid and do something, but the results are not what you intended.
These types of errors are usually the most difficult to find.
The debugger enables you to control the execution of your program. It provides the ability
to execute parts of the code step-by-step. You can also set breakpoints that pause the
program execution when it reaches the line of code you want to examine.
While the program is paused, you can inspect and even modify program variables. This
helps you examine loops and other control structures to make sure that what is happening is
what you intended.
Oracle10g: Java Programming 6-21
Debugging (continued)
Breakpoints
Breakpoints are a convenient way of tracing the cause of a problem in a program. When the
debugger encounters a breakpoint, it pauses the program execution. You can resume
execution, stepping through the code line-by-line, examining variables and conditions, or
stop the program. You can set as many breakpoints as you want.
Oracle10g: Java Programming 6-22
Copyright 2004, Oracle. All rights reserved.
Setting Breakpoints
Setting breakpoints:
Manage multiple breakpoints
Manage conditional breakpoints
Define columns displayed in window
Description
Type
Status, and so on
Control scope of action
Global > Workspace > Project
Breakpoints
Setting Breakpoints
Set a breakpoint by selecting a line of code in the source code window, right-click and
select Toggle Breakpoint. You can click in the left margin to set a new breakpoint. After
you start debugging, breakpoints that are known to be valid will have a check mark in the
breakpoint icon. A breakpoint without a check mark may mean that this line does not
represent code where the debugger can stop, but it may just mean that the debugger does
not know yet whether the breakpoint is valid or invalid.
Viewing Breakpoints
To view all the currently enabled breakpoints, select View > Breakpoints from the menu
bar. A window showing all the breakpoints set in the program appears. To disable or
remove a breakpoint, right-click the breakpoint, and select an action from the menu.
Conditional Breakpoints
To set the conditions on which you want a breakpoint to be activated, right-click a
breakpoint, and select Edit Breakpoint. In the Breakpoint Conditions tab, you can specify
information about how and when the breakpoint is activated including valid Java
conditional statements and thread-specific conditions.
Oracle10g: Java Programming 6-23
Breakpoints (continued)
Display Settings
To select which columns are displayed in the breakpoints window, right-click in the
breakpoints window and select Settings. In the dialog box, select Debugger > Breakpoints
in the navigator tree on the left, and select the columns to display.
Scope Settings
To select the scope for the debugging, right-click in the breakpoints window, select Change
Scope, and select the appropriate value.
Oracle10g: Java Programming 6-24
Copyright 2004, Oracle. All rights reserved.
Using the Debugger Windows
View Debug information:
Classes: Displays list of loaded classes and status
Watch: Evaluates and displays expressions
Monitors: Displays information about active
monitors
Threads: Displays the names and statuses of all
threads
Smart Data: Analyzes source code near execution
point
and more
Debugging a Java Application
Make sure that the project is selected, and click the Debug icon. Alternatively, from the
Menu bar you can select Debug > Debug <Project Name>.jpr. This causes any files to be
compiled if necessary and then starts your program in debug mode.
Debugging Windows
As soon as you start the debugger, three tabs are added to a new window at the bottom right
side of JDeveloper: the Smart Data tab, the Data tab, and the Watch tab. A new tab is added
to the existing message window. This tab enables you to monitor the code as it executes.
Fields for each window can be modified in the Tools > Preferences menu, in the Debugger
node.
Smart Data tab: Displays only the data that appears to be relevant to the source code
you are stepping through
Data tab: Displays all the arguments, local variables, and static fields for the current
method
Watch tab: Displays the current value of an expression that you have flagged to be
displayed during the execution of the program
Remote Debugging
You may manually launch the program you want to debug, then start the debugger. In the
Host list, select the name of the machine where the program has been started. After the
debugger is attached to the running program, remote debugging is similar to local
debugging.
Oracle10g: Java Programming 6-25
Copyright 2004, Oracle. All rights reserved.
Stepping Through a Program
Step through a program by using the buttons on the
Debugger toolbar:
Start the debugger.
Resume the program.
Step over a method call.
Step into a method call.
Step out of a method call.
Step to the end of the method.
Pause execution.
Stop the debugger.
Step Through a Program
Start the debugger: Executes the program in debug mode. The program will be
paused when it encounters a breakpoint. If no breakpoints have been set, you can
pause program by using the Pause execution button.
Resume the program: Resumes the program after stopping at a breakpoint
Step over a method call: Executes the method at the current position in the program
at full speed rather than tracing into the method line-by-line
Step into a method call: Traces into a method line-by-line. This is useful when you
suspect that the method may be the one that is causing the problem.
Step out of a method call: Enables you to step out of the current method and return
to the next instruction of the calling method
Step to the end of the method: Jumps to the end of the method
Pause execution: Pauses a running program at its current position
Stop the debugger: Stops the execution of a running program. This is a useful way of
killing the program.
Oracle10g: Java Programming 6-26
Copyright 2004, Oracle. All rights reserved.
Watching Data and Variables
The Smart Data tab displays analyzed variables
and fields.
The Data tab displays arguments, local variables,
and static fields from the current context.
To watch other variables:
Select a variable in the source window and right-
click.
Select Watch... at Cursor from the context menu.
View the variable in the Watch tab.
Right-click a data item to modify it.
Watching Data and Variables
Viewing Analyzed Data in the Smart Data Tab
The debugger analyzes the source code near the execution point looking for variables and
fields expressions that are used in the lines of code. By default, the debugger analyzes only
one line of code for each location.
Viewing Local Variables in the Data Tab
The Data tab is the lower window that is displayed when you select the Debug tab at the
bottom of System Navigator. The Data tab automatically displays a list of local variables,
static fields and arguments that are in scope. As you jump from one method to the next, the
list of variables displayed in the Data tab changes.
Selecting Other Variables and Expressions to Watch
Other variables and expressions can be viewed by following the steps described in the
slide. Select a variable or expression such as age+10. Right-click the variable or
expression and select Watchat Cursor from the context menu. A dialog box appears
displaying the selected variable or expression; click OK to accept it and add it to the Watch
tabbed page. View the variables you have selected to monitor in the Watch tabbed page. To
modify a data value, right-click it and select Modify Value from the context menu.
Oracle10g: Java Programming 6-27
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how:
JDeveloper builds, debugs, and runs all types of
Java applications
JDeveloper can be used to develop:
Java applications
Java servlets
JSPs
EJBs
JDeveloper can be used to build enterprise
applications
Additional Reading
You can find out more about the features of JDeveloper on the Oracle Technology
Network, http://otn.oracle.com. The following are some examples of the topics covered:
Overview
Overview of JDeveloper, The JDev IDE, Creating a BC4J Application, Java Concepts in
JDeveloper, Naming Conventions, Debugging the Code, Deployment Alternatives
ADF Application Development Framework
Reduces the Complexity of J2EE Development by providing Visual and Declarative
Development, Increases Development Productivity, Encourages J2EE Best Practices by
Implementing Standard J2EE Design PatternsMVC, Provides a Flexible and Extensible
Environment by allowing Multiple Technology Choices and Development Styles
JSPs
JSP Overview, Creating JSPs, JSP Components
Advanced Topics
HTML in JDev Environment, JavaScript in JDev Environment, Customizing & Extending
the IDE, Overview of the Class Modeler, Overview of the Activity Modeler, Security
Oracle10g: Java Programming 6-28
Copyright 2004, Oracle. All rights reserved.
Practice 6: Overview
This practice covers:
Exploring the Oracle JDeveloper 10g IDE
Creating a workspace and project
Including application files from the earlier lesson
Practice 6: Overview
Note: In this practice, you use the E:\labs\les06 directory.
The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and
structure of the Java language. Their sole purpose is to instruct and is not intended to reflect
any set of application development best practices.
The purpose of the practices from lesson 6 to the end of the course is different. Starting in
lesson 6, you use JDeveloper to build an application employing techniques you will use
during real-world development. The practices continue to support the technical material
presented in the lesson, while incorporating some best practices you will use while
developing a Java application.
In the Applications Navigator node, expand the OrderEntryWorkspaceLes<nn>
OrderEntryProjectLes<nn> - Application Sources oe, and
double-click the UML Class Diagram1 entry. This diagram displays all the classes
created to this point in the course.
Oracle10g: Java Programming 6-29
Practice 6: Building Java by Using Oracle JDeveloper 10g
Goal
In this practice, you explore using the Oracle JDeveloper 10g IDE to create a workspace
and a project, so that you manage your Java files more easily during the development
process. You practice how to use the rapid code generation features, such as the text Code
Editor and debugger. You practice how to create one or more Java applications and classes
by using the rapid code generation features, such as the text Code Editor and debugger.
More importantly, you now start using JDeveloper for most of the remaining lab work for
this course (occasionally returning to the command line for various tasks). By the end of
the course, you will have built and deployed the course GUI application while continuing
to develop your Java and JDeveloper skills.
Note: In this practice, you use the files found in the E:\labs\les06 directory. They
are similar to the ones you created in earlier practices, with subtle differences and the
introduction of a class to manage the data, named DataMan. This file will be used in later
labs.
Your Assignment
In part 1, you explore JDeveloper default rapid code generation features by creating a
new default workspace using the default JDeveloper paths, and then create a default
project from an existing code in the E:\labs\les06 directory.
In the extra credit section, you run and test the application using the debugger.
Create a Workspace and Project
Launch Oracle JDeveloper 10g from the desktop icon provided, or ask your instructor for
instructions on how to start JDeveloper. In this practice, you must use the E:\labs\les06
directory.
1. Create a new Workspace and a new Project.
a. Select File > New to invoke the JDeveloper New Gallery window. This a
launching point for creating all your Java source code. The New Gallery
window is divided into two columns, Categories and Items. The list of items
available depend on the category selected.
b. The General category is selected by default the first time New is selected. If it
is not highlighted, select it now. Then, either double-click the Workspace item
(or click Workspace and then click the OK button).
c. Change the workspace directory name field to E:\labs\les06.
You can use the Browse button to locate the directory, if desired.
d. Enter the following workspace file name: OrderEntryWorkspace.jws.
e. Note: Clear the Add New Empty Project check box. Click the OK button, and
save your workspace.
2. Create a new project called OrderEntryProject.jpr in the new workspace,
and populate the project with files existing in E:\labs\les06\src\oe
directory.
a. Right-click the OrderEntryWorkspace.jws workspace, and select the
New Project menu item. Then double-click the Project from Existing
Source entry in the items of the New Gallery window.
Oracle10g: Java Programming 6-30
Practice 6: Building Java by Using Oracle JDeveloper 10g (continued)
b. Click the Next button on the Welcome screen. In Project with
Existing Source Wizard Location, change the Project Name to
OrderEntryProject and select the E:\labs\les06 directory. Then,
click the Next button.
c. In Project with Existing Source Wizard - Add Source
Files and Directories, click the Add button. Navigate to the
subdirectory containing the Java source files, which are in the src\oe
subdirectory of the E:\labs\les06 directory tree.
d. Select all the .java files in the E:\labs\les06\src\oe directory, and
click the Open button. The wizard displays the selected files under the Refine
Files to Be Added list. Click the Next button.
e. In Project with Existing Source Wizard - Source Paths,
confirm the Output Directory is E:\labs\les06\classes, and leave the
HTML Root field empty. Then click the Next button.
f. In Project with Existing Source Wizard - Run Settings,
select the file OrderEntry.java, under the E:\labs\les06\src\oe
directory as the Main Entry Point. Then click the Next button.
g. In Project with Existing Source Wizard Finish, click the
Finish button.
h. Double-click the OrderEntryProject and select the Input Path node. Set
the Default Package to oe.
i. Save all your work. Then compile the files in the project. Right-click
OrderEntryProject, and select the Rebuild Project menu option. (Or, use
the Project > Rebuild OrderEntryProject.jpr menu item). Pay
attention to the compilation progress in the Log window.
j. Select the Run > Run OrderEntryProject.jpr menu item to run the
default application, or right-click the OrderEntry.java file and select Run
OrderEntry.java from the context menu. View the output results of your
application in the Log window.
Optional Extra Credit
Debugging the Course Application
In this part of the practice, you run the application in debug mode, and examine how the
debugger works.
3. Run the OrderEntry application in debug mode.
a. Open Order.java file in the Code Editor by double-clicking the file name, or
right-clicking the file name and choosing Code Editor from the context menu.
b. Remove the comments lines from the System.out.println, and set
breakpoints on the following two statements:
item1Total = item1.getItemTotal();
...
and
System.out.println("Item 2 Total: " + item2Total);
Note: To set the breakpoint on this line, click the line number in the margin.
Oracle10g: Java Programming 6-31
Practice 6: Building Java by Using Oracle JDeveloper 10g (continued)
c. In the Navigator, select the OrderEntry.java file, right-click and select
Debug from the context menu.
JDeveloper creates a new debugger tabbed page that opens at the bottom right
of the JDeveloper window. The execution of the code stops at your first
breakpoint, as indicated by a red arrow. The red arrow indicates the next line
that is about to be executed when you resume debugging.
The Log/Debug window is modified to contain two tabsa Log tab and a
Breakpoints tabin which you can view all the breakpoints you have set. The
Log tab must display the output results generated by the application. Resize the
windows, if required.
d. Visually select the Smart Data tab in the bottom right window, known as the
Debug window.
Note: If the Debug window is not visible, display it by selecting the View >
Debug Windows > Smart Data menu item. The check box next to the Data item
must be selected to make it visible; otherwise, the tab will be removed from the
Debug window displayed.
e. Locate the item1 variable in the Smart Data tabbed page and expand it. Using
the values of quantity and unitPrice, calculate the item1Total of the
order. What is its present value of item1Total?
(Hint: The value for quantity was displayed as 2 and the value for unitPrice was
displayed as 2.95.) But the value item1Total was showing out of scope in the
Smart Data window
f. Select the Debug > Step Over menu item (alternatively, press [F8] or click the
appropriate toolbar icon) to calculate the item1Total. Note the changes to
the item1Total instance variable in the Smart Data tabbed page of the
Debug window. Was your calculation in the previous step correct?
g. In the top toolbar, press the Resume [F9] button (or select the Debug > Resume
menu item). The red arrow in the Code Editor advances and highlights the line
with the next breakpoint detected in the code execution sequence.
h. Continue by selecting the Debug|Resume menu (F9 key, or click the toolbar
button) until the program is completed. You need to click it only once.
i. Remove the breakpoints from the Order.java source by clicking each
breakpoint entry (red dot) in the margin for each line with a breakpoint.
Copyright 2004, Oracle. All rights reserved.
Creating Classes and Objects
Oracle10g: Java Programming 7-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Define instance variables and methods
Define the no-arg (default) constructor method
Instantiate classes and call instance methods
Perform encapsulation by using packages to
group related classes
Control access with public and private access
modifiers
Use class variables and methods
Lesson Aim
This lesson shows you how to create a new class definition using Oracle JDeveloper. You
define instance variables and methods for the class. The lesson also shows how to create
objects using new, basic object initialization and how to manipulate the objects using
instance methods.
Oracle10g: Java Programming 7-3
Lesson Aim (continued)
Class Definitions
Java is an object-oriented programming language. All the data or attributes and behavior of
objects are defined within classes. You use classes for everything you do in Java.
Code
Object orientation is about modeling real-world objects or concepts in software. Java forces
you to think in an object-oriented way, because every piece of Java code must live in a class
definition. There are no global functions defined outside the scope of a class.
Data
Java uses variables to store information about an object. The variables can store primitive
values or references to other objects. Variables also are defined only within classes.
Packages
Packages group logically related classes by application and provide access control. Java uses
packages to control which classes can be seen and accessed by classes outside of the
package.
Oracle10g: Java Programming 7-4
Copyright 2004, Oracle. All rights reserved.
Using Java Classes
Packages
Methods Objects
Object
references
Attributes
Contained in a class
What Is a Class?
A class is a template or blueprint that is used in creating multiple objects. A class
encapsulates all the data and behaviors that make up an object. When you ask Java to create
or instantiate a class, Java uses the class definition as a template for building the new object.
A class contains attributes that are assigned to all new objects of that class. Attributes are the
information or data that describe, classify, categorize, or quantify an object. Each object of a
given class has its own set of the class attributes. For example, an object of the Customer
class may have a name, a billing address, and a telephone number attribute.
Data that is stored in an object can be primitive data types, such as integers or characters, or
references to objects.
A class also contains methods, or functions, that specify the behavior or actions that an
object can perform. For example, a customer may rent a video, make a payment, or change
his or her billing address.
Java uses packages to group classes that are logically related. Packages consist of all the
classes in a subdirectory. They are also used to control access from programs outside of the
package.
Oracle10g: Java Programming 7-5
Copyright 2004, Oracle. All rights reserved.
title: Gone with
rating: PG
title: Last Action
rating: PG-13
Comparing Classes and Objects
An object is an
instance of a
class.
Objects have
their own
memory.
Class definitions
must be loaded
to create
instances.
public void displayDetails()
private String title;
private String rating;
public void setRating()
Movie
mov1 mov2
Classes and Objects
A class is a template for building objects of that class. In object-oriented terminology, an
object is an instance of a class. Each object of that class has the same data structure and
operations. However, the values that are held in this data structure are unique to each object;
these values are therefore called instance variables. The operations of an object act on the
instance variables in that object.
The class contains variables and methods called members. Those members owned by the
class are static members, and those owned by the objects from the class are called
instance members.
In the case of the Movie class, each individual movie is an instance of Movie. Gone with
the Wind is one distinct instance of Movie while Last Action Hero is another. Each has
its own set of variables that are separate and distinct from the variables of any other movie,
or object, of the Movie class.
Each new object is identified within Java by a unique object reference. Java distinguishes
between objects by using this reference. Objects are uniquely identifiable even if all their
properties are the same.
Oracle10g: Java Programming 7-6
Copyright 2004, Oracle. All rights reserved.
Creating Objects
Objects are typically created by using the new
operator:
For example, to create two Movie objects:
Movie mov1 = new Movie("Gone ...");
Movie mov2 = new Movie("Last ...");
ClassName objectRef = new ClassName();
title: Gone with
rating: PG
title: Last Action
rating: PG-13
Creating New Objects
In Java, you can create objects by using the new operator. The new operator creates an
instance of a class and returns the reference of the new object. For example:
Movie mov1 = new Movie();
This statement creates an instance variable of the Movie type named mov1. It then creates
a new instance of Movie by using the new operator and assigns the object reference to the
mov1 instance variable. It is important to remember that the new operator returns a
reference to the new object that points to the location of that object in memory.
Oracle10g: Java Programming 7-7
Copyright 2004, Oracle. All rights reserved.
Using the new Operator
The new operator performs the following actions:
Allocates and initializes memory for the new
object
Calls a special initialization method in the class,
called a constructor
Returns a reference to the new object
Movie mov1 = new Movie("Gone with");
mov1
(When instantiated)
title: Gone with
rating: PG
Anatomy of the new Operator
The new operator performs the following three tasks:
Allocating memory for the new object. It knows how much memory is required by
looking in the class definition to see what instance variables are defined in the class.
Calling a constructor to initialize the instance variables in the new object. A
constructor is a special method that is supplied by the class.
Returning a reference to the newly created object. To refer to this object in the future,
you must store this reference in a variable.
Separating Variable Declaration from Object Creation
The declaration of an object reference and the creation of an object are completely
independent. In the previous examples, these two parts were combined in a single statement:
Movie mov1 = new Movie();
However, you can achieve the same effect with two separate statements, as follows:
Movie mov1; // Declare an object reference,
// capable of referring to a Movie.
mov1 = new Movie(); // Create Movie object, and return the
// reference to the mov1 variable.
Oracle10g: Java Programming 7-8
Copyright 2004, Oracle. All rights reserved.
Comparing Primitives and Objects
Primitive variables
hold a value.
int i;
int j = 3;
Movie mov1 = new Movie();
Object variables
hold references.
title: null
rating: null
mov1
Movie mov1;
mov1
0
3
i
j
null
Primitive Variables and Object Variables
Primitive variables are treated very differently from object variables in Java. It is important
to understand what are the differences.
Primitive Variables
When you declare a primitive variable, Java allocates a chunk of memory to hold a variable
of the specified primitive type. If you define a primitive variable as an instance or a class
variable, then the variable is initialized to 0 if it is a number, false if it is a Boolean, or
\0 if it is a char.
Primitive variables hold their values directlyfor example, if you declare an int variable
and assign it the value 3, then the value is stored directly in the four bytes of the int.
Object Variables
When you declare an object variable, you also receive a chunk of memory, but this memory
is only large enough to hold a reference to an object. You may find it useful to think of a
reference as a pointer to an object.
As mentioned previously, declaring an object variable does not create an object of the
specified class. Consequently, an object instance variable is initialized to null to indicate
that it does not yet refer to any object. Use the assignment operator to make an object
variable refer to an object. The assignment can be to an existing object or a new object by
using the new operator.
Oracle10g: Java Programming 7-9
Copyright 2004, Oracle. All rights reserved.
Using the null Reference
A special null value may be assigned to an object
reference, but not to a primitive.
You can compare object references to null.
You can remove the association to an object by
setting the object reference to null.
Movie mov1; //Declare object reference

if (mov1 == null) //Ref not initialized?
mov1 = new Movie(); //Create a Movie object

mov1 = null; //Forget the Movie object
More About null
Consider the following statement:
Movie mov1 = null;
This declares a variable called mov1 with a special reference called null. This indicates
that the reference does not refer to a real object yet.
Checking Object References Against null
null is a keyword in the Java language. You can use it with the equality operator to check
whether an object reference has been initialized or not:
if (mov1 == null) {
// The mov1 variable has not been initialized,
// so do something to initialize it
}
Discarding an Object
When you have finished using an object, you can set its object reference to null. This
indicates that the variable no longer refers to the object. When there are no more live
references to an object, the object will be marked for garbage collection.
The Java Virtual Machine (JVM) automatically decrements the number of active references
to an object whenever an object is dereferenced, goes out of scope, or the stored reference is
replaced by another reference.
Oracle10g: Java Programming 7-10
Copyright 2004, Oracle. All rights reserved.
Assigning References
Assigning one reference to another results in two
references to the same object:
Movie mov1 = new Movie("Gone...");
mov1
Movie mov2 = mov1;
mov2
title: Gone with
rating: PG
Different Object References Can Refer to the Same Object
As previously mentioned, when you declare an object reference variable, it is initialized to
null. Before you can use that variable, you must initialize it; typically, you initialize it
with a reference to a new object by using the following syntax:
Movie mov1 = new Movie();
However, it is also possible to initialize an object reference to an existing object as follows:
Movie mov2 = mov1;
This is perfectly legal Java syntax, but there is still only one Movie object. When you
assign one object reference to another object reference, you end up with two references to
the same object, not a copy of the other object.
The Object Can Be Accessed Through Either Reference
You can access the same object through either reference; however, there is still only one
object.
You can change either reference to refer to a different object without affecting the other
reference. However, if you really need a separate object, rather than multiple references to a
single object, then you must create a new object.
Oracle10g: Java Programming 7-11
Copyright 2004, Oracle. All rights reserved.
title: null
rating: null
title: null
rating: null
Declaring Instance Variables
Instance variables are declared within the class, but
outside the methods or instance or static intializers.
public class Movie {
public String title;
public String rating;
public float getPrice(){
return price;
}
}
Movie mov1 = new Movie();
Movie mov2 = new Movie();
mov2
mov1
Create movies:
Declaring Instance Variables
Instance variables must be declared within the class definition. In this example, these
instance variables have been declared as public to allow users of the class to access them
directly. Although this is not a good practice, it is done here to keep the example simple.
Declaring instance variables as public is a violation of encapsulation; after you have seen
how to write instance methods, the instance variables will be made private to prevent
them from being manipulated directly by users of the class.
What Does an Object Look Like?
The example creates two instances of the Movie class. To put it in another way, two
Movie objects have been created: the first Movie object is referenced by mov1, and the
second Movie object is referenced by mov2.
Although these two Movie objects are completely independent, they have an identical data
structure. In other words, each object has its own separate and distinct copies of the instance
variables that you declared in the Movie class.
Oracle10g: Java Programming 7-12
Copyright 2004, Oracle. All rights reserved.
Accessing public Instance Variables
public instance variables can be accessed by using
the dot operator:
public class Movie {
public String title;
public String rating;

}
Movie mov1 = new Movie();
mov1.title = "Gone ...";

if (mov1.title.equals("Gone ... ") )
mov1.rating = "PG";
Accessing public Instance Variables
The example shows how to access public instance variables in an object using the dot
operator. This operator takes an object reference on the left and the name of an instance
variable on the right:
objectRef.instanceVarName
Remember that this syntax is allowed only if the instance variable has been declared as
public. In a fully encapsulated object, where the instance variables are private, the
only way to change the state of an object is by calling a suitable instance method on the
object. By exposing the variables as public, anyone using your class can manipulate
instance data without validation or control.
Users can set the rating to anything they want, regardless of business rules governing that
data.
Note: equals(...) compares object types.
Oracle10g: Java Programming 7-13
Copyright 2004, Oracle. All rights reserved.
Defining Methods
A method in Java is equivalent to a function or
subroutine in other languages.
modifier returnType methodName (argumentList) {
// method body

};
Methods
When you define a class for an object-oriented program, you implement all of the behavior
of that class in one or more methods. A Java method is equivalent to a function, procedure,
or subroutine in other languages, except that it must be defined inside a class definition. In
other words, there is no support for global methods in Java; every method must be defined
within a class.
Anatomy of an Instance Method
The key components of an instance method are:
A modifier, such as public or private. If you specify an instance method as
public, then it can be called from anywhere in the program. If you specify a method
as private, then it can be invoked only by other methods in the same class. If no
modifier is specified, then the method can be invoked by any method in any class in
the same package. An instance method may also have a protected or a default modifier.
A return type. This can be a primitive type, such as int, a class type such as String,
or the void keyword, if the method does not return a value.
The name of the method. A Java naming convention expects method names to begin
with a lowercase letter. Compound words in the method name must begin with an
uppercase character.
An optional argument list inside parentheses, separated by commas. If the method does
not take any arguments, then simply leave the parentheses empty.
The method body enclosed in braces
Oracle10g: Java Programming 7-14
Copyright 2004, Oracle. All rights reserved.
Calling a Method
Objects communicate by using messages:
All methods are defined within a class and are not
defined globally as in traditional languages.
When you call a method, it is always in the context
of a particular object.
myPen.write( ): Object-oriented programming
Write (myPen): Traditional structured
programming
Objects Must Associate with Each Other
Objects must associate with other objects to enable messages to be sent. To send a particular
message, an object must know the recipient of the message. This visibility may be achieved
dynamically and transiently, or an object can remember another object through a
reference. (To be pedantic, two classes may associate with each other, and two objects may
have a link between them.)
A link is simply a relationship between objects. In programming terms, it may be
implemented in various waysfor example, a variable in one object containing a reference
to the other object.
Oracle10g: Java Programming 7-15
Copyright 2004, Oracle. All rights reserved.
Specifying Method Arguments: Examples
Specify the number and type of arguments in the
method definition:
If the method takes no arguments, then leave the
parentheses empty:
public void displayDetails() {
System.out.println("Title is " + title);
System.out.println("Rating is " + rating);
}
public void setRating(String newRating) {
rating = newRating;
}
Specifying Method Arguments or Signature
A method can have zero or more arguments, also known as parameters; this is called the
method signature. When you define a method in a class definition, you specify its formal
arguments in an argument list. Each formal argument is a placeholder for a variable of some
type, either a primitive or an object reference. Like any other variable, each argument must
be declared in terms of its type, such as String, and a name, such as title.
Specifying Multiple Arguments
If a method has multiple arguments, then each declaration must be separated by commas, as
in the following example:
public void setMovieDetails(String pTitle, String pRating) {
title = pTitle;
rating = pRating;

}
Specifying No Arguments
If a method has no arguments, then simply leave the parentheses empty in the definition.
Oracle10g: Java Programming 7-16
Copyright 2004, Oracle. All rights reserved.
Returning a Value from a Method
Use a return statement to exit a method and to
return a value from a method:
If the return type is void, then no return is needed.
You can use a return without a value to terminate
a method with a void return type.
public class Movie {
private String rating;

public String getRating () {
return rating
}
}
Returning a Value from a Method
A method can return a single value or expression to a caller of that method. If so, then it
must be defined with a return type such as int in front of the method name, as follows:
public int getLength() {

}
Methods are also allowed to return a reference to an object; this can be useful if you want to
return more than one value. Here is a method that returns a reference to a String object:
public String getRating() {

}
The return Statement
A return statement is the mechanism by which methods pass the required value back to
the calling method. A return statement takes a single value or expression, which must be
compatible with the return type that is specified at the beginning of the method.
When a return statement is encountered, the method exits immediately, and ignores any
statements that lie between the return statement and the closing brace of the method. This
can be used for void methods that have no return value or to exit the function immediately:
return; // Use this syntax to return void from a method
Oracle10g: Java Programming 7-17
Copyright 2004, Oracle. All rights reserved.
Calling Instance Methods
public class Movie {
private String title, rating;
public String getRating(){
return rating;
}
public void setRating(String newRating){
rating = newRating;
}
}
Movie mov1 = new Movie();
String r = mov1.getRating();
if (r.equals("G")) Use the dot
operator:
Use the dot Operator to Call an Instance Method
As with instance variables, you can use the dot operator to call an instance method on an
object. The general syntax is as follows:
objectRef.methodName(arguments );
If the method takes no arguments, then you still have to include the parentheses when you
call the method, but you leave them empty:
objectRef.methodName(); // Call method that takes no args
Example
In the example, two instance methods in the Movie class are defined: getRating() and
setRating(). You then create a Movie object and check its rating by using
getRating():
if ( mov1.getRating.equals("G") )
If necessary, the movie rating can be reset by using setRating():
mov1.setRating("PG");
Oracle10g: Java Programming 7-18
Copyright 2004, Oracle. All rights reserved.
Applying Encapsulation in Java
Instance variables must be
declared as private.
Only instance methods can access
private instance variables.
private decouples the interface
of the class from its internal operation.
Movie mov1 = new Movie();
String rating = mov1.getRating();
String r = mov1.rating; // error: private
...
if (rating.equals("G"))
var
aMethod
aMethod()
Encapsulation
Encapsulation is a key concept in object-oriented programming. A well-defined class must
decouple its public interface from its internal implementation. To achieve this, all instance
variables of a class must be made private to hide them from users of the class. Only the
instance methods of a class can access the private instance variables of that class.
Users of the class must invoke one of the public methods of the class to access (get) or
change (set) the state of an object. For example, if the Movie class is properly encapsulated,
then it is impossible for a user of the Movie class to directly access instance variables such
as title and rating.
The Benefits of Encapsulation
As a class evolves, there is every chance that you will need to modify the way in which the
class is implemented internally. However, as long as you preserve the same interface to the
class, the rest of the program will not need to be modified at all. You preserve the interface
by retaining the same public instance methods with exactly the same signatures or
parameter lists.
By maintaining this encapsulation, you will not break any existing code that uses the Movie
class.
Oracle10g: Java Programming 7-19
Copyright 2004, Oracle. All rights reserved.
Passing Primitives into Methods
When a primitive or object reference value is passed
into a method, a copy of the value is generated:
public void aMethod(int arg) {
if (arg < 0 || arg > 100)
arg = 0;
System.out.println("arg: " + arg);
}
int num = 150;
anObj.aMethod(num);
System.out.println("num: " + num);
arg
150
num
150
Passing Primitives into a Method
When a primitive value is passed into a method, a copy of its value is passed into the method
argument. If the method changes the value of the argument in any way, then only the local
argument is affected. When the method terminates, this local argument is discarded, and the
original variable in the calling method is left unchanged.
Example
The example in the slide illustrates the way in which primitive variables are passed by
value into methods. The code on the left declares an int variable called num and assigns it
the value 150. When num is passed into aMethod(), a copy of its current value is passed
into the method argument, which you have called arg; arg will be 150 initially.
Inside aMethod(), arg is reset to 0. However, when aMethod() terminates, arg is
discarded and you return to the calling method, where num still has the value of 150.
Therefore, this example prints out the following messages:
arg: 0
num: 150
Oracle10g: Java Programming 7-20
Copyright 2004, Oracle. All rights reserved.
title: Gone with
rating: PG
Passing Object References into Methods
When an object reference is passed into a method, the
object is not copied but the pointer to the object is
copied:
public void aMethod(Movie ref2) {
ref2.setRating("R");
}
mov1
ref2
Movie mov1 =
new Movie("Gone");
mov1.setRating("PG");
anObj.aMethod(mov1);
Passing Object References into Methods
When an object reference is passed to a method, a copy of the passed reference is generated,
which refers to the original object. The reference contains the address where the object is
located in memory. Any changes that the method makes to the argument will change the
original object. When the method terminates, any changes that you have made to the object
during the method remain in force.
Example
The example in the slide illustrates the way in which objects are passed by reference into
methods. The code on the left creates a new Movie object and stores a reference to it in
mov1. The movie rating is then set to "PG".
When mov1 is passed into aMethod(), the method receives a reference to the original
Movie object. Inside aMethod(), the movie rating is changed to "R".
When aMethod() terminates, the original Movie object that is referred to by mov1 has a
rating of "R", not "PG".
Oracle10g: Java Programming 7-21
Copyright 2004, Oracle. All rights reserved.
What Are Class Variables?
Class variables:
Belong to a class and are common to all instances
of that class
Are declared as static in class definitions
public class Movie {
private static double minPrice; // class var
private String title, rating; // inst vars
Movie class variable Movie objects
title
rating
title
rating
title
rating
min
Price
Class Variables
A class variable, which is also called a static variable, is a variable that belongs to a class
and is common to all instances of that class. In other words, there is only one instance of a
class variable, no matter how many instances of that class exist.
Defining Class Variables in Java
In Java, you declare class variables by using the static keyword. In the example,
minPrice has been declared as a class variable, because the minimum price is the same
for all Movie objects. Notice that minPrice has been declared private, because it
must be be accessed only by methods of the Movie class.
In this example, the minPrice is the same for all movies, regardless of title or rating.
Oracle10g: Java Programming 7-22
Copyright 2004, Oracle. All rights reserved.
Initializing Class Variables
Class variables can be initialized at declaration.
Initialization takes place when the class is loaded.
Use a static initializer block for complex
initialization.
All class variables are initialized implicitly to
default values depending on data type.
public class Movie {
private static double minPrice = 1.29;
private String title, rating;
private int length = 0;
When Do Class Variables Get Initialized?
Class variables are initialized when the class is loaded. Do not initialize class variables in a
constructor; constructors are for initializing instance variables, not class variables.
Default Initialization of Class Variables
Class variables have the same default values as instance variables: numbers are set to 0,
boolean variables are set to false, characters are set to '\u0000', and references are
set to null.
Explicit Initialization of Class Variables
Class variables can be initialized with nondefault values, just like instance variables. For
example, the minPrice variable in the slide has been set to 1.29.
Complex Initialization of Class Variables
Complex initialization of class variables is performed in a static initialization block, or
static initializer. A static initializer is not named, has no return value, and begins with the
static keyword, followed by a block of code inside braces. It is similar to a constructor
except that it executes only once and does not depend on any instance of the class.
public class Movie {
private static double minPrice;
static {
Date todaysDate = new Date();
minPrice = getMinPrice(todaysDate);
}
Oracle10g: Java Programming 7-23
Copyright 2004, Oracle. All rights reserved.
What Are Class Methods?
Class methods are:
Shared by all instances
Useful for manipulating class variables
Declared as static
A class method is called by using the name of the
class or an object reference.
public static void increaseMinPrice(double inc) {
minPrice += inc;
}
Movie.increaseMinPrice(.50);
mov1.increaseMinPrice(.50);
Class Methods
A class method, which is also called a static method, is a method that belongs to a class
and is shared by all instances of that class. Unlike an instance method, a class method does
not operate on a single object, and so it does not have a this reference. A class method can
access only the class variables and class methods of its class.
Why Use Class Methods?
Class methods are an ideal way to access class variables. In fact, they are the only way if no
instances of the class currently exist. For example, the increaseMinPrice() method in
the slide changes the minimum price of all movies, currently instantiated or not.
How Do You Call a Class Method?
Class methods are called by using the following general syntax:
ClassName.classMethodName( argumentList );
You can also call class methods by using an object reference before the dot, rather than the
name of the class, but the method can still access only class variables and class methods.
Static Methods
You may want to create a method that is used outside of any instance context. Declare a
method to be static, which may only call other static methods directly. Static methods may
not refer to their superclass or its methods.
Oracle10g: Java Programming 7-24
Copyright 2004, Oracle. All rights reserved.
Guided Practice: Class Methods
or Instance Methods
public class Movie {
private static float price = 3.50f;
private String rating;

public static void setPrice(float newPrice) {
price = newPrice;
}
public String getRating() {
return String;
}
}
Movie.setPrice(3.98f); Movie
mov1 = new Movie();
mov1.setPrice(3.98f);
String a = Movie.getRating();
String b = mov1.getRating();
Legal or not?
Class Methods or Instance Methods
Describe the definition of the Movie class in the slide. Then, take a look at the test code,
where a Movie object is created and various methods are called.
Explain the Movie class and the code that uses it. Which statements are legal, and which
are illegal? Why or why not?
Oracle10g: Java Programming 7-25
Copyright 2004, Oracle. All rights reserved.
Examples in Java
Examples of static methods and variables:
main()
Math.sqrt()
System.out.println()
public class MyClass {
public static void main(String[] args) {
double num, root;

root = Math.sqrt(num);
System.out.println("Root is " + root);
}
main() Is a Static Method
When you run a Java application, the virtual machine locates and calls the main() method
of that class. Even though everything in a Java program must be contained within a class,
you need not create an instance of the class if main() just calls class methods. If main()
accesses instance methods or variables of its own class, then it must first instantiate itself:
public class Movie {
public void increaseMinPrice(double increase) { }
public static void main(String[] args) {
Movie myMovie = new Movie();
myMovie.increaseMinPrice(.20);
}
}
Math.sqrt() Is a Static Method
The Math class provides class methods to compute many mathematical functions, such as
trigonometric functions and logarithms. It also provides several class constants such as E
(2.71828) and PI (3.1415926).
What Is System.out.println()?
The System class provides class variables to represent the state of the entire system.
System.out is a class variable that refers to a PrintStream object, which represents
the standard output stream; println() is an instance method of PrintStream.
Oracle10g: Java Programming 7-26
Copyright 2004, Oracle. All rights reserved.
Creating Classes Using the Class Editor
Using JDevelopers Class Editor
JDeveloper can help you create your classes in the Class Editor. To modify a class, select it,
right-click and select Class Editor.
The Fields tab allows you to add, remove and edit any fields, as well as specify their
scope and type. While adding a new field, you can include the get and set methods, and they
will appear in the Methods tab.
The Methods tab allows for modification of methods, including the scope, type and
parameters.
The Events tab allows the class to fire and listen for a set of standard events, or you to
create and import your own.
Oracle10g: Java Programming 7-27
Copyright 2004, Oracle. All rights reserved.
What Are Java Packages?
oe
Customer Order Util
OrderEntry OrderItem
What Is a Java Package?
A package is a container of classes that are logically related, either by application or
function. A package consists of all the Java classes within a directory on the file system.
Package names are used within a Java run-time environment to manage the uniqueness of
identifiers as well as to control access from other classes. They also help by segmenting
related parts of complex applications into manageable parts.
Namespace
Java Virtual Machine (JVM) uses a construct called namespace to manage identifier names
within a Java program. A namespace is a chunk of memory that is allocated specifically to
manage objects. Objects are placed in specific namespaces depending on the source of the
code. For example, a class that is loaded from a local package is loaded into one namespace,
whereas one loaded from a network source goes into another separate namespace.
Identifier names must be unique within a namespace. Without the internal namespace
construct, identifier names will need to be unique across all Java classes. In other words, if
the J2SE or any other class that you need uses an identifier named count, your program
cannot define a variable named count.
Java uses namespaces to manage the identifier names so that you do not have to worry about
what names are used by other classes. You have to manage uniqueness only within your
program.
Oracle10g: Java Programming 7-28
Copyright 2004, Oracle. All rights reserved.
Grouping Classes in a Package
Include the package keyword followed by the
package name at the top of the Java source file.
Use the dot notation to show the package path.
If you omit the package keyword, then the
compiler places the class in a default unnamed
package.
Use the d flag with the javac compiler to create
the package tree structure relative to the specified
directory.
Running a main() method in a packaged class
requires:
That the CLASSPATH contains the directory having
the root name of the package tree
That the class name must be qualified by its
package name
Using Packages
The package represents the organization of the Java bytecode of classes and interfaces. It is
not the source code organization, which is represented by the .java files. The Java
compiler reads and uses any needed packaged classes that you specify.
Note: The CLASSPATH environmental variable is extremely critical when using packages.
Most run-time problems with code using packages emanate from a missing directory in the
CLASSPATH environment.
When running the Java application, you must include the package name in the command.
c:\>java <package_name>.<class>
c:\>java practice06.MaintainCustomers
If a class is included in a package, then the compiler can be requested to put the class file in
a subdirectory reflecting the package name. To create the package directory names during
compile time, use the d option. For example, if you compile a class called RentItem in a
package called rentals as follows:
javac -d c:\acmevideo RentItem.java
then the class file that is created is called
c:\acmevideo\rentals\RentItem.class
The default behavior for the javac command without the -d option is to put the class file
in the same directory as the source file.
Oracle10g: Java Programming 7-29
Copyright 2004, Oracle. All rights reserved.
Setting the CLASSPATH with Packages
The CLASSPATH includes the directory containing the
top level of the package tree:
Package name .class location
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06
CLASSPATH
Setting the CLASSPATH with Packages
The CLASSPATH must point to the directory above the classes. For example, suppose you
want the Java interpreter to be able to find classes in the package practice06. If the path
to the practice06 classes directory is:
E:\Curriculum\courses\java\les06\practice06
then you would set the CLASSPATH variable from an operating system prompt as follows:
set CLASSPATH=E:\Curriculum\courses\java\les06
After you exit a DOS prompt, the CLASSPATH reverts to the permanent settings. The
CLASSPATH is used by both the compiler and the class loader in the Interpreter (JVM) to
locate, resolve references to class names, and load the classes into memory at run time. The
CLASSPATH can include:
A list of directory names (separated by semicolons in Windows, and colons in UNIX):
- The classes are in a package tree relative to any of the directories in the list.
A .zip or .jar file name that is fully qualified with its path name:
- The classes in these files must be zipped with the path names that are derived
from the directories formed by their package names.
Note: The directory containing the root name of a package tree must be added to the
CLASSPATH. Consider putting the CLASSPATH information in the command window or
even the Java command, rather than hard-coding it in the environment. For example,
java -classpath E:\Curriculum\courses\java\les06
practice06.AddCustomers
Oracle10g: Java Programming 7-30
Copyright 2004, Oracle. All rights reserved.
Access Modifiers
private
protected
acmevideo acmetools
public public
Access Modifiers
Java controls access to variables and methods through the use of access modifiers. The
access modifiers are private, public, protected and default (no
modifier).
The least restrictive access modifier is public. Variables and methods that are declared as
public can be seen and used by any other class.
If an access modifier is not specified, called package access (or default access), then the
variables and methods can be used by any other class within the same package.
The next level of access modifier is protected. Variables and methods that are declared
as protected can be seen from any subclass of that class. They can also be seen from any
class within the package in which they exist.
The most restrictive access modifier is private. A private method or variable cannot
be accessed by any other class. The restriction applies to all other classes and subclasses
regardless of their package.
The final access modifier is default (no modifier). In this modifier, only other
members of the same package can access variables and methods.
Oracle10g: Java Programming 7-31
Access Modifiers (continued)
Variable or Method Visibility
Member Visibility Modifier
Access in order from least restrictive to most restrictive:
Public: All
Protected: Only other members of the same package or from a different package if
inherited (using extends keyword)
Default (no modifier): Only other members of the same package
Private: Only other members of the same class
Examples:
1. A protected double getWage() method is visible in all the classes that are in
the same package as the class in which this method is defined and all subclasses of that
class.
2. The int getCount() method is visible in all the classes that are in the same
package as the class in which this method is defined.
N N N Y Non-Subclass in
Different Package
N N Y Y Subclass in
Different Package
N Y Y Y Any Class in Same
Package
Y Y Y Y Same Class
Private Default
(absent)
Protected Public Accessible to
Oracle10g: Java Programming 7-32
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
A class definition specifies a template for building
objects with identical features, such as instance
variables and methods.
An object is an instance of a particular class.
Create an object by using new.
Manipulate an object by using its public instance
methods.
Summary
Class Definitions
Class definitions serve as templates or blueprints for all objects of that class. The definition
includes all attributes and behaviors for that class. The attributes are called instance
variables and must be declared as private to achieve proper levels of encapsulation. The
behaviors are called instance methods and must be declared as public.
Objects
All objects are instances of a particular class. Objects are created by using the new operator.
If the classes are declared properly, then all object manipulation must occur by the use of
public instance methods.
Oracle10g: Java Programming 7-33
Copyright 2004, Oracle. All rights reserved.
Practice 7: Overview
This practice covers:
Defining new classes
Specifying the classes instance variables and
instance methods
Creating Customer objects in main()
Manipulating Customer objects by using public
instance methods
Practice 7: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les06 directory, load up the
OrderEntryWorkspaceLes06 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes06 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes06 OrderEntryProjectLes06 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 7-34
Practice 7: Creating Classes and Objects
Goal
The goal of this practice is to complete the basic functionality for existing method bodies of
the Customer classes. You then create customer objects, and manipulate them by using
their public instance methods. You display the Customer information back to the JDeveloper
message window.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les06 directory, load the
OrderEntryLes06 workspace, and continue with this practice.
Your Assignment
In this practice, you begin refining the application for the Order Processing business area.
These classes continue to form the basis for the rest of the application that you are building
for the remainder of the course. After creating one or more Customer objects, you
associate a customer with an order.
Refine the Customer class
1. From the Application Navigator pane, in the OrderEntryProject, make the
following changes to the Customer class.
a. Make all instance variables private. To do this, open the Customer.java
file and select the Class tab. This opens the Class Editor. Select the Fields tab,
double-click an attribute name, and click the Scope drop-down list to change the
value to private.
Note: Alternatively, you can also change the scope of the variables in the Source
by modifying the Customer.java file.
b. Using the Code Editor, assign each of the setXXX() methods to its appropriate
field.
c. The get methods must be assigned. Confirm whether the getXXX() methods
return their appropriate field values.
Note: The naming convention, such as setId(), setName(), and so on for these
methods, makes the classes more intuitive and easier to use.
2. At the moment, there is no way to display most or all details for a Customer object
by calling one method.
a. To cover this deficiency, add a new toString() public method to the class,
without arguments, and return a String containing the customers ID, name,
address, and phone number. The resultant string should be a simple
concatenation of the attributes that you want to display. For example:
public String toString() {
return property1 + " " + property2;
}
Note: The toString() method is a special method that is called anytime a String
representation of an object is needed. The toString() method is very useful to add
to any class, and thus it is added to almost all the classes that you create. When adding
the toString method, a pop-up dialog box with this message is displayed: OK to
override method. Click yes.
b. Save the Customer class, and compile it to remove any syntax errors. Compile
by right-clicking the Customer.java file and selecting the Make option.
Oracle10g: Java Programming 7-35
Practice 7: Creating Classes and Objects (continued)
Create Customer Objects (OrderEntry class)
3. Modify the main() method in the OrderEntry class to create two customer
objects.
a. In the main() method of OrderEntry.java, create two customer objects by
using the new operator, assigning each one to a different object reference (use
customer1 and customer2).
b. At the end of the main() method, initialize the state of each Customer object
by calling its public setXXX() methods to set the ID, name, address, and
phone. Use the table data below:
Id Name Address Phone
1Gary Williams Houston, TX 713.555.8765
2Lynn Munsinger Orlando, FL 407.695.2210
c. Print the two customer objects created, under a printed heading of Customers:
by calling the toString() method inside the argument of the
System.out.println() method. For example:
System.out.println("\nCustomers:");
System.out.println(customer1.toString()); ...
Note: Alternatively, you can just print the customer object reference variable
to achieve the same result. For example:
System.out.println(customer1);
This latter technique is a feature of Java that is discussed in a subsequent lesson.
d. Save the OrderEntry class, compile, and run the class to view the results.
Modify OrderEntry to Associate a Customer to an Order
4. In the main() method of the OrderEntry class, associate one of the customer
objects with the order object, and display the order details.
a. Call the setCustomer() method of the order object passing in the object
reference of customer1 (or customer2).
b. After setting the customer, call the showOrder() method of the order object.
c. Save, compile, and run the OrderEntry class.
Copyright 2004, Oracle. All rights reserved.
Object Life Cycle and Inner Classes
Oracle10g: Java Programming 8-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Provide two or more methods with the same name
in a class
Provide one or more constructors for a class
Use initializers to initialize both instance and class
variables
Describe the class loading and initializing
process, and the object life cycle
Define and use inner classes
Lesson Aim
This lesson explores some of the more advanced issues relating to class definitions. You
learn how to provide and use overloaded methods in a class, and how to ensure that the
class and object state is initialized to know values when created. The lesson discusses
replacing and supplementing the default no-arg constructor with alternative constructors.
Oracle10g: Java Programming 8-3
Lesson Aim (continued)
Instance Methods
Instance methods are the foundation of encapsulation and are the key in providing a
consistent interface to the class. Classes that are defined with proper encapsulation
techniques use instance methods to provide class information to the outside world. Without
instance methods, a user can inspect and modify class data directly without any program-
enforced validation.
Overloading
With overloading, a method call can invoke different behaviors depending on the
parameter passed. For example in a Dog class, the smell() method can invoke
completely different behaviors depending on the parameter. If the call is smell(cat),
then the behavior would be incessant barking and howling, whereas the smell(food)
method would invoke salivating and eating or begging.
Overloading is a powerful technique in achieving a uniform appearance of your class to the
outside world.
Constructors
Constructors ensure that regardless of who creates an object, the object has all of the
expected characteristics of the class. Upon creation of an object, the constructor method is
called implicitly, providing a place for initialization routines. This is key in object-oriented
programming, because you do not know exactly who will be creating new objects of your
class.
Garbage Collector
The garbage collector is the process that handles the memory allocation. It is in charge of
cleaning the memory space that is allocated to objects that are not used anymore.
Inner Classes
In releases of the Java language before release 1.1, all top-level classes must be declared as
members of a package. As of Java Development Kit (JDK), release 1.1, this restriction is
removed allowing classes to be declared in any scope. Classes declared inside other classes
are called nested classes, and one common type of nested class is called an inner class.
Oracle10g: Java Programming 8-4
Copyright 2004, Oracle. All rights reserved.
Overloading Methods
Several methods in a class can have the same
name.
The methods must have different signatures.
public class Movie {
public void setPrice() {
price = 3.50F;
}
public void setPrice(float newPrice) {
price = newPrice;
}
}
Movie mov1 = new Movie();
mov1.setPrice();
mov1.setPrice(3.25F);
Method Overloading
Two or more methods in a class can have the same name, provided that they have different
signatures. A method signature is formed from its name, together with the number and
types of its arguments. The method return type is not considered part of the method
signature.
Defining two or more methods with the same name but different signatures is called
method overloading. This technique is useful in presenting a unified interface to the outside
world. The exact method that is called is determined by the parameters that are included in
the call. Without method overloading, each method would require a unique name. For
example, if you want to retrieve customer information by customer ID or by name, then
you would need two methods: getCustomerByID(id) and
getCustomerByName(name). With overloading, you will have two methods named
getCustomer(), one with the ID parameter and the other with the name parameter.
How Does the Compiler Decide Which Overloaded Method to Call?
When a user of a class calls an overloaded method, the compiler chooses the correct
method to call by comparing the argument types that are passed in the call with all the
methods of that name in the class definition. If the compiler cannot find a compatible
match, even after performing possible type conversions, then it flags an error. Likewise, if
more than one match is possible, then the compiler flags an error, because the method call
is ambiguous.
Can Overloaded Methods Differ in Return Type Only?
No. Overloaded methods must be distinguishable by comparing their argument lists alone.
If overloaded methods differ in their return type only, then the compiler flags an error.
Oracle10g: Java Programming 8-5
Copyright 2004, Oracle. All rights reserved.
Using the this Reference
Instance methods receive an argument called this,
which refers to the current object.
public class Movie {
public void setRating(String newRating) {
this.rating = newRating;
}
void anyMethod() {
Movie mov1 = new Movie();
Movie mov2 = new Movie();
mov1.setRating("PG");
title: null
rating: null
mov2
mov1
title : null
rating: PG
this
All Methods Receive a Reference to This Object
All instance methods receive an implicit argument called this, which can be used inside
any method to refer to the current object. The current object is the object on which the
method was called. The this argument is an implicit reference to the calling object and as
such is not required in most cases.
How Is this Used Inside an Instance Method?
Inside an instance method, any unqualified reference to an instance variable or instance
method is implicitly associated with the this reference. For example, the two following
statements are equivalent:
public void setRating(String inRating) {
rating = inRating;
this.rating = inRating;
}
There are two circumstances where you must use an explicit this reference:
When the name of an instance variable is hidden by a formal argument of an instance
method. For example, if there is an instance variable called name, and an argument
that is also called name, then the argument hides the instance variable. Any reference
to name accesses the argument, not the variable. To access the instance variable, you
must use this.name.
When you need to pass a reference to the current object as an argument to another
method
Oracle10g: Java Programming 8-6
Copyright 2004, Oracle. All rights reserved.
Initializing Instance Variables
Instance variables can be explicitly initialized at
declaration.
Initialization happens at object creation.
All instance variables are initialized implicitly to
default values depending on data type.
More complex initialization must be placed in a
constructor.
public class Movie {
private String title;
private String rating = "G";
private int numOfOscars = 0;
Initialization of Instance Variables
When an object is created, Java automatically performs default initialization for all the
instance variables in the object:
char variables are set to '\u0000'.
byte, short, int, and long variables are set to 0.
boolean variables are set to false.
float and double variables are set to 0.0.
Object references are set to null.
Explicit Initialization of Instance Variables
To initialize an instance variable to a nondefault value, you can specify initializers. This
allows instance variables to be assigned an explicit value. For example:
public class Movie {
private String rating = "G";

}
Complex Initialization of Instance Variables
Initializers are fine if you want to assign a simple value to an instance variable, but if you
want to carry out more sophisticated initialization, then you must use a constructor. A
constructor is a special instance method that is used to initialize new instances of a class.
Oracle10g: Java Programming 8-7
Copyright 2004, Oracle. All rights reserved.
What Are Constructors?
For proper initialization, a class must provide a
constructor.
A constructor is called automatically when an
object is created:
It is usually declared public.
It has the same name as the class.
It must not specify a return type.
The compiler supplies a no-arg constructor if and
only if a constructor is not explicitly provided.
If any constructor is explicitly provided, then the
compiler does not generate the no-arg constructor.
Constructors
When an object is created, its instance variables are initialized to their default values.
However, you will generally need to provide one or more constructors in a class to
initialize its instance variables properly and to allow users of the class to specify the initial
state of an object.
For example, with the Movie class, you have already seen examples, such as:
Movie mov1 = new Movie ("Gone with the Wind");
For a user to create an object in this way, the Movie class must provide a constructor that
initializes the state of a Movie object with the specified title of the movie.
How and When Are Constructors Called?
A constructor is a special method that is called automatically by the run-time system when
an object is created. A constructor has the same name as the class; it can have arguments
but must not specify a return type. Constructors must be declared as public unless you
want to restrict who can create instances of the class.
What Happens If You Do Not Provide a Constructor?
If you do not provide any constructors, then a default no-argument (no-arg) constructor is
provided for you. This constructor takes no arguments and does nothing, but does at least
allow objects to be created. The no-arg constructor invokes the no-arg constructor of its
parent class.
Note: If you want a specific no-arg constructor as well as constructors that take arguments,
then you must explicitly provide your own no-arg constructor.
Oracle10g: Java Programming 8-8
Copyright 2004, Oracle. All rights reserved.
Defining and Overloading Constructors
public class Movie {
private String title;
private String rating = "PG";
public Movie() {
title = "Last Action ";
}
public Movie(String newTitle) {
title = newTitle;
}
}
Movie mov1 = new Movie();
Movie mov2 = new Movie("Gone ");
Movie mov3 = new Movie("The Good ");
The Movie class
now provides two
constructors.
Anatomy of a Constructor
A constructor is a special method that is called automatically when an object is created. A
constructor must have the same name as the class. It can have arguments, but it must not
specify a return type.
Overloaded Constructors
As with overloaded methods, if you want to provide more than one constructor in a class,
then each one must have a different signature. Because each constructor must have the
same name anyway, this simply means that each constructor must have different numbers
or types of arguments.
Example
In the example, the Movie class has two simple constructors: one with no arguments, and
the other that takes a String argument for the title of the movie.
Users of the Movie class can now create movies with different titles. When you create a
new Movie object, the compiler decides which constructor to call based on the arguments
that are specified in parentheses in the new statement. For example:
Movie mov1 = new Movie(); // calls the no-arg
constructor
Movie mov2 = new Movie(Last ...); // calls the constructor with
the String argument
Oracle10g: Java Programming 8-9
Copyright 2004, Oracle. All rights reserved.
Sharing Code Between Constructors
public class Movie {
private String title;
private String rating;
public Movie() {
this("G");
}
public Movie(String newRating) {
rating = newRating;
}
}
A constructor
can call another
constructor by
using this().
Movie mov2 = new Movie();
What happens
here?
Sharing Code Between Constructors
A constructor can call another constructor of the same class by using the this() syntax.
public Movie() { // First constructor
this("G");
}
public Movie(String r) { // Second constructor
rating = r;
}
The first constructor calls the second constructor, passing "G" as an argument. The second
constructor then copies the string into the rating instance variable. Using this technique
ensures that the default rating for all Movies is "G" without duplicating the code in
multiple constructors.
By using this(), you avoid duplicate code in multiple constructors. This technique is
especially useful if the initialization routine is complex. All the complex code goes into one
constructor that is called from all the others.
Syntax Rules
When one constructor calls another by using the this() syntax, there are a few rules of
syntax that you need to be aware of:
The call to this() must be the first statement in the constructor.
The arguments to this() must match those of the target constructor.
Oracle10g: Java Programming 8-10
Copyright 2004, Oracle. All rights reserved.
final Variables, Methods, and Classes
A final variable is a constant and cannot be
modified.
It must therefore be initialized.
It is often declared public static for external
use.
A final method cannot be overridden by a
subclass.
A final class cannot be subclassed.
public final class Color {
public final static Color black=new Color(0,0,0);

}
final Variables
By default, all variables may be modified, and methods may be overridden. Specifying a
variable as final prevents modification of its value, making a constant value. This is
useful for guaranteeing that a value is consistent across all users of the class. These
variables are usually declared public static final, as classwide constants.
final Methods
A final method is one that cannot be overridden in a subclass. In other words, if a
programmer inherits from the class, then he or she is not allowed to provide an alternative
version of this method. This is a useful technique to prevent programmers inadvertently or
maliciously redefining core methods that must work a certain way.
final Classes
You may also declare a class to be final. A final class is one that cannot be inherited
from. In fact, the Color class that is shown in the slide is a final class. By declaring a
class as final, you are making a strong design decision that the class is complete enough
to meet all its current and future requirements and will never need to be extended to
provide additional functionality.
Oracle10g: Java Programming 8-11
Copyright 2004, Oracle. All rights reserved.
Reclaiming Memory
When all references to an object are lost, the
object is marked for garbage collection.
Garbage collection reclaims memory that is used
by the object.
Garbage collection is automatic.
There is no need for the programmer to do
anything, but the programmer can give a hint to
System.gc();.
Garbage Collection
Memory management in Java is automatic. When an object is created, memory is allocated
for the object from a heap. When there are no more references to that object, it is marked
for garbage collection. When the garbage collector runs, it searches for marked memory
and returns it to the heap.
There are no free() or delete() functions in Java as there are in C++. To force an object to
be marked for garbage collection, simply remove all references to that object by setting the
references to null.
When Does Garbage Collection Occur?
Garbage collection is implementation specific. Some environments run garbage collection
when the amount of free memory that is available to Java Virtual Machine (JVM) falls
below some arbitrary threshold. JVM performs garbage collection in a low-priority thread.
When JVM has nothing else to do, the garbage collector thread receives some CPU time to
see whether any memory can be reclaimed.
You can explicitly request the garbage collector to run by calling the gc() method as
follows:
System.gc();
However, this is only a request for garbage collection; there is no guarantee that JVM will
take the hint.
Because of this internal garbage collection process, you do not automatically know when
an object is deleted and whether the necessary amount of memory that is needed for this
object is still in use.
Oracle10g: Java Programming 8-12
Copyright 2004, Oracle. All rights reserved.
Using the finalize() Method
If an object holds a resource such as a file, then
the object should be able to clean it up.
You can provide a finalize() method in that
class.
The finalize() method is called just before
garbage collection.
public class Movie {

public void finalize() {
System.out.println("Goodbye");
}
}
Any problems?
Destructors and the finalize() Method
In some languages, such as C++, a class can provide a destructor. A destructor is similar to
a constructor, except that it is called automatically just before an object is destroyed. A
destructor is normally used to free up resources that are held by the object, such as any
secondary memory that is allocated by the object, open files, and so on.
Java Does Not Support Destructors
Java manages memory automatically, so an object need not explicitly free any secondary
memory that it may have allocated. Consequently, Java does not support destructors.
Instead, to allow an object to clean up resources other than memory, such as open files,
Java allows a class to provide a finalize() method.
Anatomy of the finalize() Method
The finalize() method is called automatically when an object is garbage-collected.
Unfortunately, as you have already seen, there is no guarantee regarding when this will
happen or that it will happen before the program exits. The virtual machine reserves the
right to not immediately collect the memory that is associated with an object after calling
the finalizer. Such objects are known as phantoms.
Alternatives to finalize()
The unpredictability of when finalize() is called is unacceptable if resources are
scarce. The only solution is to manage such resources manually. To take control of the
process, you can define a public dispose() method in your class, which users of your
class must call when they have finished using an object of your class. You can still keep
your finalize() method if you want to, as a final effort to clean up resources.
Oracle10g: Java Programming 8-13
Copyright 2004, Oracle. All rights reserved.
What Are Inner Classes?
Inner classes are nested classes, defined in a
class or method.
They enforce a relationship between two classes.
They are of four types:
Static
Member
Local
Anonymous
public class Outer {
class Inner {
}
}
Enclosing class
Inner Class Definition
An inner class is simply a class that is defined within a class.
You define inner classes because they functionally support the outer class or because they
make sense in the context of the enclosing class.
Inner classes have different privileges when accessing outer class members according to
the type of inner class they are.
There are four different types of inner classes:
Defined in a class:
- Static Inner Class
- Member Inner Class
Defined in a method:
- Local Inner Class: Used within the scope of the method it was declared in
- Anonymous Inner class: Used globally outside of the method it was declared in
You must be careful when using inner classes, because they can make the code more
difficult to read, especially for people who have to maintain the application.
Inner classes result from the combination of block structure with class-based programming,
which was pioneered by the Beta programming language. Using block structure with inner
classes makes it easier for the Java programmer to connect objects together, because
classes can be defined closer to the objects that they need to manipulate, and can directly
use the names that they need.
Oracle10g: Java Programming 8-14
Copyright 2004, Oracle. All rights reserved.
Using Member Inner Class
It is declared within another class.
Nesting is allowed.
It can access variables within its own class and
any enclosing classes.
It can only declare final static methods.
public class CalendarPopup {
...
class MonthSelector {
class DayOfMonth{...};
DayOfMonth[] NumberOfDaysInMonth
...
}
}
Member Inner Class: Example
To better understand Member Inner classes, look at this example:
You have an application with a few date items, such as booking date and return date, and
you want to allow the users to select a specific booking date from a pop-up calendar. You
can put a button on the user interface, which when clicked, invokes a pop-up calendar
displaying the current date. The user can then select a different month for the booking or
select a specific day.
In this example, a top-level class can be used to control the pop-up calendar. The month
selector class can be implemented as a Member Inner class of the calendar. The
MonthSelector class will then populate an array with the appropriate days in the
month. The DayOfMonth class is a Member Inner class, because it is created within a
class and not a method.
Oracle10g: Java Programming 8-15
Copyright 2004, Oracle. All rights reserved.
Using Local Inner Class
It is declared within a code block (inside a
method).
All final variables or parameters declared in the
block are accessible by the methods of the inner
class.
public class CalendarPopup {
...
public void handlerMethod(){
class DateHandler{};
DateHandler sc = new DateHandler();
...
}
}
Local Inner Class: Example
To better understand Local Inner classes, look at this example:
You have the same application as before, with a few date items, such as booking date and
return date.You can put a button on the user interface, which when clicked, invokes a pop-
up calendar displaying the current date. The user can then select a different month for the
booking or select a specific day.
In this example, a top-level class can be used to control the pop-up calendar functionality.
The DateHandler class can be implemented as a Local Inner class of the
CalendarPopup. After a booking day button is clicked, and then accepted, the action
handler method invoked can create a Local Inner class to store the booking date and
calculate the return date. In this case, the Local Inner class will be used within the action
handler and nowhere else. The Local Inner class is used only with the scope of the action
handler.
Oracle10g: Java Programming 8-16
Copyright 2004, Oracle. All rights reserved.
Defining Anonymous Inner Classes
They are defined at method level.
They are declared within a code block.
They lack the class, extends, and implements
keywords.
They cannot have a constructor.
public class Outer {
...
public void outerMethod(){
...
myObject.myAnonymous(new SomeOtherClass(){
...
} )
}
}
Anonymous Inner Classes
Anonymous inner classes are Local Inner classes with no class name. The class keyword
is omitted and so are public, protected, extends, and implements. They are
commonly used to implement user interface adapters to perform event handling when using
AWT or Swing events.
Anonymous inner classes have the same restriction as Local Inner classes concerning the
visibility on the outer class elements.
The generic anonymous class syntax takes the form:
Class Outer {

AnInnerAnonymousClass (new SuperClass ( ) {


. . .
} );
. . .
}
The anonymous class is derived from a superclass that allows the use of the methods of this
superclass. Anonymous inner classes can implicitly extend or implement only other classes
or interfaces. The use of anonymous classes is most effective when they implement only a
single or very few small methods. Reading the code can get confusing when the definition
of the inner class is long.
Anonymous inner classes have the same accessibility rules as Local Inner classes. It is
primarily used to create a one-time implementation class of an interface.
Oracle10g: Java Programming 8-17
Copyright 2004, Oracle. All rights reserved.
Using the Calendar Class
It converts between a date object and a set of
integer fields.
It represents a specific moment in time.
Subclasses interpret a date according to the
specific calendar system.
public class Order {
...
public void String getShipDate(){
...
Calendar c = Calendar.getInstance();
c.setTime(orderDate);
...
}
}
The Calendar Class
Calendar is an abstract base class for converting between a Date object and a set of
integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a
specific instant in time with millisecond precision.)
Specific subclasses of Calendar interpret a Date according to the rules of a specific
calendar system. One concrete example of a Calendar subclass is GregorianCalendar.
Using the Calendar Class
The Calendar object can produce all the time field values needed to implement the date
time formatting for a particular language and calendar style (for example, Japanese
Gregorian, JapaneseTraditional, and so on). Calendar defines the range of values
returned by certain fields, as well as their meanings. For example, the first month of the
year has value MONTH == JANUARY for all calendars.
Like other locale-sensitive classes, Calendar provides a class method, getInstance,
for getting a generally useful object of this type. A Calendars getInstance method
returns a Calendar object whose time fields have been initialized with the current date
and time:
Calendar rightNow = Calendar.getInstance();
The setTime method sets this Calendars current time with the given Date.
Oracle10g: Java Programming 8-18
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
Methods can be overloaded in Java.
Instance methods receive a this reference to the
current object.
Most classes provide one or more constructors to
initialize new objects.
Class variables and class methods can be defined
for classwide properties and behaviors.
Classes can be defined in various ways within a
class.
Oracle10g: Java Programming 8-19
Copyright 2004, Oracle. All rights reserved.
Practice 8: Overview
This practice covers:
Defining and using overloaded methods
Providing a no-arg constructor for a class
Providing additional constructors for a class
Defining static variables and static methods for
classwide behavior
Using static methods
Practice 8: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful
and you want to move on to this practice, then change to the les07 directory, load up the
OrderEntryLes07 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes07 workspace. In the Applications Navigator node, expand the
OrderEntryWorkspaceLes07 OrderEntryProjectLes07 -
Application Sources oe, and double-click the UML Class Diagram1
entry. This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 8-20
Practice 8: Object Life Cycle Classes
Goal
The goal of this practice is to gain experience with creating and using constructors,
classwide methods, and attributes. You also use an existing DataMan class to provide a
data access layer for finding customers and products in the OrderEntry application. Part
of the practice is to understand method overloading by creating more than one constructor
and/or method with the same name in the same class.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful
and you want to move on to this practice, then change to the les07 directory, load up the
OrderEntryLes07 workspace, and continue with this practice.
Your Assignment
Create at least one or more suitable constructors to properly initialize the Customer
objects when instantiated. Examine the Order class and the new instantiations. Copy and
examine a DataMan class to provide classwide (static) attributes of customer objects to be
used by the OrderEntry application when it associates a customer object to an order.
Modify Customer Information
The Customer class will have two constructors:
1. Create a no-arg constructor to provide default initialization, and another constructor
to set the actual name, address, and phone properties. The no-arg constructor will be
invoked by the second constructor.
a. Add a no-arg constructor to the Customer class, which is used to generate the
next unique ID for the customer object by first declaring a class variable, called
nextCustomerId, as a private static integer initialized to zero.
b. In the OrderEntry class, comment out the customer.setId,
customer.setName, customer.setAddress, and
customer.setPhone statements for both customer1 and customer2.
c. Back in the Customer class, create a no-arg constructor, increment the
nextCustomerId, and use the setID() method with nextCustomerId
to set the ID of the customer.
d. Add a second constructor that accepts a name, address, and phone as String
arguments. This constructor must set the corresponding properties to these
values.
e. In the first line of the second constructor, chain it to the first constructor by
invoking the no-arg constructor by using the this() keyword. This is done to
ensure that the ID of a customer is always set regardless of the constructor used.
f. Save, compile, and run the OrderEntry class to check the results. Including
the order and item details that are displayed as output, you should see
"Customer: 1 null null null".
Replace and examine the Order.java File
2. In Windows Explorer, copy the Order.java class from the E:\labs\temp directory
into your current working \src\oe directory. For example if you are working in
les06 directory then copy the files under E:\les06\src\oe.
a. Select your workspace and select the Open menu option. Navigate to your
current \src\oe directory and select the Order.java file. Click the Open
button, and it will be included in the list of files.
Oracle10g: Java Programming 8-21
Practice 8: Object Life Cycle Classes (continued)
The new version of the Order class also has one constructor:
3. Examine the way in which the order date information is managed:
a. Notice the orderDate variable that had been commented out is now a
private variable.
b. After the package statement at the top of the class, notice the import statements
(before the class declaration):
import java.util.Date;
import java.util.Calendar;
c. Notice the orderDate type to be Date instead of String, and that the three
integer variablesday, month, and yearhave been removed.
4. Examine the methods that depend on three integer date variables (which were
removed in step 3c) to use orderDate.
a. The return type and value of the getOrderDate() method are replaced as
follows:
public Date getOrderDate()
{
return orderDate;
}
In addition, included is an overloaded void setOrderdate() method that
accepts a Date as its argument and sets the orderDate variable.
b. The getShipDate() method had used the Calendar class to calculate the
ship date. The body of getShipDate() has been replaced with the following
code:
int daysToShip = Util.getDaysToShip(region);
Calendar c = Calendar.getInstance();
c.setTime(orderDate);
c.add(Calendar.DAY_OF_MONTH, daysToShip);
return c.getTime().toString();
c. The setOrderDate() method body is coded to set the orderDate by
using the Calendar class methods, using the three input arguments: The
following date initialization code has been deleted:
day = 0;
month = 0;
year = 0;
d. Notice the setOrderDate() method has been modified. The following three
bold lines of code:
if ((m > 0 && m <= 12) && (y > 0 )) {
day = d;
month = m;
year = y;
}
have been replaced with these three lines of code:
Calendar c = Calendar.getInstance();
c.set(y, m - 1, d);
orderDate = c.getTime();
Oracle10g: Java Programming 8-22
Practice 8: Object Life Cycle Classes (continued)
5. A no-arg constructor has been created to initialize the order number, date, and total.
a. Notice that a new class nextOrderId has been declared and initialized to
100.
b. In the no-arg constructor, the ID of the order is set to the value in
nextOrderIdand then the nextOrderId value is incremented by 1. The
orderTotal value is set to 0, and the orderDate is set as follows:
orderDate = new Date();
Load the DataMan.java Class File into JDeveloper
The DataMan class is used to create the data that will be used to test the application. The
file creates the customer objects, and later will be used to access a database for
information. This class is really a convenience class that simplifies your application testing.
However, after this class is completed, it can be changed to retrieve data from a database
without impacting your application.
6. In Windows Explorer, copy the DataMan.java class from the E:\labs directory
into your current working \src\oe directory.
a. Select your workspace and select the Open menu option. Navigate to your
current \src\oe directory and select the DataMan.java file. Press OK,
and it will be included in the list of classes.
b. Save and compile the DataMan.java class.
Note: You can compile DataMan.java by right-clicking the file and
selecting the Make menu option.
c. Save, compile, and run the OrderEntry class to test if the code still works. You
can compile OrderEntry.java by right-clicking on the file and selecting
the Make menu option.
Modify OrderEntry to Use DataMan
7. Modify the main() method in OrderEntry to use customer objects from the
DataMan class.
a. Use the class name DataMan. as the prefix to all customer references
variables customer1 and customer2. For example, change the code:
order.setCustomer(customer1);
to become:
order.setCustomer(DataMan.customer1);
Note: You are accessing a class variable via its class name; that is, there is no
need to create a DataMan object. In addition, the customer variables in
DataMan are visible to OrderEntry because they have default (package)
access.
b. Save, compile, and run the OrderEntry class to test if the code still works.
Replace customer1 with customer3 or customer4 from DataMan to
confirm that your code is using the customer objects from DataMan.
Copyright 2004, Oracle. All rights reserved.
Using Strings, String Buffer, Wrapper,
and Text-Formatting Classes
Oracle10g: Java Programming 9-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Create strings in Java
Use the conversion methods that are provided by
the predefined wrapper classes
Use the StringBuffer class for manipulating
character data
Introduce the DateFormat, DecimalFormat, and
MessageFormat classes
Examine standard output and serialization
Lesson Aim
This lesson shows how to use the Java String class and the StringBuffer class to
manipulate character strings. You also use the Java wrapper classes to convert primitive types
into other formats.
Oracle10g: Java Programming 9-3
Copyright 2004, Oracle. All rights reserved.
What Is a String?
String is a class.
A String object holds a sequence of characters.
String objects are read-only (immutable); their
values cannot be changed after creation.
The String class represents all strings in Java.
Strings in Java
As with most programming languages, strings are used extensively throughout Java, so the
Java application programming interface (API) provides a String class to help you work
with strings of character data. Literal string values in Java source code are turned into
String objects by the compiler. The String objects can be used directly, passed as
arguments to methods, or assigned to String object reference variables:
System.out.println( "Hello World..." );
String str = "Action";
Strings Cannot Be Modified
The String class represents an immutable string. This means that after you have created a
String object, you cannot change it. If you want to modify the contents of the string, then
you must use the StringBuffer class.
Oracle10g: Java Programming 9-4
Copyright 2004, Oracle. All rights reserved.
Creating a String
Assign a double-quoted constant to a String
variable:
Concatenate other strings:
Use a constructor:
String category = "Action";
String empName = firstName + " " + lastName;
String empName = new String(Bob Smith");
Creating Strings
The easiest way to create a string is from a double-quoted constant, as shown in the first
example in the slide. You can use the + operator to concatenate two String objects. This is
explained in more detail in the following slides.
The String class provides several constructors. The following are some of the more useful
ones:
String() creates an empty string, with the value "".
String(String str) creates a copy of the specified String object, str.
String(char[] arr) creates a string from the characters in a character array.
You can find a list of constructors in the online J2SE documentation for the String class,
which is available in JDevelopers online Help.
Using Strings in Your Code
The String class is part of the java.lang package. java.lang is automatically
imported into all Java classes, so you do not need to add any import statements to your code to
use String objects.
Oracle10g: Java Programming 9-5
Copyright 2004, Oracle. All rights reserved.
Concatenating Strings
Use the + operator to concatenate strings.
You can concatenate primitives and strings.
The String class has a concat() instance
method that can be used to concatenate strings.
System.out.println("Name = " + empName);
int age = getAge();
System.out.println("Age = " + age);
Concatenating Strings
Java uses +, which is the only overloaded operator in Java, for string concatenation. The
concat() method in the String class is another way to concatenate strings.
The following code produces equivalent strings:
String name = "Sam Wong";
String name = "Sam " + "Wong";
String name = "Sam ".concat("Wong");
The second example in the slide shows a primitive (in this case, an int) being concatenated
with a String; the primitive is implicitly converted to a String.
Literal strings cannot span lines in Java source files, but you can concatenate lines to produce
the same effect:
String song =
"What good is sitting alone in your room" + "\n" +
"Come hear the music play" + "\n" +
"Life is a cabaret old chum" + "\n" +
"Come to the cabaret" + "\n";
Oracle10g: Java Programming 9-6
Copyright 2004, Oracle. All rights reserved.
Performing Operations on Strings
Find the length of a string:
Find the character at a specific index:
Return a substring of a string:
int length(); String str = "Comedy";
int len = str.length();
char charAt(int index); String str = "Comedy";
char c = str.charAt(1);
String substring
(int beginIndex,
int endIndex);
String str = "Comedy";
String sub =
str.substring(2,4);
Performing Operations on Strings
Find the Length of a String
The length() method returns the number of characters in a string. In the example in the
slide, len is set to 6.
Return the Character at a Specified Index
The charAt() method returns the character at the specified index (indexing starts at 0). In
the example in the slide, c is set to "o".
Return a Substring of a String
The substring() method returns a specified substring (starting at beginIndex, ending
at endIndex - 1) of the string. In the example in the slide, sub is set to "me".
Oracle10g: Java Programming 9-7
Copyright 2004, Oracle. All rights reserved.
Performing More Operations on Strings
Convert to uppercase or lowercase:
Trim whitespace:
Find the index of a substring:
String toUpperCase();
String toLowerCase();
String caps =
str.toUpperCase();
String trim(); String nospaces =
str.trim();
int indexOf (String str);
int lastIndexOf
(String str);
int index =
str.indexOf("me");
Performing More Operations on Strings
Convert to Uppercase or Lowercase
The toUpperCase() method returns a new string containing an uppercase version of the
original string. Similarly, the toLowerCase() method returns a new string containing a
lowercase version of the original string.
Trim Whitespace
The trim() method returns a new string containing a copy of the old string with whitespace
removed from both ends.
Find the Index of a Substring
There are two accessors that return the position of a specific character or string:
indexOf and lastIndexOf
The indexOf() method returns the index of a specified substring. It returns a zero-based
position of substring within str or 1 if not found. The lastIndexOf() method returns
the index of the last occurrence of a specified substring.
Note: There are multiple versions of both these methods. Check the online J2SE
documentation for the String class for details of each one.
Oracle10g: Java Programming 9-8
Copyright 2004, Oracle. All rights reserved.
Comparing String Objects
Use equals()if you want case to count:
Use equalsIgnoreCase()if you want to ignore
case:
Do not use ==.
String passwd = connection.getPassword();
if (passwd.equals("fgHPUw")) // Case is important
String cat = getCategory();
if (cat.equalsIgnoreCase("Drama"))
// We just want the word to match
Comparing String Objects
boolean equals(Object anObj) returns true if the specified strings contains the
same text. It does not return true if anObj is null or is not a String object.
boolean equalsIgnoreCase(String s2) is similar to equals(), except that it
ignores case.
Do not use the == operator to compare String objects or to compare any types of objects.
With objects, == returns true only if the two references point to the same object.
Oracle10g: Java Programming 9-9
Copyright 2004, Oracle. All rights reserved.
Producing Strings from Other Objects
Use the Object.toString() method.
Your class can override toString().
System.out.println() automatically calls an
objects toString() method if a reference is
passed to it.
public Class Movie {
public String toString () {
return name + " (" + Year + ")";
}
Movie mov = new Movie();
System.out.println(mov);
Strings from Objects
The toString method for a class object returns a string consisting of the name of the class
of which the object is an instance, the @ (at sign) character, and the unsigned hexadecimal
representation of the hash code of the object. The toString() method is invoked
automatically whenever you use any object reference in a string concatenation expression, or
pass it to System.out.println. In the example in the slide, the Movie class provides a
toString() method that prints the name and year of the movie.
What Happens If a Class Does Not Provide a toString() Method?
If a class does not provide its own toString() method, then it inherits one from the
Object class. The string that is produced by Object.toString() is not very user-
friendly; it consists of the name of the class of which the object is an instance and a
hexadecimal number representing a hash code. The equivalent code that is inherited from the
Object.toString() method is:
public String toString() {
return getClass().getName() +
'@' + Integer.toHexString(hashCode());
}
Oracle10g: Java Programming 9-10
Copyright 2004, Oracle. All rights reserved.
Producing Strings from Primitives
Use String.valueOf():
There is a version of System.out.println()for
each primitive type:
String seven = String.valueOf(7);
String onePoint0 = String.valueOf(1.0f);
int count;

System.out.println(count);
Strings from Primitives
The String class provides a static method valueOf() that returns a string representation
of a primitive type. However, a String does not have a valueOf() method for byte or
short. There is a version of valueOf() for each remaining primitive type. The example in
the slide uses two versions:
String valueOf(int i)
String valueOf(float f)
Printing Primitives
When a primitive is concatenated with a string, it is automatically converted to a string by
calling String.valueOf(). When a primitive is passed to System.out.println()
on its own, the appropriate version of println() is called; there is a version for each
primitive type.
Oracle10g: Java Programming 9-11
Copyright 2004, Oracle. All rights reserved.
Producing Primitives from Strings
Use the primitive wrapper classes.
There is one wrapper class for each primitive type:
Integer wraps the int type.
Float wraps the float type.
Character wraps the char type.
Boolean wraps the boolean type.
And so on
Wrapper classes provide methods to convert a
String to a primitive, and primitives to a String.
Primitive Wrapper Classes
For each primitive type, Java provides a corresponding wrapper class that allows a primitive
to be handled like an object. Each wrapper class provides a static method to convert a
String to the corresponding primitive type. The following slide shows how to use these
conversion methods.
Other Uses of Wrapper Classes
Wrapper classes are useful if you need to treat a primitive type as an object. For
example, you cannot store primitive types in a Vector, which holds objects. Thus, you
will convert an int to an Integer object by using the Integer(int) constructor.
Wrapper classes provide conversion methods that are related to primitive data type. For
example, the Integer class has a number of methods, including
Integer.parseInt(), that convert a String containing digits to an int.
Wrapper classes also provide variables that are related to the type. For example,
Integer.MAX_VALUE is the largest possible value of an int.
Oracle10g: Java Programming 9-12
Copyright 2004, Oracle. All rights reserved.
Wrapper Class Conversion Methods
Example: Use the methods to process data from fields
as they are declared.
String qtyVal = "17";
String priceVal = "425.00";
int qty = Integer.parseInt(qtyVal);
float price = Float.parseFloat(priceVal);
float itemTotal = qty * price;
Wrapper Class Conversion Methods
The example in the slide shows hardcoded String variables containing numeric values.
These values are used to perform a calculation. The qtyVal string is being converted into a
int by using the Integer.parseInt() method and the priceVal is being converted
into a float by using the Float.ParseFloat() method.
Note that the conversion methods were called without instantiating either an Integer object
or a Float object. The wrapper classes serve as a home for their conversion methods and
need not be instantiated when the methods are called.
What Happens If the Strings Contain a Value That Cannot be Converted?
If the string contains a noninteger value in the first field, then Integer.parseInt() will
fail and throw an exception. To handle such a case, you must add code to catch and handle
this exception and to catch and handle a similar exception that is thrown by
Float.parseFloat().
Oracle10g: Java Programming 9-13
Copyright 2004, Oracle. All rights reserved.
Changing the Contents of a String
Use the StringBuffer class for modifiable
strings of characters:
Use StringBuffer if you need to keep adding
characters to a string.
Note: StringBuffer has a reverse() method.
public String reverseIt(String s) {
StringBuffer sb = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--)
sb.append(s.charAt(i));
return sb.toString();
}
Introducing the StringBuffer Class
StringBuffer represents strings that can be modified and extended at run time. The
following example creates three new String objects, and copies all the characters each time
a new String is created:
String quote = "Fasten your seatbelts, ";
quote = quote + "its going to be a bumpy night.";
It is more efficient to preallocate the amount of space that is required by using the
StringBuffer constructor and its append() method as follows:
StringBuffer quote = new StringBuffer(60); // alloc 60
chars
quote.append("Fasten your seatbelts, ");
quote.append(" its going to be a bumpy night. ");
StringBuffer also provides several overloaded insert() methods for inserting various
types of data at a particular location in the StringBuffer.
Oracle10g: Java Programming 9-14
Copyright 2004, Oracle. All rights reserved.
Formatting Classes
The java.text package contains:
An abstract class called Format with the format
() method shown in the following example:
Classes that format locale-sensitive information
such as dates, numbers, and messages
DateFormat, NumberFormat, and MessageFormat
public abstract class Format {
public final String format(Object obj){
//Formats an object and produces a string.
}

}
Formatting Classes
These formatting methods define the programming interface for formatting locale-sensitive
objects into strings and for parsing strings back into objects (the parseObject()method).
Any string that is formatted by the format() method is guaranteed to be parseable by
parseObject.
If there is no match when parsing, parseObject(String) throws a
ParseException, and parseObject(String, ParsePosition) leaves the
ParsePosition index member unchanged and returns null.
Below hierarchy of Format class.
Format
NumberFormat
ChoiceFormat
DecimalFormat
Format
MessageFormat
Format
DateFormat
SimpleDateFormat
Oracle10g: Java Programming 9-15
Copyright 2004, Oracle. All rights reserved.
Using the SimpleDateFormat Class
The SimpleDateFormat:
Is a concrete class for formatting and parsing
dates in a locale-sensitive manner
Allows you to start by choosing any user-defined
patterns for datetime formatting
Uses time-pattern string to display the date:
y year 1996
M month in year July or 07
m minute in hour 30
Example of SimpleDateFormat
import java.text.SimpleDateFormat;
:
SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
System.out.println(df.format(new java.util.Date() ));
Format Pattern Result
yyyy.MM.dd G at hh:mm:ss z 1996.07.10 AD at 15:08:56 PDT
EEE, MMM d, yy Wed, Jul 10, 96
hh oclock a, zzzz 12 oclock PM, Pacific Daylight Time
K:mm a, z 0:00 PM, PST
yyyyy.MMMMM.dd GGG hh:mm aaa 1996.July.10 AD 12:08 PM
Oracle10g: Java Programming 9-16
Copyright 2004, Oracle. All rights reserved.
Using the MessageFormat Class
The MessageFormat:
Is a concrete class for constructing language
neutral messages, displayed for end users
Takes a set of objects, formats them, and then
inserts the formatted strings into the pattern at the
appropriate places
Differs from other Format classes, in that you
create a MessageFormat object
Is typically set dynamically at run time
Example of MessageFormat
MessageFormat provides a means to produce concatenated messages in a language-neutral
way. You use this to construct messages displayed for end users.
The MessageFormat takes a set of objects, formats them, and then inserts the formatted
strings into the pattern at the appropriate places. It differs from the other Format classes in
that you create a MessageFormat object with one of its constructors.
Object[] arguments = {
new Integer(7),
new Date(System.currentTimeMillis()),
"a disturbance in the Force" };
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet
{0,number,integer}.", arguments);
Output: At 12:30 PM on Jul 3, 2053, there was a disturbance in
the Force on planet 7.
Oracle10g: Java Programming 9-17
Copyright 2004, Oracle. All rights reserved.
Using DecimalFormat
The DecimalFormat:
Is a concrete subclass of NumberFormat for
formatting decimal numbers
Allows for a variety of parameters and for
localization to Western, Arabic, or Indic numbers
Uses standard number notation in format
public DecimalFormat(String pattern);
Using the DecimalFormat
Special characters are used in the parts of the pattern. For example, if you are using the
decimal format constructor to create a format pattern for displaying decimal numbers, then the
structure of the pattern can be represented by the symbols in the following chart:
Symbol Meaning
0 a digit
# a digit; zero shows as absent
. placeholder for decimal separator
, placeholder for grouping separator
; separates formats
- default negative prefix
% multiply by 100 and show as percentage
unicode \u2030 multiply by 1000 and show as per mille
unicode \\u00A4 currency sign; replaced by currency symbol; if doubled, replaced by
international currency symbol
Oracle10g: Java Programming 9-18
Copyright 2004, Oracle. All rights reserved.
Guided Practice
1. What is the output of each code fragment?
a.
b.
String s = new String("Friday");
if(s == "Friday")
System.out.println("Equal A");
if(s.equals("Friday"))
System.out.println("Equal B");
int num = 1234567;
System.out.println(String.valueOf(num).charAt(3));
Oracle10g: Java Programming 9-19
Copyright 2004, Oracle. All rights reserved.
Guided Practice
2. What is the output of each code fragment?
a.
b.
String s1 = "Monday";
String s2 = "Tuesday";
System.out.println(s1.concat(s2).substring(4,8));
// s3 begins with 2 spaces and ends with 2 spaces
String s3 = " Monday ";
System.out.println(s3.indexOf("day"));
System.out.println(s3.trim().indexOf("day"));
Oracle10g: Java Programming 9-20
Copyright 2004, Oracle. All rights reserved.
Using Regular Expressions
Matches character sequences against patterns
specified by regular expressions
Includes a Matcher class which is the engine that
performs match operations
Employs a Pattern class to provide a compiled
representation of a regular expression
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
Using Regular Expressions
A regular expression is a pattern of characters that describe a set of strings. You can use the
java.util.regex package to find, display, or modify some of the occurrences of a
pattern in an input sequence.
Pattern Class
An instance of the Pattern class represents a regular expression that is specified in string
form in a syntax similar to that used by Perl. A regular expression, specified as a string, must
first be compiled into an instance of this class. The resulting pattern can then be used to create
a Matcher object that can match arbitrary character sequences against the regular
expression. All of the states involved in performing a match resides in the matcher; so, many
matchers can share the same pattern.
Matcher Class
A matcher is created from a pattern by invoking the patterns matcher method. After it is
created, a matcher can be used to perform three different kinds of match operations:
The matches method attempts to match the entire input sequence against the pattern.
The lookingAt method attempts to match the input sequence, starting at the
beginning, against the pattern.
The find method scans the input sequence looking for the next subsequence that
matches the pattern.
Oracle10g: Java Programming 9-21
Regular Expression Examples
String class has new methods matches(regExpr), replaceFirst(regExpr),
replaceAll(regExpr) and split(regExpr).
Example 1
String p = "^[A-Z].*[\\.?!]$"; // ^ and $ irrelevant
String s = "Java is fun!";
System.out.println(s.matches(p)); //returns true. Note:
matches(..) always matches entire string
New classes for regular Expressions: java.util.regex.Pattern,
java.util.regex.Matcher and
java.util.regex.PatternSyntaxException
Example 2
String p = "^[A-Z].*[\\.?!]$";
String s = "Java is fun!";
Pattern pc1 = Pattern.compile(p, Pattern.CASE_INSENSITIVE);
Matcher m1 = pc1.matcher(s);
//Also possible: Pattern.matches(regExp,string). Less
efficient for repeated matches
System.out.println(m1.matches()); //returns true.
Example 3
Pattern pc2 = Pattern.compile("\\bis");
Matcher m2 = pc2.matcher("Java is a language. This is fun");
while (m2.find())
System.out.println(m2.start());//2 matches at 5 and 25
m2.reset("John is an actor. His movies are grisly.");
while (m2.find())
System.out.println(m2.start());//1 match at 5 only
Oracle10g: Java Programming 9-22
Regular Expression Examples (continued)
Example 4
Pattern pc2 = Pattern.compile("\\bis");
String frags = pc2.split("Java is a language. This is fun");
for (int i=0; i < frags.length; i++)
System.out.print("\"" + frags[i] + "\"\t");
output:"Java " a language. This " " fun"
Flags used by Pattern.compile(String regex, int flags):
CASE_INSENSITIVE: Matching is not case sensitive.
DOTALL: If set, the . character matches any character; otherwise, it matches all characters
except the end-of-line character.
MULTILINE: If set, the ^ and $ characters match not only the beginning and end of the string
but also matches the beginning and end of each line within the string.
UNIX_LINES: If set, then only the newline character (\n) is considered a line terminator;
otherwise, the line terminators can be \n,\r and \r\n.
Special Metacharacters (Short List):
\escape character. \\, \n, \r, \t,\f matches \, newline, carriage return, tab, and formfeed
respectively.
^ matches beginning of string (or line if MULTILINE is set).
$ matches end of string (or line if MULTILINE is set).
\b matches on a word boundary.
xy matches x followed by y.
x | y matches either x or y.
() grouping operator groups into a unit that can be repeated with *,+ or ?
Character classes: [a-d] matches a single character a through d.
[^a-d] matches any character except a-d.
Repetition: x? matches zero or one occurrence of x
x* matches 0 or more occurrences of x
x+ matches 1 or more occurrences of x
Oracle10g: Java Programming 9-23
Copyright 2004, Oracle. All rights reserved.
About System.out.println
Understanding System.out.println()
System is a class in the java.lang package.
out is a public final static (class) variable.
Declared as a PrintStream object reference
println() is an overloaded method of the
PrintStream class.
PrintStream is a FilterOutputStream that
subclasses OutputStream.
System.err is also provided as a PrintStream
object reference to write to standard error.
Understanding System.out.println()
The principal way in which your Java program has been exposed to the external environment
in previous lessons is through System.out.println() where you have sent data to the
console output.
Most Java programs execute in an environment that has a notion of the console, to which both
output and errors can be directed. If you run your program from a UNIX or DOS command-
line shell, the Java run-time environment binds the console to the shell or command window.
Two of the three System items, standard output and standard err, are derived from the
PrintStream class. The third System stream is an in, which typically reads input
entered by the user.
public final static PrintStream out = ; // standard output
public final static PrintStream err = ; // standard error
About the PrintStream Class
The PrintStream class, a subclass implementation of an OutputStream, allows you to
print data in a platform-independent way, such as primitive values and objects formatted as
strings (that is, in their textual representations). This is achieved by calling one of the
overloaded implementations of the println() methods defined in the PrintStream
class.
Oracle10g: Java Programming 9-24
Copyright 2004, Oracle. All rights reserved.
About OutputStream and PrintStream
OutputStream provides basic byte I/O operations:
write(int b) to write one byte
write(byte[] b) to write an array of bytes
write(byte[] b,int off,int len) to write a
subset of an array of bytes
flush() and close() to flush and close the stream
PrintStream is a subclass of (Filter)Output
Stream, which
Converts Unicode to environment byte encoding
Terminates lines in a platform-independent way
Flushes the output stream
About OutputStream and PrintStream
The OutputStream class provides basic methods for low-level byte I/O operations. The
methods are:
write(int b) to write one byte
write(byte[] b) to write an array of bytes
write(byte[] b, int off, int len) to write a subset of an array of bytes
flush() and close() flushes and closes the stream
Using an OutputStream object is not very useful for printing text terminated by a new line
in a platform-independent way. However, PrintStream, a subclass of
FilterOutputStream, extends the basic I/O capabilities of OutputStream in the
following ways:
It converts Java Unicode strings into the byte encoding of the environment, such that
you can see the text in a readable format.
It terminates a line in a platform-independent way. In JDK releases before 1.2, new lines
written were not platform independent.
It flushes the stream. In general, there is no guarantee that data written will be visible
immediately. Flushing the stream explicitly requests that the data be displayed now.
Oracle10g: Java Programming 9-25
Copyright 2004, Oracle. All rights reserved.
What Is Object Serialization?
Serialization is a lightweight persistence mechanism
for saving and restoring streams of bytes containing
primitives and objects.
A class indicates that its instances can be
serialized by:
Implementing java.io.Serializable or
java.io.Externalizable interface
Ensuring that all its fields are serializable, including
other objects referenced
Using the transient modifier to prevent fields
from being saved and restored
Object Serialization
Object serialization is the process of encoding an object, and the objects it references, into a
stream of bytes. Object serialization also provides mechanisms for reconstructing the object,
and its referenced objects from the stream.
Serialization can be used for lightweight persistence (for example, permanent storage in file
on disk) or used for communication between distributed Java applications.
The object saved and the relationship it has with other objects, via object references, is called
an object graph. When an object is saved and restored, the objects it references must also be
maintained. By default, when an object is stored, all of the objects that are reachable from that
object are stored as well; that is, the object graph is stored.
For an object to be saved to and restored from a stream, its class can implement one of the
following:
The java.io.Serializable interface
The java.io.Externalizable interface
Only the identity of the class of an Externalizable instance is written in the serialization
stream and it is the responsibility of the class to save and restore the contents of its instances.
Oracle10g: Java Programming 9-26
Object Serialization (continued)
Serialization: Example
package serdemo;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream; public class
SerializationDemo {
public static void main(String[] args) {
Person p1 = new Person("John", 'M', null);
Person p2 = new Person("Mary", 'F', p1);
p1.setSpouse(p2);
try{
ObjectOutputStream os = new ObjectOutputStream(new
FileOutputStream("person_graph.ser") );
os.writeObject(p1); //entire object graph is written
os.close();
ObjectInputStream is = new ObjectInputStream(new
FileInputStream("person_graph.ser") );
Person p3 = (Person) is.readObject(); //entire object
graph is read
is.close();
System.out.println(p3);
Person p4 = p3.getSpouse(); //Object obtained from graph.
System.out.println(p4);
}
catch(Exception ioe){
ioe.printStackTrace();
}
}//end main()
}
class Person implements Serializable{
private String name;
private char gender;
private Person spouse;
Oracle10g: Java Programming 9-27
Object Serialization (continued)
Serialization: Example (continued)
Person(){
}
Person(String name, char gender, Person spouse){
setName(name);
setGender(gender);
setSpouse(spouse);
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public char getGender() {
return gender;
}
public void setGender(char newGender) {
gender = newGender;
}
public Person getSpouse() {
return spouse;
}
public void setSpouse(Person newSpouse) {
spouse = newSpouse;
}
public String toString(){
return "\nName=" + name
+ "\nGender=" + gender
+ "\nSpouse=" + getSpouse().getName();
}
}
Oracle10g: Java Programming 9-28
Copyright 2004, Oracle. All rights reserved.
Serialization Streams, Interfaces,
and Modifiers
Example of implementing java.io.Serializable
Mark fields with the transient modifier to prevent
them from being saved; that is, to protect the
information.
Write object with java.io.ObjectOutputStream.
Read object with java.io.ObjectInputStream.
import java.io.Serializable;
public class Member implements Serializable {
private int id;
private String name;
private transient String password;

}
Serialization Streams, Interfaces, and Modifiers
As already stated, for an object to be serialized, its class must implement the
Serializable interface, as shown in the slide, or the Externalizable interface.
Implementing the Serializable interface does not require that you write any methods and
acts as a marker to the Java serialization system that the object can be serialized.
Use the transient modifier for variables whose values you do not want saved when the
object contained is serialized (for example, to prevent sensitive information from being
stored). However, if a variable in your serializable object references another object that is not
serializable, then that variable must be made transient; otherwise, serialization will fail. The
java.io.NotSerializableException exception is thrown if serialization fails.
Stream for Writing Objects
Writing objects to a stream is accomplished by using the ObjectOutputStream class,
whose constructor accepts another OutputStream. Thu,s wrapping another stream in an
ObjectOutputStream is quite common. For example, wrapping a
FileOutputStream in an ObjectOutputStream stores objects in a file.
Stream for Reading Objects
Reading objects from a stream is possible by using the ObjectInputStream class whose
constructor accepts another InputStream.
Oracle10g: Java Programming 9-29
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Create strings in Java
Use the conversion methods that are provided by
the predefined wrapper classes
Use the StringBuffer class for manipulating
character data
Manipulate objects by using the DateFormat,
DecimalFormat, and MessageFormat classes
Oracle10g: Java Programming 9-30
Copyright 2004, Oracle. All rights reserved.
Practice 9: Overview
This practice covers:
Creating a new Order class
Populating and formatting orderDate
Formatting existing orderDate values with the
GregorianCalendar class
Formatting orderTotal
Practice 9: Overview
Note: If you have successfully completed the previous practice, then continue using the same
directory and files. If the compilation from the previous practice was unsuccessful and you
want to move on to this practice, then change to the les08 directory, load up the
OrderEntryWorkspaceLes08 workspace, and continue with this practice.
In this practice, you use the GregorianCalendar class. This class allows you to get a
date value for a specific point in time. You can specify a date and time and see the behavior of
your class respond to that specific date and time. The class can then be based on the values
you enter, not just the system date and time.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes08 workspace. In the Applications Navigator node, expand the
OrderEntryWorkspaceLes08 OrderEntryProjectLes08 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 9-31
Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting Classes
Goal
The goal of this practice is to modify the Util class to provide generic methods to support
formatting the order details, such as presenting the total as a currency and controlling the date
string format that is displayed. This should give you exposure in using some of the
java.text formatting classes.
Note: If you have successfully completed the previous practice, then continue using the same
directory and files. If the compilation from the previous practice was unsuccessful and you
want to move on to this practice, then change to the les08 directory, load the
OrderEntryLes08 workspace, and continue with this practice.
Your Assignment
You create a method called toMoney() to return a currency formatted string for the order
total. You also create a method called toDateString() that formats the date in a
particular way. You then modify the Order class to use these methods to alter display of
order details, such as the order date and total.
Add Formatting Methods to the Util Class
1. Create a static method called toMoney() that accepts an amount as a double
and returns a String.
a. Add the following import statement to the class:
import java.text.DecimalFormat;
b. Add the following toMoney() method code to the class, to format a double:
public static String toMoney(double amount) {
DecimalFormat df = new DecimalFormat("$##,###.00");
return df.format(amount);
}
c. Save and compile the Util class.
2. Add the following static toDateString() method to format a date.
a. Add the following import statements to the Util class:
import java.util.Date;
import java.text.SimpleDateFormat;
b. Use the following code for your method:
public static String toDateString(Date d) {
SimpleDateFormat df =
new SimpleDateFormat("dd-MMMM-yyyy");
return df.format(d);
}
c. Save and compile the Util class.
Oracle10g: Java Programming 9-32
Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting Classes
(continued)
3. In this step of the practice, you use the GregorianCalendar class. This class allows
you to get a date value for a specific point in time. You can specify that date and time,
see the behavior of your class based on the values you enter, not just the system date and
time.
Create another static method called getDate() that accepts three integers
representing the day, month, and year, and returns a java.util.Date object
representing the specified date (For Example: month = 1 which represents January on
input). Because many of the methods in the Date class that could have been used are
deprecated, you use the GregorianCalendar class to assist with this task.
a. Import the java.util.GregorianCalendar class.
b. Use the following for the method:
public static Date getDate(int day,int month,int year)
{
// Decrement month, Java interprets 0 as January.
GregorianCalendar gc =
new GregorianCalendar(year, --month, day);
return gc.getTime();
}
c. Save and compile the Util class.
Use the Util Formatting Method in the Order Class
4. In the Order class, modify the toString() method to use the Util class methods
toMoney() and toDateString() altering the display format..
a. In the toString() method, replace the return value with the following text.
When shipMode is not specified, you do not need to display the information for
"Shipped: ".
return "Order: " + id +
" Date: " + Util.toDateString(orderDate) +
" Shipped: " + shipMode +
" (" + Util.toMoney(getOrderTotal()) + ")";
b. Save and compile the Order class, and then run the OrderEntry class to view
the changes to the displayed order details.
c. Now import the java.text.MessageFormat class in the Order class, and
use this class to format the toString() return value, as follows:
import java.text.MessageFormat;
Object[] msgVals = {new Integer(id),
Util.toDateString(orderDate), shipMode,
Util.toMoney(getOrderTotal()) };
return MessageFormat.format(
"Order: {0} Date: {1} Shipped: {2} (Total: {3})",
msgVals);
Oracle10g: Java Programming 9-33
Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting Classes
(continued)
d. Save and compile the Order class, and then run the OrderEntry class to view
the results of the displayed order. The change to the displayed total must appear.
Optional Extra Credit
Use Formatting in OrderItem Class
5. In the OrderItem class, modify the toString() method to use the
Util.toMoney() methods to alter the display format of item total.
a. In the toString() method, replace the return statement with the following:
return lineNbr + " " + quantity + " " +
Util.toMoney(unitPrice);
b. Save and compile the OrderItem class, and then run the OrderEntry class to
view the changes to the order item total.
Use Util.getDate() to Set the Order Date
6. In the OrderEntry class, alter the second order object creation statement to use the
Util.getDate() method to provide the value for the first argument in the
constructor. Choose the previous days date for the values of the day, month, and year
arguments supplied to the Util.getDate() method.
a. The call to the constructor should look like:
Order order2 =
new Order(Util.getDate(7, 3, 2002), "overnight");
b. Save, compile, and run the OrderEntry class to confirm that the order
date has been set correctly.
Copyright 2004, Oracle. All rights reserved.
Reusing Code with Inheritance
and Polymorphism
Oracle10g: Java Programming 10-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Define inheritance
Use inheritance to define new classes
Provide suitable constructors
Override methods in the superclass
Describe polymorphism
Use polymorphism effectively
Lesson Aim
This lesson shows how to extend an existing class in Java, and illustrates the power of
polymorphism in object-oriented programs. You learn how to extend existing classes to
meet specific application needs. You also learn how to override superclass methods to fine-
tune object characteristics and behaviors.
Oracle10g: Java Programming 10-3
Copyright 2004, Oracle. All rights reserved.
Key Object-Oriented Components
Inheritance
Constructors referenced by subclass
Polymorphism
Inheritance as an OO fundamental
InventoryItem
Movie Game Vcr
Superclass
Subclasses
Key Object-Oriented Components
What Is Inheritance?
Inheritance defines a relationship between classes where one class shares the data structure
and behaviors of another class. Inheritance is a valuable technique because it enables and
encourages software reuse by allowing you to create a new class based on the properties of
an existing class. As a result, the developer is able to achieve greater productivity than
would otherwise be possible.
Inheritance and Constructors
Constructors are blocks of code that are executed when an object of that class is created. By
using an inheritance model, each subclass has access to the superclasss constructor. Any
common constructor code can be put in the superclass constructor and called by the
subclass. This technique minimizes the need for duplicated code and provides for consistent
object creation.
Polymorphism
Polymorphism describes the ability of Java to execute a specific method based on the object
reference that is used in the call. By using this technique, you can define a method in the
superclass and override it in the appropriate subclass. You can now write method calls to the
superclass, and if the method is overridden in a subclass, then Java automatically calls the
right method. This is a very powerful construct that you can use to define superclass
methods before knowing the details of any subclasses.
Oracle10g: Java Programming 10-4
Copyright 2004, Oracle. All rights reserved.
Example of Inheritance
The InventoryItem class defines methods and
variables.
Movie extends InventoryItem and can:
Add new variables
Add new methods
Override methods in InventoryItem class
InventoryItem
Movie
The InventoryItem Class
The InventoryItem class defines the attributes and methods that are relevant for all
kinds of inventory items. The attributes and methods may include:
Attributes, such as the date of purchase, purchase cost, and condition
Methods, such as calculating a deposit, changing the condition, and setting the price
Dealing with Different Types of InventoryItem
Depending on what you are trying to do in your program, you may need to represent a
specific type of InventoryItem in a particular way. You can use inheritance to define a
separate subclass of InventoryItem for each different type of InventoryItem. For
example, you may define classes such as Movie, Game, and Vcr.
Each subclass automatically inherits the attributes and methods of InventoryItem, but
can provide additional attributes and methods as necessary. For example, the Movie class
may define the following additional attributes and methods:
Attributes, such as the title of the movie, the director, and the running length
Methods, such as reviewing the movie and setting the rating
Subclasses can also override a method from the superclass if they want to provide more
specialized behavior for the method. In this example, the movie could override the
InventoryItem calculating a deposit method. A movie may have an additional amount
calculated into the deposit.
Oracle10g: Java Programming 10-5
Copyright 2004, Oracle. All rights reserved.
Specifying Inheritance in Java
Inheritance is achieved by specifying which
superclass the subclass extends.
Movie inherits all the variables and methods of
InventoryItem.
If the extends keyword is missing, then the
java.lang.Object is the implicit superclass.
public class InventoryItem {

}
public class Movie extends InventoryItem {

}
Specifying Inheritance in Java
When you define a subclass, you must provide code only for the features in the subclass that
are different from those of the superclass. In a very real way, the subclass is extending the
superclass. The syntax for specifying inheritance in Java makes use of the extends
keyword. For example:
public class InventoryItem {
// Definition of the InventoryItem class
}
public class Movie extends InventoryItem {
// Additional methods and attributes, to distinguish a
// Movie from other types of InventoryItem
}
Characteristics of Inheritance in Java
If you have experience with another OO language, such as C++, then note that Java allows
only single inheritance. In other words, a class can specify only one immediate superclass.
Also, remember that all classes in Java are automatically inherited from the root class called
Object, which sits at the top of the inheritance tree. If a class does not specify an explicit
superclass, as is the case with InventoryItem in the slide, then the class is deemed to
extend directly from Object, as if it were defined as follows:
public class InventoryItem extends Object {
The java.lang.Object class is the root class for all the classes in Java.
Oracle10g: Java Programming 10-6
Copyright 2004, Oracle. All rights reserved.
Defining Inheritance
by Using Oracle JDeveloper 10g
When specifying a class, JDeveloper asks for its
superclass:
JDeveloper generates the code automatically.
Defining Inheritance by Using Oracle JDeveloper 10g
To define a new class that inherits from another class, follow these steps:
1. Select File > New from the Main menu bar.
2. A dialog box is displayed that prompts you for the kind of feature you want to create.
Select the General category, and double-click the Java Class icon. This launches the
New Class dialog box.
3. Specify the name for your class, and browse to the name of the superclass that you
want to extend. In the Browse window, JDeveloper brings up all packages (and the
classes that are contained inside them) that it currently holds in memory. The default
superclass name is java.lang.Object; that is, the Object class that is located in
the java.lang package.
4. Click the OK button. JDeveloper generates a skeleton class to get you started, as
follows:
package practice17;
public class Movie extends InventoryItem {
}
Oracle10g: Java Programming 10-7
Copyright 2004, Oracle. All rights reserved.
What Does a Subclass Object
Look Like?
A subclass inherits all the instance variables of its
superclass.
Movie
title
length
price
condition
public class
Movie extends InventoryItem {
private String title;
private int length;
}
public class InventoryItem {
private float price;
private String condition;
}
Variables in Superclass and Subclass
The superclass defines the variables that are relevant for all kinds of InventoryItem,
such as the purchase date and condition. The subclass, Movie, inherits these variables for
free and has to specify only the Movie-specific variables, such as the title.
What Does an Object Look Like?
If you create a plain InventoryItem object, then it contains only the instance variables
that are defined in InventoryItem :
InventoryItem i = new InventoryItem ();
// an InventoryItem has a price and condition
However, if you create a Movie object, then it contains four instance variables: the two
inherited from InventoryItem, plus two added in Movie:
Movie m = new Movie();
// A Movie object has a price and condition, because a
// Movie is a kind of InventoryItem.
// The Movie object also has a title and length.
Declaring Instance Variables as private
Instance variables must normally be declared as private, which means that instances of
subclasses inherit the values, but cannot access them directly. You must define methods to
access private variables. You can define methods in the subclass or inherit them from the
superclass.
Oracle10g: Java Programming 10-8
Copyright 2004, Oracle. All rights reserved.
Default Initialization
What happens when a subclass
object is created?
If no constructors are defined:
First, the default no-arg
constructor is called in the
superclass.
Then, the default no-arg
constructor is called in the
subclass.
Movie movie1 = new Movie();
Movie
title
length
price
condition
Default Provision of Constructors
A class does not inherit any constructors from its superclass. Therefore, the
InventoryItem class has only the constructors explicitly declared in its definition or a
default no-arg constructor if there are no other constructors at all.
What Happens When a Subclass Object Is Created?
The example in the slide creates a movie1 object. For the moment, assume that neither the
Movie class nor the InventoryItem class provides any constructors; all they have is the
default no-arg constructor that is provided automatically by Java.
What happens when a movie1 object is created? Objects are always constructed from the
top class down to the bottom class; that is, from the Object class down to the class that is
being instantiated using new. This ensures that a constructor in a subclass can always rely
on proper construction of its superclass.
In the example, when you create a movie1 object, the no-arg constructor of
InventoryItem is called first to initialize the InventoryItem instance variables with
default values. The price is set to 0 and condition is set to its default: excellent.
After the superclass is initialized, the no-arg constructor of Movie is then called to initialize
the title and length instance variable with default values.
Oracle10g: Java Programming 10-9
Copyright 2004, Oracle. All rights reserved.
The super Reference
Refers to the base, top-level class
Is useful for calling base class constructors
Must be the first line in the derived class
constructor
Can be used to call any base class methods
The super Reference
The super reference is useful only when a class has an ancestor. A subclass inherits all of
the superclass methods and variables as well as creates its own. Methods in the superclass
may be overridden in the subclass by creating methods with the same name and signature in
the subclass. You can use the super keyword to specifically access methods in the
superclass even though they have been overridden in the subclass.
Calling Constructors
One of the more common uses of super is to invoke a constructor provided by the
superclass. When the superclass was designed, it probably had a constructor to ensure proper
initialization of any new objects. Because a subclass inherits all of the superclass variables,
they must be initialized for subclass objects as well.
The syntax rule is that super() must be the first line in the subclass constructor.
Add the super reference within the subclass constructor to access the superclass constructor:
- subclass() { // constructor for the subclass
- super(); // call the superclass constructor
- ; // subclass specific constructor code
- }
The super keyword may also be used to call any superclass methods.
Oracle10g: Java Programming 10-10
Copyright 2004, Oracle. All rights reserved.
The super Reference Example
public class InventoryItem {
InventoryItem(String cond) {
System.out.println("InventoryItem");

}
}
class Movie extends InventoryItem {
Movie(String title) {
Movie(String title, String cond)
{super(cond);

System.out.println("Movie");
}
}
Base class
constructor
Calls base
class
constructor
The super Reference Example
In the example, there are initialization routines that must happen for all inventory items.
Those routines are placed in the InventoryItem constructor. These routines must be
used regardless of the type of InventoryItem that is being constructed, whether it is a
Movie, Game, or a Book.
There are also constructors in each of the subclasses to take care of subclass-specific
routines. The Movie constructor reuses the InventoryItem constructor by referencing it
with the super keyword. This statement is the first statement in the Movie constructor and
may be followed by whatever other statements are necessary to fully construct a Movie
object.
Oracle10g: Java Programming 10-11
Copyright 2004, Oracle. All rights reserved.
Using Superclass Constructors
Use super() to call a superclass constructor:
public class InventoryItem {
InventoryItem(float p, String cond) {
price = p;
condition = cond;
}
public class Movie extends InventoryItem {
Movie(String t, float p, String cond) {
super(p, cond);
title = t;
}
Nondefault Initialization with Inheritance
The superclass and subclass often have constructors that take arguments. For example,
InventoryItem may have a constructor that takes arguments to initialize price and
condition:
public InventoryItem (float p, String cond) {
price = p;
condition = cond;
}
Likewise, the Movie class may have a constructor that takes enough arguments to initialize
its attributes. This is where things get interesting. A Movie object has three attributes:
price and condition that are inherited from InventoryItem, plus title, which is
defined in Movie itself. The Movie constructor may therefore take three arguments:
public Movie(float p, String cond, String t) { }
Oracle10g: Java Programming 10-12
Nondefault Initialization with Inheritance (continued)
Rather than initializing price and condition explicitly, all the Movie constructor has
to do is call the superclass constructor. This can be achieved by using the super keyword;
the call to super() must be the first statement in the constructor.
public Movie(float p, String cond, String t) {
super(p, cond); // Call superclass constructor
title = t; // Initialize Movie-specific attributes
If you do not explicitly call super(), then the compiler calls the superclass no-arg
constructor by default. If the superclass does not have a no-arg constructor, then a compiler
error occurs.
Oracle10g: Java Programming 10-13
Copyright 2004, Oracle. All rights reserved.
Specifying Additional Methods
The superclass defines methods for all types of
InventoryItem.
The subclass can specify additional methods that
are specific to Movie.
public class InventoryItem {
public float calcDeposit()
public String calcDateDue()

public class Movie extends InventoryItem {
public void getTitle()
public String getLength()
Methods in the Superclass and Subclass
The slide shows some of the methods that are declared in the superclass and the subclass.
The superclass defines the methods that are relevant for all kinds of InventoryItem,
such as the ability to calculate a deposit or the due date for the item. The subclass, Movie,
inherits these methods from the superclass and has to add only the Movie-specific methods,
such as getting the title and getting the length.
Oracle10g: Java Programming 10-14
Methods in the Superclass and Subclass (continued)
What Methods Can Be Called?
When you create an object, you can call any of its public methods plus any public
methods that are declared in its superclass. For example, if you create an InventoryItem
object, then you can call the public methods that are defined in InventoryItem, plus
any public methods that are defined in its superclass, Object:
InventoryItem i = new InventoryItem ();
i.getId(); // Call a public method in InventoryItem
i.getClass(); // Call a public method in Object
If you create a Movie object, then you can call any public methods that are defined in
Movie, InventoryItem, or Object:
Movie m = new movie(); // Create a Movie object
m.getTitle(); // Call a public method in Movie
m.getId(); // Call a public method in InventoryItem
m.getClass(); // Call a public method in Object
Oracle10g: Java Programming 10-15
Copyright 2004, Oracle. All rights reserved.
Overriding Superclass Methods
A subclass inherits all the methods of its
superclass.
The subclass can override a method with its own
specialized version.
The subclass method must have the same signature
and semantics as the superclass method.
public class InventoryItem {
public float calcDeposit(int custId) {
if
return itemDeposit;
}
public class Vcr extends InventoryItem {
public float calcDeposit(int custId) {
if
return itemDeposit;
}
Overriding Superclass Methods
A subclass inherits all of the methods of its superclass. However, a subclass can modify the
behavior of a method in a superclass by overriding it, as shown in the slide.
To override a superclass method, the subclass defines a method with exactly the same
signature and return type as a method somewhere above it in the inheritance hierarchy.
The method in the subclass effectively hides the method in the superclass. It is important to
make sure that the method in the subclass has the return type and signature as the one that it
is overriding.
Which Method Is Called?
In the example that is shown in the slide, the InventoryItem class provides a
calcDeposit() method, and the Vcr class overrides it with a more specialized version.
If you create an InventoryItem object and call calcDeposit(), then it calls the
InventoryItem version of the method. If you create a Vcr object and call
calcDeposit(), then it calls the Vcr version of the method.
Oracle10g: Java Programming 10-16
Overriding Superclass Methods (continued)
Overriding and Overloading
Do not confuse method overloading with method overriding:
Method overloading is a process by which you define multiple methods with different
signatures. Overloaded methods are resolved at compile time, based on the arguments
that you supply.
Method overriding is a process by which you provide a method with exactly the same
signature as a method in a superclass. Overridden methods are resolved at run time,
unlike overloaded methods.
Oracle10g: Java Programming 10-17
Copyright 2004, Oracle. All rights reserved.
Invoking Superclass Methods
If a subclass overrides a method, then it can still
call the original superclass method.
Use super.method() to call a superclass method
from the subclass.
public class InventoryItem {
public float calcDeposit(int custId) {
if
return 33.00;
}
public class Vcr extends InventoryItem {
public float calcDeposit(int custId) {
itemDeposit = super.calcDeposit(custId);
return (itemDeposit + vcrDeposit);
}
Invoking Superclass Methods
Calling an Overridden Method from the Client Program
As previously mentioned, when a subclass overrides a method in a superclass, it hides that
method. For example, if the client program creates a Vcr object and calls the
calcDeposit() method, then it always executes the Vcr version of calcDeposit():
Vcr v = new Vcr(); // Create a Vcr object
v.calcDeposit(); // Executes Vcr calcDeposit() method
Oracle10g: Java Programming 10-18
Invoking Superclass Methods (continued)
Calling an Overridden Method from the Subclass
Within the Vcr version of calcDeposit(), you can call the InventoryItem version
of calcDeposit() that is defined in the superclass by using the super keyword. The
super keyword is similar to this, except that it acts as a reference to the current object as
an instance of its superclass.
Calling an overridden superclass method by using super helps to avoid duplicating the
code that is contained in the overridden method; by reducing the amount of duplicate code,
the code is more consistent and easier to maintain.
The syntax for an example of overriding a method is:
super.calcDeposit();
Working in JDeveloper
You can take advantage of JDevelopers built-in functionality to see all the methods of a
given class, plus its inherited methods (taken from the superclass). To do this, select the
class (for example, Game, which extends InventoryItem), right-click and select Class
Editor, and then click the Methods tab (the third tab from the left). Toggle the Show
Inherited Methods check box to display methods. The same behavior is available in the
Fields tab.
Oracle10g: Java Programming 10-19
Copyright 2004, Oracle. All rights reserved.
Example of Polymorphism in Java
Recall that the java.lang.Object class is the root
class for all Java Class.
Methods in the Object class are inherited by its
subclasses.
The toString() method is most commonly
overridden to achieve polymorphic behavior.
For example: public class InventoryItem {
public String toString() {
return "InventoryItem value";
}
}
InventoryItem item = new InventoryItem();
System.out.println(item); // toString() called
Polymorphism and the toString Method
Polymorphism returns a string representation of the object. In general, the toString
method returns a string that textually represents this object. The result must be a concise
but informative representation that is easy for a person to read. It is recommended that all
subclasses override this method.
The toString method for the Object class returns a string consisting of the name of the
class of which the object is an instance, the @ (at sign) character, and the unsigned
hexadecimal representation of the hash code of the object. In other words, this method
returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Oracle10g: Java Programming 10-20
Copyright 2004, Oracle. All rights reserved.
Treating a Subclass as Its Superclass
A Java object instance of a subclass is assignable to
its superclass definition.
You can assign a subclass object to a reference
that is declared with the superclass.
The compiler treats the object via its reference
(that is, in terms of its superclass definition).
The JVM run-time environment creates a subclass
object, executing subclass methods, if overridden.
public static void main(String[] args) {
InventoryItem item = new Vcr();
double deposit = item.calcDeposit();
}
Subclass and Its Superclass
Any Java subclass object can be assigned to an object reference variable that is declared as
its superclass, or as the same class as itself. The slide example shows that a Vcr object is
assigned to the item object reference, which is declared as an InventoryItem. The
Vcr must previously be declared as a class that extends InventoryItem. The Java
compiler accepts this as valid syntax. This is necessary for polymorphism.
There are two ways to look at the code example:
The Compiler View
The compiler sees the Vcr object as if it were a kind of InventoryItem. Therefore, all
methods that are called from the item object reference can only be those defined in the
InventoryItem class, because item is defined as an InventoryItem. In essence, you
are writing generic code to deal with common functionality of any kind of inventory item
object.
The Run-Time View
At run time, JVM dynamically creates the Vcr object. Thus, when you call a method, such
as item.calcDeposit(), it is the Vcrs calcDeposit() method that is invoked if
it overrides its superclass definition. Otherwise, the inherited method is called. JVM uses a
run-time type checking mechanism to ensure that the call is valid; otherwise, it throws an
exception.
Oracle10g: Java Programming 10-21
Copyright 2004, Oracle. All rights reserved.
Browsing Superclass References
by Using Oracle JDeveloper 10g
Oracle JDeveloper makes it
easy to browse the contents
of your superclass.
3
1
2
Browsing Superclass References by Using Oracle JDeveloper 10g
You can use the structure pane on the bottom left of JDeveloper to browse the contents of
any of your superclass references. The following sections describe what to do:
1. Select your class in the navigation pane.
The structure pane at the top left of the navigation pane lists all the classes in your
project. Select the subclass that you want to start with, such as Individual.
2. Select the superclass in the structure pane.
The structure pane at the bottom left of the navigation pane lists all the methods,
variables, and constructors for the current class. It also contains an icon to represent
the superclass, which in this case is Customer.
3. View the superclass reference in the subclass code.
Select the extends superclass text in the Structure pane (in this case, extends
Customer) and the Code Editor displays the reference.
Oracle10g: Java Programming 10-22
Copyright 2004, Oracle. All rights reserved.
Acme Video and Polymorphism
Acme Video started renting only videos.
Acme Video added games and Vcrs.
What is next?
Polymorphism solves the problem.
Acme Video and Polymorphism
Acme Video started as a simple video rental business that only rented videos. As business
began to improve, Acme Video decided to branch out and add video games to its inventory.
It soon started getting requests for Vcrs and for video game devices.
Each of the different items Acme is now renting has unique properties, and it handles each
type in a slightly different manner. For example, it requires a deposit on the Vcrs and video
game devices, but not on videos and games. The deposit is based on the type of equipment
and the customer. Regular, established customers with good credit are not required to leave
a deposit, whereas new customers are.
When the customer checks out, Acme must determine the price of the items as well as any
required deposit. Its application must be flexible enough to accept new types of items
without having to change or recompile existing code each time its business is expanded. It
accomplishes this goal by using Javas polymorphic abilities.
Acme designed the ShoppingBasket class to simply accept and process
InventoryItems, whatever type they may be. It then allows Java determine the type of
the item and call the correct methods based on that type.
By using this technique, Acme can add as many new item types as you need without having
to change or recompile existing code.
Oracle10g: Java Programming 10-23
Copyright 2004, Oracle. All rights reserved.
ShoppingBasket
Using Polymorphism for Acme Video
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();

}
InventoryItem
Vcr
Movie
calcDeposit(){}
calcDeposit(){} calcDeposit(){}
Using Polymorphism for Acme Video
When Acme designed its video rental application, it did not know all the types of
InventoryItem that would be rented in the long term. In non-OO programming, this
would create a problem that would be solved by modifying code each time a new type was
added.
In Java, you can use polymorphism to solve the problem. Heres how you can do it:
The calcDeposit() method in the InventoryItem class is overridden in the Vcr
and Movie classes to provide object-specific calculation logic. The ShoppingBasket
class includes an addItem(InventoryItem item) method that calls the
calcDeposit() method by using an InventoryItem object.
Oracle10g: Java Programming 10-24
Using Polymorphism for Acme Video (continued)
At run time, Java interrogates the argument to determine its actual object type and
determines whether the type has an overriding method. If it does, then Java uses the subclass
method in place of the superclass method.
For example, if movie is a variable of type Movie and Vcr is a variable of type Vcr:
addItem(movie); // calls the Movie version of calcDeposit()
addItem(vcr); // calls the Vcr version of calcDeposit()
The addItem method accepts any kind of InventoryItem object, including the plug-
compatible subclass objects.
The significance is that the ShoppingBasket or InventoryItem classes do not need
to change as new InventoryItem types are added to the business. The OO-designed
code will continue to work.
Oracle10g: Java Programming 10-25
Copyright 2004, Oracle. All rights reserved.
Using the instanceof Operator
You can determine the true type of an object by
using an instanceof operator.
An object reference can be downcast to the
correct type, if necessary.
public void aMethod(InventoryItem i) {

if (i instanceof Vcr)
((Vcr)i).playTestTape();
}
The instanceof Operator
You can use the instanceof operator to determine the type of an object at run time. It is
useful in situations where you need to call some subclass-specific operation on an object, but
you must first verify that the object is the correct type.
The syntax of the instanceof operator is as follows:
objectRef instanceof className
The instanceof operator returns a Boolean value. If the object that is referred to by
objectRef is an instance of the specified className, or one of its subclasses, then the
instanceof operator returns true. Otherwise, it returns false.
Example
The method in the slide takes an object reference whose compile-time type is declared as
InventoryItem. However, at run time, the object that is passed into the method may be
any kind of InventoryItem, such as Vcr, Movie, or Game.
Inside the method, you use instanceof to test whether you have a Vcr object. If so, then
you convert the compile-time type of the object reference into the Vcr type, and then call a
Vcr-specific method. This is often called downcasting.
Downcasting
The downcast is necessary in this example. Without it, the compiler allows you to call only
those methods that are defined in the InventoryItem class. Having said that, you must
use downcasting sparingly. There are usually alternative designs that obviate the need for
excessive downcasting.
Oracle10g: Java Programming 10-26
Copyright 2004, Oracle. All rights reserved.
Limiting Methods and Classes with final
You can mark a method as final to prevent it
from being overridden.
You can mark a whole class as final to prevent it
from being extended.
public final class Color {

}
public final boolean checkPassword(String p) {

}
final Methods
Methods and classes are made final for two primary reasons: security and optimization.
If a method is performing some vital operation, such as identity validation or authorization
checking, then it must be declared final to prevent anyone from overriding the method
and circumventing your security checks. Many of the methods that are defined in
java.net classes are final. For example,
final Classes
If you declare a class as final, then it can never be extended by any other class. This is a
strong design statement that the class is sufficient to cater to all current and future
requirements. The implication is clear: You do not even need to think about inheriting from
this class. For example, the Color class in java.awt is declared final.
final Classes and final Methods Yield More Efficient Code
final classes enable the compiler to produce more efficient code. Because a final class
cannot be extended, if the compiler encounters an object reference of that type, and you call
a method by using that object reference, then the compiler does not need to perform run-
time method binding to cater to any subclasses that may have overridden the method.
Instead, the compiler can perform static binding; that is, the compiler can decide which
method to call and avoid the overhead of run-time polymorphic lookup.
This is true for individual final methods as well. If you call a final method anywhere in
your program, then the compiler can call that method statically, without worrying about
whether the method may be overridden by some subclass.
Oracle10g: Java Programming 10-27
Copyright 2004, Oracle. All rights reserved.
Ensuring Genuine Inheritance
Inheritance must be used only for genuine is a
kind of relationships:
It must always be possible to substitute a subclass
object for a superclass object.
All methods in the superclass must make sense in
the subclass.
Inheritance for short-term convenience leads to
problems in the future.
Inheritance Represents an Is-a-Kind-of Relationship
Use inheritance only to model a genuine is a kind of relationship. In other words, do not
use inheritance unless all of the inherited methods apply to the subclass. If you cannot
substitute a subclass object for a superclass object, then you do not have a genuine is a kind
of relationship. In this case, the classes may be related, but not hierarchically.
If you do use inheritance, then exploit the polymorphic nature of the instance methods in the
inheritance hierarchy. For example, if you find that you need to test for the type of an object
in an inheritance tree, then use polymorphism to avoid having to write separate code to
handle objects of each class. This maximizes the reusability of your code and makes your
code easier to maintain in the future.
Oracle10g: Java Programming 10-28
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
A subclass inherits all the variables and methods
of its superclass.
You can specify additional variables and methods
and override methods.
A subclass can call an overridden superclass
method by using super.
Polymorphism ensures that the correct version of
a method is called at run time.
Oracle10g: Java Programming 10-29
Copyright 2004, Oracle. All rights reserved.
Practice 10: Overview
This practice covers:
Defining subclasses of Customer
Providing subclass constructors
Adding new methods in the subclasses
Overriding existing superclass methods
Practice 10: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les09 directory, load the
OrderEntryWorkspaceLes09 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes09 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes09 OrderEntryProjectLes09 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 10-30
Practice 10: Reusing Code with Inheritance and Polymorphism
Scenario
In this practice, you add a few new classes as subclasses. The new classes that are added are
Company and Individual and they inherit from the Customer class. Here is a Class
diagram to show the relationship between Customer, Company, and Individual. Each
box represents a class. The name of the class appears at the top of each box. The middle
section specifies the attributes in the class, where underlined attributes represent class
variable. The lower section specifies the methods in the class.
Notice the arrow on the line connecting Company and Individual to Customer. This
is the UML notation for inheritance.
Person class
Customer
int nextCustomerId
int id
String name
String address
String phone
toString()
getNamen()
setName()
getAddress()
setAddress()

Person class
Company
String contact
int discount
toString()
setContact()
getContact()
setDiscount()
getDiscount()
Person class
Individual
String licNumber
toString()
setLicNumber()
getLicNumber()
Oracle10g: Java Programming 10-31
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
Goal
The goal of this practice is to understand how to create subclasses in Java, and use
polymorphism with inheritance through the Company and Individual subclasses of the
Customer class. Refine the subclasses and override some methods and add some new
attributes, making use of the Class Editor in JDeveloper.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les09 directory, load the
OrderEntryWorkspaceLes09 workspace, and continue with this practice.
Your Assignment
Add two classes, Company and Individual, that inherit from Customer. The owners
of the business have decided to expand their business and sell their products to companies as
well as individuals. Because companies have slightly different attributes than individuals,
you have decided to create subclasses for Company and Individual. Each of the
subclasses will have a few of their own methods and will override the toString()
method of Customer. In JDeveloper, continue to use your workspace and project
(OrderEntryWorkspace and OrderEntryProject) from the previous practice
containing the files from the previous practices.
Define a New Company Class
1. Define a Company class that extends Customer and includes the attributes and
methods that were defined in the object model on the first page of this practice
(scenario section).
a. Right-click the OrderEntryProject.jpr project and select the New
option from the pop-up menu. In the New Gallery window, select the General
category (if not selected by default) and Java Class from the Items list.
Then, click OK.
b. In the Create Java Class Wizard, enter Company in the Name field, then click
the Browse button next to the Extends field. In the Class Browser window,
locate and expand the oe package, select the Customer class, and click the OK
button. The oe.Customer class must be shown in the Extends field. Leave the
Optional Attributes in their default state, and click the OK button. When the
source code for the generated class is displayed, save your work.
c. Select Company.java file in the Navigator and then select the Class tab at the
bottom of the code window. This displays the Class Editor. In the Class Editor,
select the Fields tab.
d. In the Fields tab, for each attribute, click the +Add button in the Declared Fields
area to add the following private attributes:
private String contact;
private int discount;
For each attribute in the Fields Setting dialog box, enter:
- A Field name (for example, Contact)
- A Field type (appropriate for the variable)
- A Scope set to private
Oracle10g: Java Programming 10-32
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
Note: In the Accessors section, note that Create get() method and
Create set() method check boxes are selected. Then, click the OK button
to create each field.
e. After adding the attributes, click the Methods tab to view the get and set
methods that JDeveloper has generated for each attribute. The methods are
named according to JavaBean coding standards. Modify the code created by
JDeveloper to match the code below, if required.
f. Save your changes.
2. Alter the Company constructor to have arguments.
a. Add the following arguments to the no-arg constructor:
public Company(String aName, String aAddress,
String aPhone, String aContact, int aDiscount) {
}
b. Use the arguments to initialize the object state (including the superclass state).
Hint: Use the super() method syntax to pass values to an appropriate
superclass constructor to initialize the superclass attributes. For example:
super(aName, aAddress, aPhone);
contact = aContact; ...
3. Add a public String toString() method in the Company class to to return the
contact name and discount. Include in the return value the superclass details, and
format as follows:
(Scott Tiger, 20%)
return super.toString() + " ("+ contact + ", "+ discount
+ "%) ";
a. You can manually enter the toString() method signature to the class, or get
JDeveloper to generate the toString() method signature as described in step
(b). Skip step (b) if you manually enter the method.
b. Select the Tools> Override Methods... menu, to launch the Override Methods
Wizard. Ensure that oe.Company is visible in the Class field. Select the
toString(): String method from the Methods list and then click the OK
button. Scroll down to the end of the source code in the Company class to view
the results and modify the code for the method body to match with the displayed
code.
c. Save and compile the Company.java class.
Define a New Individual Class As a Subclass of Customer
4. Define an Individual class extending Customer, and include the attributes and
methods that are defined in the object model on the first page of this practice.
a. Create the Individual class similarly as mentioned for the Company class in point
1:a. Add the licNumber attribute as a String, with a private scope and
ensure that the get and set methods are created to retrieve the values.
Oracle10g: Java Programming 10-33
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
b. Alter the no-arg constructor to accept four arguments for the name, address,
phone, and the license number.
c. Complete the constructor body initialization by assigning the arguments to the
appropriate instance variables in the Individual class and its superclass.
d. Override the toString() method that is defined in the superclass, and append
the license number enclosed in brackets to the superclass information.
Note: You can write the code in bold without manually having to select the Tools
Override menu option.
e. Save and compile the Individual class.
Modify the DataMan Class to Include Company and Individual Objects
You add two new class variables to the DataMan classone for a Company object, and
the other for an Individual.
5. Open DataMan in the Code Editor and add two new class variables called
customer5 and customer6.
a. Create a Company variable called customer5, and initialize the variable by
using the Company constructor. For example:
static Company customer5 =
new Company("Oracle","Redw","80","Larry",20);
b. Create an Individual variable called customer6, and initialize by using
the constructor from the Individual class.
c. Save and compile DataMan.java by right-clicking the file and selecting Make
from the shortcut menu.
Test Your New Classes in the OrderEntry.java Application
Modify the OrderEntry code that assigns a customer object to each of the two order
objects in the main() method.
6. Open OrderEntry.java in the Code Editor.
a. Locate the line assigning customer3 with the first order object.
For example, find:
order.setCustomer(DataMan.customer3);
Hint: Use Ctrl + F to display a search dialog box.
Replace customer3 with customer5 (the company in DataMan).
b. Compile the code, and if successful, explain why.
c. Now replace customer4 in order2.setCustomer() argument with
customer6 (the individual in DataMan).
d. Compile and run the OrderEntry.java application. What is displayed in the
customer details for each order?
Explain the results that you see.
Oracle10g: Java Programming 10-34
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
Optional Extra Credit
Refine the Util and Customer Classes and Test Results
It is not obvious to the casual user that data that is printed for a customer, company, or
individual objects represent different objects, unless the user is made aware of the meaning
of the subtle differences in the displayed data. Therefore, you are asked to modify your code
to explicitly indicate the object type name in the text that is printed before the rest of the
object details, as follows:
[Customer] <customer details>
[Company] <company details>
[Individual] <individual details>
If you manually add the bracketed text string before the return values of the toString()
methods in the respective classes, then it produces a result that concatenates [Company] to
[Customer], and [Individual] to [Customer] for the subclasses of Customer.
Therefore, the solution is to use inherited code called from the Customer class that
dynamically determines the run-time object type name.
You can determine the run-time object type name of any Java object by calling its
getClass() method, which is inherited from the java.lang.Object class. The
getClass() method returns java.lang.Class object reference, through which you
can call a getName() method returning a String containing the fully qualified run-time
object name. For example, if you add this line to the Customer class:
String myClassName = this.getClass().getName();
The variable myClassName will contain a fully qualified class name that includes the
package name. The value that is stored in myClassName will be oe.Customer.
To extract only the class name, you must strip off the package name and the dot that
precedes the class name. This can be done by using a lastIndexOf() method in the
String class to locate the position of the last dot in the package name, and extract the
remaining text thereafter. To do this, add the getClassName() method to the Util
class, and call it from the toString() method in the Customer class.
7. Open Util.java in the Code Editor.
a. Add a public static String getClassName() method to determine the
run-time object type name, and returns only the class name.
public static String getClassName(Object o) {
String className = o.getClass().getName();
return className.substring(
className.lastIndexOf('.')+1,
className.length());
}
b. Save and compile Util.java. Note that JDeveloper automatically recompiles
other classes that are dependent on code in Util.java. JDeveloper has a built-
in class dependency checking mechanism.
Oracle10g: Java Programming 10-35
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
8. Open Customer.java in the Code Editor.
a. Prefix a call to the Util.getClassName() method before the rest of the
return value data in the toString() method, as follows:
return "[" + Util.getClassName(this) + "] " + id +;
b. Save and compile Customer.java.
c. Run the OrderEntry.java application to view the results.
d. In the above code, what does this represent? And, why do you pass a
parameter value this to the Util.getClassName() method?
Explain why the compiler accepts the syntax that is used.
Copyright 2004, Oracle. All rights reserved.
Using Arrays and Collections
Oracle10g: Java Programming 11-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Describe how to create arrays of primitives and
objects
Process command-line variables
Work with vectors
Explore other Java collections such as
Enumerators, Iterators, ArrayLists, and
Hashtables
Process command-line and system properties
Lesson Aim
This lesson shows how to use Java collection objects, introducing the Java array of
primitive, array of Object references and other collection classes such as Vectors,
Hashtables, Properties, Enumerators and Iterators.
Oracle10g: Java Programming 11-3
Copyright 2004, Oracle. All rights reserved.
What Is an Array?
An array is a collection of variables of the same type.
Each element can hold a single item.
Items can be primitives or object references.
The length of the array is fixed when it is created.
1
2
4
8
[0]
[1]
[2]
[3]
Action
Comedy
Drama
[0]
[1]
[2]
Arrays
Arrays are useful when you want a group of objects that you can manipulate as a whole.
For example, if you are writing a program to allow users to search for a movie, you would
probably store the list of categories in an array.
The slide shows an array of four integers and an array of three strings. The following slides
show how to create and initialize the arrays. As you will soon see, an array in Java is an
object.
Oracle10g: Java Programming 11-4
Copyright 2004, Oracle. All rights reserved.
Creating an Array of Primitives
1. Declare the array:
type is a primitive, such as int and so on.
2. Create the array object:
3. Initialize the array elements
(optional).
Null
arrayName
arrayName
1
2
4
0
0
0
arrayName
type[] arrayName;
or
type arrayName[];
// Create array object syntax
arrayName = new type[size];
Creating an Array of Primitives
1. Declaration: Create the variable that references the array.
2. Creation: Create an array object of the required type and size, and store a reference
to the array in the array variable.
3. Initialization: Initialize the array elements to the values that you want. This is
optional for an array of primitives, because the elements are initialized to default
values when the array object is created. The following slides explain these three steps
in detail.
Oracle10g: Java Programming 11-5
Copyright 2004, Oracle. All rights reserved.
Declaring an Array of Primitives
Create a variable to reference the array object:
When an array variable is declared:
Its instance variable is initialized to null until the
array object has been created
Its method variable is unknown until the object is
created
int[] powers; // Example
null
powers
Declaring an Array
There are two ways to declare an array:
Most Java programmers use the first style because it separates the variable type (in the
example, an array of int) from the variable name, making the code clearer to read.
When you declare an array variable, it refers to null initially, until you initialize the array
by using new.
Syntax Example
type[] arrayname; int[] powers;
type arrayname[]; int powers[];


Oracle10g: Java Programming 11-6
Copyright 2004, Oracle. All rights reserved.
Creating an Array Object for
an Array of Primitives
Create an array of the required length and assign
it to the array variable:
The array object is created by using the new
operator.
The contents of an array of primitives are
initialized automatically.
int[] powers; // Declare array variable
powers = new int[4]; //Create array object
powers
0
0
0
0
Creating an Array Object
If you are using the new operator, you must specify the array size inside the brackets. The
size must be an integer, but does not have to be a constant number; it could be an
expression that is evaluated at run time.
After the array object has been created, its length is fixed for the lifetime of the array.
Default Initialization of Array Elements
All elements in a new array of primitives are initialized automatically with default values,
as follows:
char elements are set to '\u0000'.
byte, short, int, and long elements are set to 0.
boolean elements are set to false.
float and double elements are set to 0.0.
Note: '\u0000' is Unicode 0000. Java uses the Unicode character set.
Examples of Valid Array Creation
Example 1
final int SIZE = 4;
int[] powers = new int[SIZE]; // SIZE is a constant
Oracle10g: Java Programming 11-7
Creating an Array Object (continued)
Examples of Valid Array Creation (continued)
Example 2
int[] examMarks;
int num = askUserHowManyStudents(); // set the value of num
examMarks = new int[num]; // array is a fixed size
Examples of Invalid Array Creation
Example 1
int powers[4]; // Invalid syntax: you cant set the size of
// the array in the declaration statement.
Example 2
int num;
int[] examMarks = new int[num]; // Compilation error: num has
// not been initialized
Oracle10g: Java Programming 11-8
Copyright 2004, Oracle. All rights reserved.
Initializing Array Elements
Assign values to individual elements:
Create and initialize arrays at
the same time:
int[] primes = {2, 3, 5, 7};
type[] arrayName = {valueList};
primes
[0]
[1]
[2]
2
3
5
7 [3]
arrayName[index] = value;
powers[0] = 1;
powers
[0]
[1]
[2]
1
0
0
0 [3]
Initializing Array Elements
First Method: Assign a Value to Each Array Element
To refer to an element in an array, use an index in brackets ([]) as shown in the slide.
Array elements are numbered from 0 to n-1, where n is the number of elements in the
array. In other words, the index of the first element in an array is 0, not 1.
Second Method: Use Array Initializers
As shown in the slide, there is a shorthand technique for creating and initializing an array
of primitives. Here, there is no need to use the new operator, and the length of the array is
set automatically. Note the use of the braces, and remember the semicolon at the end.
Array initializers are very useful for creating lookup tables, as in the following example:
int[] daysInMonth = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
This method is useful only if the value of each element is known when the array is created.
Oracle10g: Java Programming 11-9
Copyright 2004, Oracle. All rights reserved.
Creating an Array of Object References
1. Declare the array:
2. Create the array object:
3. Initialize the objects in the array.
null
arrVar
null
null
null
arrVar
Action
Comedy
Drama
arrVar
ClassName[] arrVar;
or
ClassName arrVar[];
// Create array object syntax
arrVar = new ClassName[size];
Creating an Array of Objects
The steps for creating an array of object references are the same as for arrays of primitives,
with one exception: You must initialize the elements in the array, because this is not done
automatically.
1. Declaration: The syntax is the same as for arrays of primitive objects. For example,
String[] categories;
declares a variable that can point to an array of String. If the variable is the
instance variable, the variable is set to null initially.
2. Creation: The syntax is the same as for arrays of primitive objects. For example,
categories = new String[3];
creates an array object of the correct type (String) and a size of 3. Initially, all of
the elements are set to null.
You can declare and create an array in the same statement. For example, String[]
categories = new String[3];
3. Initialization: Initialize the array elements to the values that you want. This is
described in the next slide.
Oracle10g: Java Programming 11-10
Copyright 2004, Oracle. All rights reserved.
Initializing the Objects in the Array
Assign a value to each array element:
Create and initialize the array at the same time:
String[] categories =
{"Action", "Comedy", "Drama"};
// Create an array of four empty Strings
String[] arr = new String[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = new String();
}
Initializing the Objects in an Array
As with arrays of primitives, there are two ways of initializing an array of object
references. You can initialize the array by assigning a value to each array element or by
initializing the array when you create it.
The length Property
Every array has a length attribute that contains the number of elements in the array. By
using length, you can avoid the need to hardcode or store the size of an array in your
code. Because the index of the first element in an array is 0, the index of its last element is
length 1.
The example in the slide uses length to loop through all the elements of an array to
create an array of empty strings.
Incidentally, the System class provides a useful method for copying all or part of an array
to another array. For more information, refer to System.arraycopy() in the Java
Development Kit (JDK) documentation.
Oracle10g: Java Programming 11-11
Copyright 2004, Oracle. All rights reserved.
Using an Array of Object References
Any element can be assigned to an object of the
correct type:
Each element can be treated as an individual
object:
An array element can be passed to any method;
array elements are passed by reference.
System.out.println
("Length is " + categories[2].length());
String category = categories[0];
Passing Arrays to Methods
Because arrays behave like objects when an array is passed into a method, it is passed by
reference like any other object. Therefore, if the method changes the contents of the array,
these changes operate on the original array, not a copy.
Oracle10g: Java Programming 11-12
Copyright 2004, Oracle. All rights reserved.
Arrays and Exceptions
ArrayIndexOutOfBoundsException occurs
when an array index is invalid:
NullPointerException occurs when you try to
access an element that has not been initialized:
Movie[] movieList = new Movie[3];
// The following will throw NullPointerException
String director = movieList[0].getDirector();
String[] list = new String[4];
//The following throws ArrayIndexOutOfBoundsException
System.out.println(list[4]);
Arrays and Exceptions
The slide shows the exceptions, or errors, that occur when you try to perform an invalid
operation on an array. Exceptions are covered in more detail in the lesson titled Throwing
and Catching Exceptions; these are included in this slide because you are likely to see
these errors if your code attempts to perform one of the operations that is described in the
slide.
If you try to access an invalid array index, then your program will crash with the error
ArrayIndexOutOfBoundsException.
If you try to access an array element that has not been initialized, your program will crash
with the error NullPointerException.
Oracle10g: Java Programming 11-13
Copyright 2004, Oracle. All rights reserved.
Multidimensional Arrays
Java supports arrays of arrays:
type[][] arrayname = new type[n1][n2];
int[][] mdarr = new int[4][2];
mdarr[0][0] = 1;
mdarr[0][1] = 7;
[0]
[1]
[2]
[3]
1 7
0 0
0 0
0 0
mdarr
[0][0] [0][1]
Multidimensional Arrays
Java supports multidimensional arrays; that is arrays of arrays:
int[][] tax = new int[5][4];
This declares and creates a two-dimensional matrix; the matrix contains five rows, each of
which contains four columns. Individual elements can be accessed as follows:
tax[rowIndex][colIndex] = value;
Advanced Topic: Nonsquare Multidimensional Arrays
The following example creates a multidimensional array with 10 rows, but the number of
columns in each row is different: the first row has one element, the second row has two
elements, and so on.
int[][] a = new int[10][];
for (int i = 0; i < a.length; i++) {
a[i] = new int[i + 1];
}
Oracle10g: Java Programming 11-14
Copyright 2004, Oracle. All rights reserved.
main() Revisited
main() has a single parameter, args.
args is an array of Strings that holds command-
line parameters:
public class SayHello {
public static void main(String[] args) {
if (args.length != 2)
System.out.println("Specify 2 arguments");
else
System.out.println(args[0]+" "+args[1]);
}
C:\> java SayHello Hello World
Passing Command-Line Parameters to main()
A reference to an array can be passed to any method. A good example is the main()
method that is used in Java applications. When you start a Java application, as opposed to a
Java applet, the system locates and calls the main() method for that class.
The main() method has a single parameter, which is a reference to an array of String
objects. Each String object holds a command-line parameter; the first element in the
array contains the first command-line parameter, not the name of the program as in C and
C++.
Command-Line Parameters Are Always Converted to Strings
It is important to note that command-line parameters are always represented by String
objects. Inside the main() method, you may need to convert a parameter to a primitive
type. For example, if one of the command-line parameters represents a number, you may
need to convert it into an int to perform some arithmetic with it.
Specifying Command-Line Parameters in JDeveloper
JDeveloper has a dialog box that you can use to specify command-line parameters for a
Java application. When you run the application from the JDeveloper environment,
JDeveloper passes the parameters into the main() method, as usual.
To specify command-line parameters in JDeveloper, select the Project > Project Properties
item from the menu bar, and click the Run/Debug tab. This tab has a field where you can
define command-line parameters.
Oracle10g: Java Programming 11-15
Copyright 2004, Oracle. All rights reserved.
Working with Variable-Length Structures
The Vector class implements a resizable array of
any type of object:
Creating an empty vector:
Creating a vector with an initial size:
Vector members = new Vector();
// Create a vector with 10 elements. The vector //
can be expanded later.
Vector members = new Vector(10);
Vectors
The Vector class, belonging to the java.util package, provides a resizeable
collection of objects. Remember that Java arrays are fixed in size, so a vector is useful
when you do not know how large an array will be at the time when you create the array.
For example, you may get a list of names from a server and want to store the names in a
local array. Before you fetch the data from the server, you have no idea how large the list
is.
You cannot create a vector of int, float, or any other primitive. Instead, you must use
the wrapper classes, which were discussed in the lesson titled Using Strings,
StringBuffer, Wrapper and Text-Formatting Classes, and create a vector of
Integer, Float, and so on.
The Vector class provides methods to modify and access the vector. The following slides
show some of these methods; the JDK 1.4 online documentation provides complete
information.
Oracle10g: Java Programming 11-16
Copyright 2004, Oracle. All rights reserved.
Modifying a Vector
Add an element to the end of the vector:
Add an element at a specific position:
Remove the element at a specific index:
String name = MyMovie.getNextName();
members.addElement(name);
// Remove the first element
members.removeElementAt(0);
// Insert a string at the beginning
members.insertElementAt(name, 0);
Modifying a Vector
When you add an element to a vector, the vector is automatically expanded by one element.
When you remove an element from a vector, the size of the vector decreases automatically.
When you insert an element at a specific position, all elements after that position increase
their indexes by 1.
Oracle10g: Java Programming 11-17
Copyright 2004, Oracle. All rights reserved.
Accessing a Vector
Get the first element:
Get an element at a specific position:
Find an object in a vector:
Get the size of a vector:
String s = (String)members.firstElement();
int size = members.size();
String s = (String)members.elementAt(2);
int position = members.indexOf(name);
Vector Indexing
The index of the first element of a vector is 0.
Note that a vector always contains objects. It can contain objects of different types. When
you get an element from a vector, you must cast it to the type of object that you added to
the vector.
Example of a Vector Containing Different Objects
The Vector.addElement() method accepts an Object as its parameter type. By
applying the principle of object reference substitution (subclass object plug-compatibility
with its superclass), the parameter can be any subclass of the java.lang. The
Object class, which includes just about every object that you can create. Here is a simple
example, assuming that you have a class called Member:
Vector v = new Vector();
v.addElement(new Member());
v.addElement("pat");
v.addElement(new Integer(10));
You must be sure of the type of object that you are getting returned from methods such as
Vector elementAt() or firstElement(). You can use the instanceof
operator to determine the object type that is returned by these methods.
Oracle10g: Java Programming 11-18
Copyright 2004, Oracle. All rights reserved.
Java Collections Framework
Java Collections Framework is an API architecture for
managing a group of objects that can be manipulated
independently of their internal implementation. It is:
Found in the java.util package
Defined by six core interfaces and some
implementation classes:
Collection interface: Generic group of elements
Set interface: Group of unique elements
List interface: Ordered group of elements
Map interface: Group of unique keys and their
values
SortedSet and SortedMap for a sorted Set and
Map
Java Collections Framework
Java Collections Framework is an API architecture for managing a collection of objects
that can be manipulated independently of their internal implementation. The framework is
a unified architecture for representing and manipulating collections. All collections
frameworks contain three things: Interfaces, Implementations, and Algorithms
The framework is built around six core interfaces and many implementation classes that are
found in the java.util package. The Collection interface is inherited by the Set
and List interfaces. The SortedSet is a subclass of Set, and SortedMap is a
subclass of Map.
Oracle10g: Java Programming 11-19
Java Collections Framework (continued)
The Collection interface is an abstraction representing a group of objects called
elements.
The Set interface models mathematical set abstraction. It is a collection that cannot
contain duplicate elements. The implementation classes are HashSet and TreeSet.
The List interface represents an ordered collection (or sequence) of elements, including
duplicates. Lists provide control over where each element is inserted. Elements can be
accessed by their integer index (position). Implementing classes are ArrayList and
LinkedList. Lists are similar to vectors.
The Map interface represents an object that maps one or more keys to their values. Maps do
not contain duplicate keys, and each key maps to a single value. Implementing classes are
HashMap and TreeMap. These are similar to a Hashtable.
Sorted collections are provided through the SortedSet and SortedMap interfaces,
which are sorted versions of Set and Map, respectively.
Oracle10g: Java Programming 11-20
Copyright 2004, Oracle. All rights reserved.
Collections Framework Components
Collections Framework is a set of interfaces and
classes used to store and manipulate groups of data
as a single unit.
Core Interfaces are the interfaces used to
manipulate collections, and to pass them from one
method to another.
Implementations are the actual data objects used
to store collections, which implement the core
collection interface.
Algorithms are pieces of reusable functionality
provided by the JDK.
Java Collections Framework Components
The design of programs often requires handling of groups of objects. This collection
framework offers a set of standard utility classes to manage the collection of these objects.
The framework is made up of three main components (listed on the previous page):
Core Interfaces: These allow collections to be manipulated, independent of their
implementation. These interfaces describe a common set of functionality, displayed
by collections, and enhance data exchange between collections. In object-oriented
languages, these interfaces, generally, are contained within a hierarchy.
Implementations: A small set of implementations exists as concrete implementations
of the core interfaces, which provide a data structure that a program can use. In a
sense, these are reusable data structures. The implementations come in three flavors:
general-purpose, wrapper, and convienience.
Algorithms: Methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. These algorithms are said to
be polymorphic because the same method can be used on many different
implementations of the appropriate collections interface. In essence, algorithms are
reusable functionality.
Oracle10g: Java Programming 11-21
Copyright 2004, Oracle. All rights reserved.
Using ArrayList and Hashtable
The ArrayList class:
Is a resizable implementation of the List interface
Allows manipulation of the array size
Has capacity that grows as elements are added to
the list
The Hashtable class:
Is a legacy class similar to Map implementations
Is used to store arbitrary objects that are indexed
by another arbitrary object
Is commonly used with String as the key to store
objects as values
ArrayList
The ArrayList is a resizable-array implementation of the List interface. It implements
all optional list operations, and permits all elements, including null. In addition to
implementing the List interface, this class provides methods to manipulate the size of the
array that is used internally to store the list.
Hashtable
The java.util.Hashtable class provides a table of keys, where each key is hashed
to an associated value object. The key and value can be any Java object. Here is an
example of using the Hashtable to store String objects on information about a book.
import java.util.Hashtable;
public class HashtableDemo {
public static void main (String args[]) {
Hashtable ht = new Hashtable();
ht.put ("title", "Beyond Freedom and Diginity");
ht.put ("author", "B.F. Skinner");
ht.put ("year", "1971");
System.out.println(ht);
System.out.println("Year: " + ht.get("year"));
}
}
Oracle10g: Java Programming 11-22
Copyright 2004, Oracle. All rights reserved.
Using Iterators
The Iterator interface, which is part of Java
Collection Framework, can be used to process a series
of Objects. The java.util.Iterator interface:
Implements an object-oriented approach for
accessing elements in a collection
Replaces the java.util.Enumeration approach
Contains the following methods:
hasNext() returns true if more elements exist.
next() returns the next Object, if any.
remove() removes the last element returned.
Another Type of Collection
Collections differ from arrays in that the members of a collection are not directly accessible
using indices, as you would with arrays. When using an Enumeration or an Iterator
you can only move the current item pointer to the first or next element of a collection. The
Enumeration was part of the standard Java API, and the Iterator was added with
Java Collection Framework API. An Iterator supports removal of an object from the
collection, whereas an Enumeration can only traverse the collection.
The following example creates a Vector containing several String elements, and then
calls the iterator() method to return an Iterator object. The loop uses the
next() method of the Iterator is to get elements and display their string value in
uppercase.
When hasNext() is false the loop terminates.
import java.util.Vector;
import java.util.Iterator;
:
Vector v = new Vector();
v.addElement("Jazz");
v.addElement("Classical");
v.addElement("Rock 'n Roll");
for (Iterator e = v.iterator(); e.hasNext(); ) {
String s = (String) e.next();
System.out.println(s.toUpperCase());
}
Oracle10g: Java Programming 11-23
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
Create Java arrays of primitives
Create arrays of object references
Initialize arrays of primitives or object references
Process command-line arguments in the main()
method
Use the Vector object to implement resizable
arrays
Use ArrayList and Hashtable classes
Oracle10g: Java Programming 11-24
Copyright 2004, Oracle. All rights reserved.
Practice 11: Overview
This practice covers:
Modifying the DataMan class
Create an array to hold the Customer, Company, and
Individual objects.
Add a method to ensure that the array is
successfully created and initialized.
Add a method to find a customer by an ID value.
Practice 11: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful
and you want to move on to this practice, then change to the les10 directory, load the
OrderEntryWorkspaceLes10 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes10 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes10 OrderEntryProjectLes10 -
Application Sources oe, and double- click on UML Class Diagram1
entry. This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 11-25
Practice 11: Using Arrays and Collections
Goal
The goal of this practice is to gain experience with Java array objects, and work with
collection classes such as the java.util.Vector class. You also work with command-
line arguments.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful
and you want to move on to this practice, then change to the les10 directory, load the
OrderEntryWorkspaceLes10 workspace, and continue with this practice.
Your Assignment
Continue to use JDeveloper to build on the application classes from the previous practices.
You will enhance the DataMan class to construct an array of Customer objects, and
then provide a method to find and return a Customer object for a given ID.
The Order class is modified to contain a vector of order items, requiring a method to add
items into the vector, and (optionally) another method to remove the items.
Modify DataMan to Keep the Customer Objects in an Array
1. Modify the DataMan class to build an array of customers.
a. Define a private static array of Customer objects named customers.
b. Initialize the array to a null reference.
2. Create a public static void method called buildCustomers() to populate the
array of customers. The array must hold six objects by using the four Customer
objects, the Company object and the Individual object that you have already
created.
a. In the body of the method, first test whether the customers variable is not
null, and if so, then return from the method without doing anything because a
non-null reference indicates that the customers array has been initialized. If
customers is null, then you must create the array object to hold the six
customer objects that are already created.
b. Now move (cut and paste) the definitions of the four existing Customer
objects, the Company, and the Individual into the body of this method,
after creating the array object. Then, delete the static keyword and class
name or type before each customer<n> variable name. Modify each variable
to be the name of the array variable followed by brackets enclosing an array
element number. Remember, array elements start with a zero base.
For example replace:
static Customer customer1 = new Customer();
with:
customers[0] = new Customer();
The example here assigns the customer object to the first element in the array.
Repeat this for each customer<n> object references in the code.
c. Create a static block that invokes the buildCustomers() method to create
and initialize the array of customer objects, when the DataMan class is loaded.
Place the block at the end of the DataMan class. (Static blocks in the class
definition are sometimes called class constructors.)
static
{
buildCustomers();
}
Oracle10g: Java Programming 11-26
Practice 11: Using Arrays and Collections (continued)
d. Save and compile the DataMan class. What other classes are compiled?
Explain the results. (Only fix errors that are related to the DataMan class, if
any. Any errors pertaining to OrderEntry class will be fixed after doing the
next set of questions).
Hint: Look in the Messages and Compiler tabs of the Log Window.
Modify DataMan to Find a Customer by ID
3. Create a public static method called findCustomerById(int custId), where
the argument represents the ID of the Customer object to be found. If found, then
return the object reference for the matching Customer, otherwise return a null
reference value.
a. Why is the customer array guaranteed to be initialized when the
findCustomerById() method is called? Thus, you can write code
assuming that the array is populated.
b. Write a loop to scan through the customers array, obtaining each customer
object reference to compare the custId parameter value with the return value
from the getId() method of each customer. If there is a match, then return
the customer object reference; otherwise, return a null.
c. Save and compile your DataMan class, only fixing the syntax errors that are
reported for the DataMan class.
4. You now fix the syntax errors in the OrderEntry class as a result of the changes
made to DataMan. The modifications that you make to OrderEntry.java fix
the syntax errors, and test the code that is added to the DataMan class.
a. In the Code Editor, locate and modify each line that directly refers to the
DataMan.customer<n> variables that previously existed.
Hint: You can quickly navigate to the error lines by double-clicking the error
message line in the Compiler tab of the Log Window.
Replace each occurrence of the DataMan.customer<n> text with a method
call to: DataMan.findCustomerById(n). For example, replace:
System.out.println(DataMan.customer1.toString());
with
System.out.println(
DataMan.findCustomerById(1).toString());
b. Save, compile, and run the OrderEntry.java file to test your changes.
Optional Extra Credit
Modify the Order Class to Hold a Vector of OrderItem Objects
Currently, the Order class has hardcoded creation of two OrderItem objects as instance
variables, and the details of each OrderItem object is set in the getOrderTotal()
method. This is impractical for the intended behavior of the Order class. You must now
replace the two OrderItem variables with a Vector that will contain the OrderItem
objects. Therefore, you must create methods to add and remove OrderItem objects to
and from the vector.
Oracle10g: Java Programming 11-27
Practice 11: Using Arrays and Collections (continued)
Modify the Order Class to Hold a Vector of OrderItem Objects (continued)
5. In the Order class, define a Vector of order items, and replace the OrderItem
instance variables, removing code dependent on the original OrderItem instance
variables.
a. Add a statement at the beginning of your class, after the package statement, to
import the java.util.Vector class.
b. Declare a new instance variable called items as a Vector object reference.
Also remove, or comment out, the declarations of the two instance variables
called item1 and item2, and the code that is using these variables.
Hint: The following methods directly use the item1 and item2 variables:
getOrderTotal(), showOrder().
c. In the Order no-arg constructor, add a line to create the item vector, as
follows:
items = new Vector(10);
d. Compile and save your changes to the Order class.
Modify OrderItem to Handle Product Information
6. Before you create the method to add an OrderItem object to the items vector,
you must first modify the OrderItem class to hold information about the product
being ordered. Each OrderItem object represents an order line item. Each
order line item contains information about a product that is ordered, its price, and
quantity that is ordered.
a. Edit the OrderItem class and add a new instance variable called product.
Declare the variable as a private int, and generate or write the
getProduct() method and setProduct() methods. Modify the
toString()method to add the product value between the lineNbr and
quantity.
b. Create an OrderItem constructor to initialize the object by using values that
are supplied from the following two arguments: int productId and
double itemPrice.
Initialize the item quantity variable to 1.
Note: The OrderItem class will not provide a no-arg constructor.
c. Save and compile the OrderItem class.
Modify Order to Add Products into the OrderItem Vector
7. In the Order class, create a new public void method called
addOrderItem()that accepts one argument: an integer called product,
representing an ID of the product being ordered. This method must perform the
following tasks:
a. Search the items vector for an OrderItem containing the supplied product.
To do this, create a loop to get each OrderItem element from the items
vector.
Oracle10g: Java Programming 11-28
Practice 11: Using Arrays and Collections (continued)
Hint: Use the size() method of the Vector object to determine the number of
elements in the vector. Use the getProduct() method of the OrderItem
class to compare the product value with the existing product value in the order
item.
If the product, with the specified ID, is found in an OrderItem elements from
the vector, then increment the quantity by using the setQuantity() method.
If the specified product does not exist in any OrderItem object in the vector,
then create a new OrderItem object by using the constructor that will accept
the product, and a price. Then add the new OrderItem object into the vector.
Note: Because line item numbers are set relative to their order, set the line
number for the OrderItem, by using the setLineNbr() method, after an
item is added to the vector. The line number is set using the size() of the
vector, because the elements are added to the end of the vector. For now,
assume that all products have a price of $5.00.
b. The orderTotal value will now be calculated as each product is added to the
order. Thus, you must also add the price of each product to orderTotal.
Hint: Use the getUnitPrice() method from the OrderItem class.
Because the orderTotal is now updated as each product is added to the
order, the getOrderTotal() method can simply return the orderTotal
value.
Note: This may already be done due to previous changes to the method.
c. Modify the showOrder() method to use an Enumeration technique to loop
through the items vector to display each OrderItem object by calling the
toString() method.
Hint: Import java.util.Enumeration, and use the Vector
elements() method to create an Enumeration. See your course notes for an
example, or ask your instructor for guidance.
d. Save and compile the Order class, and remove any syntax errors.
e. Test your changes to the OrderItem and Order classes by modifying the
OrderEntry class to add products 101, 102 to the first order object.
For example, before the call to showOrder(), enter the bold lines shown:
order.setCustomer(DataMan.findCustomerById(5));
order.addOrderItem(101);
order.addOrderItem(102);
order.addOrderItem(101);
order.showOrder();
f. Compile (eliminating syntax errors first), save and run OrderEntry.java.
Confirm that your results are accurate. For example, check whether the order
total is reported as $15.
Copyright 2004, Oracle. All rights reserved.
Structuring Code by Using
Abstract Classes and Interfaces
Oracle10g: Java Programming 12-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Define abstract classes
Define abstract methods
Define interfaces
Implement interfaces
Lesson Aim
This lesson shows how abstract classes and abstract methods can be defined and used in
Java. The lesson also introduces interfaces, and shows how they can be used to specify a set
of methods that interested classes can implement if they want to. You learn how to use
interfaces as an effective alternative to multiple inheritance.
Oracle10g: Java Programming 12-3
Copyright 2004, Oracle. All rights reserved.
Defining Abstract Classes
An abstract class cannot be instantiated.
Abstract methods must be implemented by
subclasses.
Interfaces support multiple inheritance.
Abstract
superclass
Concrete
subclasses
InventoryItem
Movie VCR
Abstract Classes
In Java, you can define classes that are high-level abstractions of real-world objects. Using
these high-level classes gives the designer a vote in what subclasses look like and even
which methods are mandatory in the subclass.
An abstract class is simply a class that cannot be instantiated; only its nonabstract subclasses
may be instantiated. For example, an InventoryItem does not contain sufficient detail to
provide anything meaningful to the business. It must either be a movie or a VCR. An
InventoryItem does, however, serve as a collection of data and behaviors that are
common to all items that are available for rent.
Abstract Methods
Abstract methods go a step beyond standard inheritance. An abstract method is defined only
within an abstract class, and must be implemented by a subclass. The class designer can use
this technique to decide exactly what behaviors a subclass must be able to perform. The
designer of the abstract class cannot determine how the behaviors will be implemented, only
that they will be implemented.
Interfaces
An interface is the specification of a set of methods, which is similar to an abstract class. In
addition to what an abstract class offers, an interface can effectively provide multiple
inheritance. A class can implement an unlimited number of interfaces but can only extend
one superclass.
Oracle10g: Java Programming 12-4
Copyright 2004, Oracle. All rights reserved.
Creating Abstract Classes
Use the abstract keyword to declare a class as
abstract.
public abstract class InventoryItem {
private float price;
public boolean isRentable()
}
public class Movie
extends InventoryItem {
private String title;
public int getLength()
public class Vcr
extends InventoryItem {
private int serialNbr;
public void setTimer()
Creating Abstract Classes
Java provides the abstract keyword, which indicates that a class is abstract. For example,
the InventoryItem class in the slide has been declared as abstract:
public abstract class InventoryItem {

}
InventoryItem is declared abstract because it does not possess enough intelligence or
detail to represent a complete and stand-alone object. The user must not be allowed to create
InventoryItem objects, because InventoryItem is only a partial class. The
InventoryItem class exists only so that it can be extended by more specialized
subclasses, such as Movie and Vcr.
What Happens If You Try to Instantiate an Abstract Class?
If you try to create an InventoryItem object anywhere in the program, then the compiler
flags an error:
InventoryItem i = new InventoryItem ();// Compiler error
The user can only create objects of the concrete subclasses:
Movie m = new Movie(); // This is fine
Vcr v = new Vcr(); // This is fine too
Oracle10g: Java Programming 12-5
Copyright 2004, Oracle. All rights reserved.
What Are Abstract Methods?
An abstract method:
Is an implementation placeholder
Is part of an abstract class
Must be overridden by a concrete subclass
Each concrete subclass can implement the
method differently.
The Need for Abstract Methods
When you design an inheritance hierarchy, there will probably be some operations that all
classes perform, each in its own way. For example, in a video rental business, the vendor
must know whether each item is rentable or not. Each type of item, however, determines
whether the item is rentable in a specific way.
To represent this concept in Java, the common is this item rentable method is defined in
the InventoryItem class. However, there is no sensible implementation for this method
in InventoryItem, because each different kind of item has its own requirements. One
approach may be to leave the method empty in the InventoryItem class:
public abstract class InventoryItem{
public boolean isRentable(); {
return true;
}
}
Oracle10g: Java Programming 12-6
The Need for Abstract Methods (continued)
This approach is not good enough because it does not force each concrete subclass to
override the method. For example, in the Vcr class, if the user forgets to override the
isRentable()method, then what will happen if the user calls the method on a Vcr
object? The isRentable()method in InventoryItem will be called and always
return true. This is not the desired outcome. The solution is to declare the method as
abstract, as shown on the next page.
Oracle10g: Java Programming 12-7
Copyright 2004, Oracle. All rights reserved.
Defining Abstract Methods
Use the abstract keyword to declare a method as
abstract:
Provide the method signature only.
The class must also be abstract.
Why is this useful?
Declare the structure of a given class without
providing complete implementation of every
method.
public abstract class InventoryItem {
public abstract boolean isRentable();

Defining Abstract Methods
To declare a method as abstract in Java, prefix the method name with the abstract
keyword as follows:
public abstract class InventoryItem {
abstract boolean isRentable();

}
When you declare an abstract method, you provide only the signature for the method,
which comprises its name, its argument list, and its return type. You do not provide a body
for the method. Each concrete subclass must override the method and provide its own body.
Now that the method is declared as abstract, a subclass must provide an implementation of
that method.
Abstract classes can contain methods that are not declared as abstract. Those methods can be
overridden by the subclasses but it is not mandatory.
Oracle10g: Java Programming 12-8
Copyright 2004, Oracle. All rights reserved.
Defining and Using Interfaces
An interface is like a fully abstract class:
All its methods are abstract.
All variables are public static final.
An interface lists a set of method signatures
without any code details.
A class that implements the interface must
provide code details for all the methods of the
interface.
A class can implement many interfaces but can
extend only one class.
What Is an Interface?
An interface is similar to an abstract class, except that it cannot have any concrete methods
or instance variables. It is a collection of abstract method declarations and constants; that is,
static final variables. It is like a contract that the subclass must obey.
Any class that implements an interface must implement some or all of the methods that are
specified in that interface. If it does not implement all of the methods, then the class is an
abstract class and a subclass of the abstract class must implement the remaining abstract
methods.
A class can implement many interfaces but can extend only one class. Java does not support
inheritance from multiple classes, but it does support implementing multiple interfaces. For
example:
class Movie extends InventoryItem implements Sortable, Listable {

}
As demonstrated earlier, Movie inherits all of the attributes and behaviors of
InventoryItem. In addition, it now must provide implementation details for all of the
methods that are specified in the Sortable and Listable interfaces. Those methods can
be used by other classes to implement specific behaviors such as a sort routine.
Oracle10g: Java Programming 12-9
Copyright 2004, Oracle. All rights reserved.
Examples of Interfaces
Interfaces describe an aspect of behavior that
different classes require.
For example, classes that can be steered support
the steerable interface.
Classes can be unrelated.
Steerable Nonsteerable
Examples of Interfaces
Interfaces describe an aspect of behavior that many different classes require. The name of an
interface is often an adjective such as Steerable, Traceable, Sortable, and so on.
This is in contrast to a class name, which is usually a noun such as Movie or Customer.
The Steerable interface may include such methods as turnRight(), turnLeft(),
returnCenter(), and so on. Any class that needs to be steerable may implement the
Steerable interface.
The classes that implement an interface may be completely unrelated. The only thing that
they may have in common is the need to be steered.
For example, the core Java packages include a number of standard interfaces such as
Runnable, Cloneable, and ActionListener. These interfaces are implemented by
all types of classes that have nothing in common except the need to be Cloneable, or to
implement an ActionListener.
Oracle10g: Java Programming 12-10
Copyright 2004, Oracle. All rights reserved.
Creating Interfaces
Use the interface keyword:
All methods are public abstract.
All variables are public static final.
public interface Steerable {
int MAXTURN = 45;
void turnLeft(int deg);
void turnRight(int deg);
}
Creating Interfaces
You can define an interface by using the interface keyword. All methods that are
specified in an interface are implicitly public and abstract. Any variables that are
specified in an interface are implicitly public, static, and final; that is, they are
constants.
Therefore, the interface definition that is shown in the slide is equivalent to the following
definition, where the public, static, final, and abstract keywords have been
specified explicitly.
public interface Steerable {
public static final int MAXTURN = 45;
public abstract void turnLeft(int deg);
public abstract void turnRight(int deg);
}
Oracle10g: Java Programming 12-11
Creating Interfaces (continued)
Because interface methods are implicitly public and abstract, it is a generally
accepted practice not to specify those access modifiers. The same is true for variables.
Because they are implicitly public, static, and final(in other words, constants), you
must not specify those modifiers.
Oracle10g: Java Programming 12-12
Copyright 2004, Oracle. All rights reserved.
Implementing Interfaces
Use the implements keyword:
public class Yacht extends Boat
implements Steerable {
public void turnLeft(int deg) {}
public void turnRight(int deg) {}
}
Implementing Interfaces
The slide shows an example of a Yacht class, that implements the Steerable interface.
Yacht must implement some or all of the methods in any interface that it implements; in
this case, Yacht may implement turnLeft() and turnRight().
A class can implement more than one interface by specifying a list of interfaces separated by
commas. Consider the following example:
public class Yacht
extends Boat
implements Steerable, Taxable {

}
Here, the Yacht class implements two interfaces: Steerable and Taxable. This means
that the Yacht class must implement all the methods that are declared in both Steerable
and Taxable.
Oracle10g: Java Programming 12-13
Copyright 2004, Oracle. All rights reserved.
Sort: A Real-World Example
Is used by several unrelated classes
Contains a known set of methods
Is needed to sort any type of object
Uses comparison rules that are known only to the
sortable object
Supports good code reuse
Sort
A sort is a classic example of the use of an interface. Many completely unrelated classes
must use a sort. A sort is a well-known and well-defined process that does not need to be
written repeatedly.
A sort routine must provide the ability to sort any object in the way that fits that particular
object. The traditional programming approach dictates several subroutines and an ever-
growing decision tree to manage each new object type. By using good OO programming
technique and interfaces, you can eliminate all of the maintenance difficulties that are
associated with the traditional approach.
The Sortable interface specifies the methods that are required to make the sort work on
each type of object that needs to be sorted. Each class implements the interface based on its
specific sorting needs. Only the class needs to know its object comparison, or sorting rules.
Implementing the sort in the OO way provides a model that supports very good code reuse.
The sort code is completely isolated from the objects that implement the sort.
Oracle10g: Java Programming 12-14
Copyright 2004, Oracle. All rights reserved.
Overview of the Classes
Created by the sort expert:
Created by the movie expert:
public class
MyApplication
public class Movie
implements Sortable
public interface
Sortable
public abstract
class Sort
Overview of the Classes
The slide shows the three classes and one interface that are involved in sorting a list of
videos. The classes are divided into two categories:
Classes that are created by the sort expert, who knows all about sort algorithms but
nothing about individual objects that people may want to sort
Classes that are created by the movie expert, who knows all about movies, but nothing
about sort algorithms
You see how interfaces can separate these two types of developers, enabling the separation
of unrelated areas of functionality.
Classes and Interfaces Used by the Example
The Sortable interface declares one method: compare(). This method must be
implemented by any class that wants to use the sort class methods.
The Sort class is an abstract class that contains sortObjects(), which is a
method to sort an array of objects. Most sort algorithms work by comparing pairs of
objects. sortObjects() does this comparison by calling the compare() method
on the objects in the array.
The Movie class implements the Sortable interface. It contains a compare()
method that compares two Movie objects.
MyApplication represents any application that must sort a list of movies. It can be
a form displaying a sortable list of movies.
Oracle10g: Java Programming 12-15
Copyright 2004, Oracle. All rights reserved.
How the Sort Works
MyApplication passes
an array of movies to
Sort.sortObjects().
sortObjects()
asks a movie to
compare itself with
another movie.
The movie
returns the
result of the
comparison.
sortObjects()
returns the
sorted list.
1
2 3
4
Sort
Movie
MyApplication
How the Sort Works
The slide shows the process of sorting a list of objects. The steps are as follows:
1. The main application passes an array of movies to Sort.sortObjects().
2. sortObjects()sorts the array. Whenever sortObjects() needs to compare
two movies, it calls the compare() method of one movie, passing it with the other
movie as a parameter.
3. The movie returns the results of the comparison to sortObjects().
4. sortObjects() returns the sorted list.
Oracle10g: Java Programming 12-16
Copyright 2004, Oracle. All rights reserved.
The Sortable Interface
Specifies the compare() method:
public interface Sortable {
// compare(): Compare this object to another object
// Returns:
// 0 if this object is equal to obj2
// a value < 0 if this object < obj2
// a value > 0 if this object > obj2
int compare(Object obj2);
}
The Sortable Interface
The Sortable interface specifies all of the methods and constants that are required for a
class to be sortable. In the example, the only method is compare().
Any class that implements Sortable must provide a compare() method that accepts an
Object argument and returns an int.
The result of the compare() method is as follows:
Note: It is entirely up to the implementer of compare() to determine the meaning of
greater than, less than, and equal to.
Value Meaning
Positive integer This object is greater than the argument.
Negative integer This object is less than the argument.
Zero This object is equal to the argument.

Oracle10g: Java Programming 12-17
Copyright 2004, Oracle. All rights reserved.
The Sort Class
Holds sortObjects():
public abstract class Sort {
public static void sortObjects(Sortable[] items) {
// Step through the array comparing and swapping;
// do this length-1 times
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length - 1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempitem = items[j+1];
items[j+1] = items[j];
items[j] = tempitem; } } } } }
The Sort Class
The Sort class contains the sortObjects() method that sorts an array of Sortable
objects. sortObjects() accepts an array of Sortable as its argument. It is legal
syntax to specify an interface type for a methods argument; in this case, it ensures that the
method will be asked to sort only objects that implement the Sortable interface. In the
example, sortObjects() executes a simple sort that steps through the array several
times, and compares each item with the next one and swaps them if necessary.
When sortObjects() needs to compare two items in the array, it calls compare() on
one of the items, passing the other item as the argument.
Note that sortObjects() knows nothing about the type of object that it is sorting. It
knows only that they are Sortable objects, and therefore it knows that it can call a
compare() method on any of the objects, and it knows how to interpret the results.
Interface as a Contract
You can think of an interface as a contract between the object that uses the interface and the
object that implements the interface. In this case, the contract is as follows:
The Movie class (the implementer) agrees to implement a method called
compare(), with parameters and return value specified by the interface.
The Sort class (the user) agrees to sort a list of objects in the correct order.
Oracle10g: Java Programming 12-18
Copyright 2004, Oracle. All rights reserved.
The Movie Class
Implements Sortable:
public class Movie extends InventoryItem
implements Sortable {
String title;
public int compare(Object movie2) {
String title1 = this.title;
String title2 = ((Movie)movie2).getTitle();
return(title1.compareTo(title2));
}
}
The Movie Class
The Movie class implements the Sortable interface. To call Sort.sortObjects(),
it must implement the Sortable interface, and if it implements the Sortable interface,
then it must implement the compare() method; this is the contract. The compare()
method takes an Object as an argument and compares it with the object on which it was
called.
In this case, you use the String compareTo() method to compare the two title strings.
compareTo() returns a positive integer, a negative integer, or zero depending on the
relative order of the two objects. When implementing compare(), you can compare the
two objects in any way you like, as long as you return an integer that indicates their relative
sort order.
Note: In the example, movie2 is an Object. So, it must be cast to Movie before you can
call getTitle() to get its title.
Oracle10g: Java Programming 12-19
Copyright 2004, Oracle. All rights reserved.
Using the Sort
Call Sort.sortObjects(Sortable []) with an array
of Movie as the argument:
class myApplication {
Movie[] movielist;
// build the array of Movie
Sort.sortObjects(movielist);
}
Using the Sort
To use the sort, you call Sort.sortObjects(Sortable []) from your application,
passing the array of objects that you want sorted. Each object that you want to sort must
implement the Sortable interface and provide the required compare() method. Only
the class implementing Sortable knows exactly how its objects are sorted.
You can make other types of objects in your application sortable. For example, you can
make the Rental and Member classes implement the Sortable interface and add a
compare() method to each class. Then, you can sort an array of Rental or Member by
calling Sort.sortObjects(). The compare() method in each of the classes can be
radically different or fundamentally the same. The only requirement is that the compare()
methods return an integer to indicate the relative sort order of the objects.
Oracle10g: Java Programming 12-20
Copyright 2004, Oracle. All rights reserved.
Using instanceof with Interfaces
Use the instanceof operator to determine
whether an object implements an interface.
Use downcasting to call methods that are defined
in the interface:
public void aMethod(Object obj) {

if (obj instanceof Sortable)
((Sortable)obj).compare(obj2);
}
Using instanceof with Interfaces
In the lesson about inheritance, you learned how to use the instanceof operator to test
whether the run-time type of an object matched a certain type.
You can also use instanceof with interfaces, as shown by the method in the slide. The
method takes an argument whose compile-time type is Object. At run time, the argument
can be any kind of object inherited from Object. The instanceof operator tests the
object to see whether it is an instanceof Sortable. In other words, does the object
support the Sortable interface?
This means that you do not care what kind of object you are dealing with. Your concern is
whether the object is capable of having the compare() method called on it.
If the object does implement the Sortable interface, then you cast the object reference
into Sortable so that the compiler lets you call the compare() method.
Oracle10g: Java Programming 12-21
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
An abstract class cannot be instantiated.
An abstract method has a signature but no code.
An interface is a collection of abstract methods to
be implemented elsewhere.
A class can implement many interfaces.
Implementing more than one interface is
comparable to multiple inheritance.
Oracle10g: Java Programming 12-22
Copyright 2004, Oracle. All rights reserved.
Practice 12: Overview
This practice covers:
Making an interface and abstract class
Implementing the java.lang.Comparable
interface to sort objects
Testing the abstract and interface classes
Practice 12: Overview
Note: To complete this practice, you must load a new workspace and use its contents.
Before starting this practice, open the \labs\les12start directory, load the
OrderEntryWorkspaceLes12Start workspace, to continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes11 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes11 OrderEntryProjectLes11 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 12-23
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
Goal
The goal of this practice is to learn how to create and use an abstract class, and how to create
and use an interface.
Note: To complete this practice, you must load a new workspace and use its contents.
Before starting this practice, open the \labs\les12start directory, load the
OrderEntryWorkspaceLes12Start workspace, to continue with this practice. The
solution for this practice is found in the \labs\les12 directory, by loading the
OrderEntryWorkspaceLes12 workspace.
Your Assignment
The OrderItem class currently only tracks a product as an integer. This is insufficient for
the business, which must know the name, description, and retail price of each product. To
meet this requirement, you create an abstract class called Product, and define three
concrete subclasses called Software, Hardware, and Manual.
To support the business requirement of computing a sales tax on the hardware products, you
create an interface called Taxable that is implemented by the Hardware subclass.
To test your changes, you must modify DataMan to build a list of Product objects, and
provide a method to find a product by its ID.
Modify OrderItem to hold an object reference for a Product, and not an integer
for ID of product, and also change Order to find a Product by its ID value.
Compile and run OrderEntry class to test the changes.
Create an Abstract Class and Three Supporting Subclasses
1. Add a public abstract class called Product to the OrderEntryProject.
a. Declare the following attributes and their getXXX() and setXXX() methods.
Hint: Use the JDeveloper Class Editor to rapidly build this class.
Note: Remember to add the abstract keyword before the class keyword in
the Source code after the Product.java file is created.
private static int nextProductId = 2000;
private int id;
private String name;
private String description;
private double retailPrice;
b. Define a public no-arg constructor that assigns the nextProductId to the ID
of a new product object, before incrementing nextProductId.
c. Add a public String toString() method to return the ID, name, and
retailPrice. Prefix with the class name by using getClassName(this)
from the Util class. Also, format retailPrice with Util.toMoney().
d. Compile and save the Product class.
e. Use JDeveloper and its Class Editor to create three concrete subclasses of the
Product class, each with attributes and initial values that are listed in the table
on the next page (generate or add the appropriate get and set methods):
Oracle10g: Java Programming 12-24
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
(continued)
1.e. (continued)
Subclass Attributes
Software String license = "30 Day Trial";
Hardware int warrantyPeriod = 6;
Manual String publisher = "Oradev Press";
f. Modify the no-arg constructor for Software, Hardware, and Manual
subclasses to accept three arguments for the product name, description, and
price. Use this code example for the Software class as an example:
public Software(String name,String desc,double price)
{
setName(name);
setDescription(desc);
setRetailPrice(price);
}
g. Compile and save all your new subclasses.
Modify DataMan to Provide a List of Products and a Finder Method
Use the new class definitions in the DataMan class to build an inventory of products.
2. In DataMan, create an object to hold a collection of products.
a. Create a private static inner class called ProductMap that extends
HashMap.
Note: Remember to import java.util.HashMap.
b. In the ProductMap inner class, create the following method to add product
objects to the collection. The ID is the key, and object reference is the value:
public void add(Product p) {
String key = Integer.toString(p.getId());
put(key, p); // use inherited put() method
}
c. Declare a private static ProductMap variable called products. For example:
private static ProductMap products = null;
d. Compile and save your DataMan class.
3. Create a method to populate the ProductMap variable with product objects.
a. Create the method called buildProducts() in the DataMan class as follows:
public static void buildProducts() {
if (products != null) return;
products = new ProductMap();
products.add(new Product());
}
b. Save and compile your code. Explain the compilation error that is listed for the
line adding the Product to the products map.
Oracle10g: Java Programming 12-25
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
(continued)
c. Fix the compilation error by adding concrete subclasses of the Product class.
Replace the line of code products.add(new Product()) with the
following text:
Note: Either copy the following code, or to save time, cut and paste the lines of
code from a file called \labs\les12.txt:
products.add(
new Hardware("SDRAM - 128 MB", null, 299.0));
products.add(new Hardware("GP 800x600", null, 48.0));
products.add(
new Software("Spreadsheet-SSP/V2.0", null, 45.0));
products.add(
new Software("Word Processing-
SWP/V4.5",null,65.0));
products.add(
new Manual("Manual-Vision OS/2x +", null, 125.0));
d. Compile the DataMan code and save your changes. Your compilation should
work this time.
e. At the end of the file, in the static block of DataMan, add a call to the
buildProducts() method.
f. Add the following method called findProductById() to return a Product
object matching a supplied ID.
public static Product findProductById(int id) {
String key = Integer.toString(id);
return (Product) products.get(key);
}
Note: Because products is a HashMap, you simply find the product object by
using its key; that is, the ID of the product.
g. Compile and save the changes to the DataMan class.
h. Test the DataMan code, and additional classes, by printing the product that is
found by its ID. Add the following line to OrderEntry class at the end of
main():
System.out.println("Product is: " +
DataMan.findProductById(2001));
i. Compile, save, and run the OrderEntry application to test the code.
Oracle10g: Java Programming 12-26
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
(continued)
Optional Extra Credit
Modify OrderItem to Hold Product Objects
4. Replace usages of the product variable as an int type with the Product class.
a. In OrderItem.java, change the type declaration for the product instance
variable to be Product instead of int.
b. Replace the two argument constructors with a single argument called
newProduct whose type is Product; that is, remove productId and
itemPrice arguments.
c. Change the body of the constructor to store the newProduct in the product
variable, and set the unitPrice to be the value that is returned by calling the
getRetailPrice() method of the product object.
d. Modify getProduct() method to return Product instead of an int, and
change setProduct() method to accept a Product instead of an int.
e. Alter the toString() method to display the item total instead of the
unitPrice.
Hint: Use the getItemTotal() method.
f. Compile and save your code changes. Only eliminate syntax errors from the
OrderItem class. Errors that are reported for the Order class are corrected in
the next step of this lab.
Modify Order to Add Product Objects into OrderItem
Alter the Order.java class to use the Product objects instead of an int value.
5. Make the following changes to the addOrderItem() method:
a. Rename the argument to be productId, and in the for loop replace:
productFound = (item.getProduct() == product);
with
productFound =
(item.getProduct().getId() == productId);
b. In the else section of the if statement, call findProductById() from
DataMan by using the productId value. If a product object is found, then
create the OrderItem by using with the product object; otherwise, do nothing.
For example:
item = new OrderItem(product, 5.0);
items.addElement(item);
becomes:
Product p = DataMan.findProductById(productId);
if (p != null) {
item = new OrderItem(p);
items.addElement(item);
}
Oracle10g: Java Programming 12-27
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
(continued)
6. Test changes that are made to your code supporting the Product class and its
subclasses, by modifying OrderEntry class to use the new product ID values.
a. Because the ID of Product objects (or its subclasses) start at 2000, edit the file
OrderEntry.java, replacing parameter values in all the calls to the
order.addOrderItem() method, as shown by the following table:
Replace With
101 2001
102 2002
b. Save, compile, and run the OrderEntryProject project, and check the
changes to the printed items. Check whether the price calculations are still
correct.
Create and Implement the Taxable Interface
7. Create an interface called Taxable.
a. Right-click the OrderEntryProject.jpr file in the Navigator, and
select New from the pop-up menu. Enter Taxable in the class name and
ensure that you clear Generate Default Constructor.
Then, click the OK button.
b. In the Code Editor, replace the keyword class with the keyword interface.
c. Add the following variable and method definitions to the interface:
double TAX_RATE = 0.10;
double getTax(double amount);
Note: Remember that all variables are implicitly public static final, and
that methods are all implicitly public.
The implementer of the interface must multiply the amount, such as a price, by
the TAX_RATE and return the result as a double.
d. Compile and save the interface.
8. Edit the Hardware class to implement the Taxable interface.
a. Add the bold text to the class definition to implement the interface, as shown:
public class Hardware extends Product
implements Taxable {
b. Compile the Hardware class and explain the error.
c. Add the following method to complete the implementation of the interface.
public double getTax(double amount) {
return amount * TAX_RATE;
}
Note: To perform the two steps above, select the Tools > Implement Interface
menu item, and select oe.Taxable from the tree in the Implement Interface
window, then click OK. JDeveloper generates all the code except for the return
value calculation. You can modify the generated body to return the desired
result, as shown above. Alternatively, you can also type the code manually in the
Source.
d. Compile and save the Hardware class.
Oracle10g: Java Programming 12-28
Practice 12: Structuring Code by Using Abstract Classes and Interfaces
(continued)
9. Change the OrderItem class to obtain the tax for each item.
a. Add a public double getTax() method to determine whether the
Product in the item is taxable. If the product is taxable, then return the tax
amount for the item total (use getItemTotal() method); otherwise, return
0.0. For example:
double itemTax = 0.0;
if (product instanceof Taxable)
{
itemTax =((Taxable)
product).getTax(getItemTotal());
}
b. Modify the toString() method to display the tax amount for the item, if and
only if the product is taxable. Use the getTax() method that you created, and
format the value with Util.toMoney().
c. To view changes, compile OrderItem.java, and run OrderEntry.
10. Modify the Order class to display the tax, and order total to include the tax.
a. In the showOrder() method, add a local double variable called taxTotal
initialized to 0.0 that accumulates the total tax for the order.
b. Modify the for loop by using the Enumeration to call the getTax() method
for each item, and add the value to taxTotal.
Hint: To do this, you must cast the return value of e.nextElement() to
OrderItem.
c. Add three System.out.println() statements after the loop: one to print
the taxTotal, the second to print the orderTotal including taxTotal,
and the last without a parameter to print a blank line. Use the
Util.toMoney() method to format the totals.
d. To view results, compile and save Order.java, and then run OrderEntry.
Copyright 2004, Oracle. All rights reserved.
Throwing and Catching Exceptions
Oracle10g: Java Programming 13-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Explain the basic concepts of exception handling
Write code to catch and handle exceptions
Write code to throw exceptions
Create your own exceptions
Lesson Aim
Many Java methods in the Java Development Kit (JDK) class library throw an exception
when they encounter a serious problem that they do not know how to handle. This lesson
explains how exceptions work in Java, and shows you how to handle such exceptions in
your applications.
Oracle10g: Java Programming 13-3
Copyright 2004, Oracle. All rights reserved.
What Is an Exception?
An exception is an unexpected event.
What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. For example, trying to access an element outside the bounds of
an array, trying to divide a number by zero, and trying to access a URL with an invalid
protocol are all exceptions.
What Is an Error?
An error in Java is an unrecoverable abnormal condition. For example, an error condition
exists if there is some internal error in Java Virtual Machine (JVM) or if JVM runs out of
memory.
What Is the Difference?
Your code can handle an exception and move on; if an error occurs, then your program must
exit.
Oracle10g: Java Programming 13-4
Copyright 2004, Oracle. All rights reserved.
How Does Java Handle Exceptions?
A method throws an exception.
A handler catches the exception.
Yes No
Handler
for this
exception?
Exception object
Exception Handling in Java
When an exception occurs within a Java method, the method creates an Exception object
and hands it off to the run-time system. This process is called throwing an exception. The
Exception object contains information about the exception, including its type and the
state of the program when the error occurred.
When a Java method throws an exception, the run-time system searches all the methods in
the call stack in sequence to find one that can handle this type of exception. In Java
terminology, this method catches the exception.
If the run-time system does not find an appropriate exception handler, then the whole
program terminates.
The following slides discuss some of the advantages of Javas exception handling over
traditional error handling in other languages.
Oracle10g: Java Programming 13-5
Copyright 2004, Oracle. All rights reserved.
Advantages of Java Exceptions:
Separating Error Handling Code
In traditional programming, error handling often
makes code more confusing to read.
Java separates the details of handling unexpected
errors from the main work of the program.
The resulting code is clearer to read and,
therefore, less prone to bugs.
Advantage 1: Separating Error Handling Code from Other Code
In traditional programming, error handling often makes code more confusing to read.
For example, if you want to write a function that reads the first line of a file, then the
pseudocode for the function may be:
readFirstLine {
open the file; // the open could fail
read the first line; // the read could fail
close the file; // the close could fail
}
The traditional way of checking for the potential errors in this function is to test each
possible error and set an error code. The table on the next page compares the traditional
method with Javas exception handling; the original three statements are in bold.
Oracle10g: Java Programming 13-6
Advantage 1: Separating Error Handling Code from Other Code (continued)
Java separates the details of handling unexpected errors from the main work of the program,
making the code clearer to read (which, in turn, makes it less prone to bugs).
Traditional Error Handling Java Exception Handling
readFirstLine {
int errcode = 0;
open the file;
if (openError) {
errcode = OPEN_ERR;
}
else {
read the first line;
if (readError) {
errcode = READ_ERR;
}
close the file;
if (closeError) {
errcode = errcode
and CLOSE_ERR;
}
}
return errcode;
}

readFirstLine {
try {
open the file;
read the first line;
close the file;
}
catch (openError) {
handle error;
}
catch (readError) {
handle error;
}
catch (closeError) {
handle error;
}
}


Oracle10g: Java Programming 13-7
Copyright 2004, Oracle. All rights reserved.
Advantages of Java Exceptions:
Passing Errors Up the Call Stack
method4
method3
method2
method1
//handle error
Error
code
Error
code
Error
code
method4
method3
method2
Method1
//handle ex
Exception
ex
Each method checks for
errors and returns an error
code to its calling method.
method4 throws an
exception; eventually
method1 catches it.
Traditional error
handling
Java exceptions
Advantage 2: Passing Errors Up the Call Stack
A Java exception is sent immediately to the appropriate exception handler; there is no need
to have if statements at each level to pass the error up the call stack. For example, a series
of nested methods can handle errors as follows:
method1 handles all errors
method1 calls method2
method2 calls method3
method3 calls method4
The following table shows the steps that are taken by traditional error handling and Java
exception handling if an error occurs in method4. Exception handling requires fewer steps.
Traditional Error Handling Java Exception Handling
1. method4 returns an error code to
method3.
2. method3 checks for errors, and
passes the error code to method2.
3. method2 checks for errors, and
passes the error code to method1.
4. method1 handles the error.
1. method4 throws an exception and it is
propagated to method3.
2. method3 receives a return from method 4 and
propagates it to method2.
3. method2 receives a return from method3 and
propagates it to method1.
4. method1 catches and handles the exception.


Oracle10g: Java Programming 13-8
Copyright 2004, Oracle. All rights reserved.
method3
Advantages of Java Exceptions:
Exceptions Cannot Be Ignored
If method3 ignores the
error, then it will never be
handled.
method4
method2
method1
//handle error
Error
code
The exception must be
caught and handled
somewhere.
Traditional error
handling
Java exceptions
method4
method3
method2
method1
//handle ex
Exception
ex
Advantage 3: Exceptions Cannot Be Ignored
After a method has thrown an exception, it cannot be ignored; it must be caught and handled
somewhere. In the example in the slide, the programmer writing method3, method2, or
method1 can choose to ignore the error code that is returned by method4, in which case
the error code will be lost.
Oracle10g: Java Programming 13-9
Copyright 2004, Oracle. All rights reserved.
Checked Exceptions, Unchecked
Exceptions, and Errors
All errors and exceptions extend the Throwable class.
Throwable
Error Exception
Unrecoverable
errors
Checked
exceptions
Unchecked (run-time)
exceptions
RuntimeException
Standard Error and Exception Classes
All the standard errors and exceptions in Java extend the Throwable class.
Errors
Errors are extensions of the Error class. If an error is generated, then it normally indicates
a problem that will be fatal to the program. Examples of this type of error are: running out of
memory or being unable to load a class. Do not catch Errors in your Java code.
Unchecked Exceptions
Unchecked (or run-time) exceptions are extensions of the RuntimeException class. All
the standard run-time exceptions (for example, dividing by zero or attempting to access an
array beyond its last element) are extensions of RuntimeException. You can choose
what to do with run-time exceptions; you can check for them and handle them, or you can
ignore them. If a run-time exception occurs and your code does not handle it, JVM
terminates your program and prints the name of the exception and a stack trace.
Oracle10g: Java Programming 13-10
Standard Error and Exception Classes (continued)
Checked Exceptions
Checked exceptions are extensions of the Exception class. Checked exceptions must be
caught and handled somewhere in your application; this rule is enforced by the compiler.
Exceptions that you create yourself must extend the Exception class.
Note: Run-time exceptions do not need to be caught, but they cannot be ignored. If they are
not caught, then the program terminates with an error.
Oracle10g: Java Programming 13-11
Copyright 2004, Oracle. All rights reserved.
What to Do with an Exception
Catch the exception and handle it.
Allow the exception to pass to the calling method.
Catch the exception and throw a different
exception.
Handling Exceptions
If you call a method that may throw a checked exception, then you have three choices:
Catch the exception and handle it.
Allow the exception to pass through your method; another handler somewhere else
must handle it.
Catch the exception and throw a different exception; the new exception must be
handled by another handler somewhere else.
Run-Time Exceptions
Your code does not need to handle run-time exceptions; these are handled by JVM. JVM
handles run-time exceptions by terminating your program; if you do not want a run-time
exception to have this effect, then you must handle it.
Oracle10g: Java Programming 13-12
Copyright 2004, Oracle. All rights reserved.
Catching and Handling Exceptions
Enclose the method
call in a try block.
Handle each
exception in a catch
block.
Perform any final
processing in a
finally block.
try {
// call the method
}
catch (exception1) {
// handle exception1
}
catch (exception2) {
// handle exception2
}
finally {
// any final processing
}
Catching and Handling Exceptions
If a block of code calls one or more methods that may throw exceptions, then enclose the
code in a try block, with one or more catch blocks immediately after it. Each catch
block handles a particular exception.
You can add a finally block after all the catch blocks. A finally block may be
executed, depending on what happens before the block (for example, System.exit).
How Do You Know Whether a Particular Java Method Throws an Exception?
All the standard Java classes are documented in the JDK documentation; part of the
specification for each method is a list of exceptions that the method may throw. Whenever
you call a Java method, you must know what exceptions may arise as a consequence. For
example, the following are declarations that are taken from the JDK documentation for
java.io.FileInputStream:
public FileInputStream(String name)
throws FileNotFoundException
public int read() throws IOException
General Guidelines for try-catch-block Structures
A try block must have at least one catch block, or a finally block.
- A catch block is required for checked exceptions, unless it is propagated.
A try block can have more than one catch block.
The finally block always executes, whether exceptions occur or not.
Oracle10g: Java Programming 13-13
Copyright 2004, Oracle. All rights reserved.
Catching a Single Exception
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
Catching a Single Exception
The example in the slide uses Integer.parseInt() to process the value that an end
user has entered on a form. parseInt() throws a NumberFormatException if the
string is not an integer value. The catch block can handle this exception by prompting the
user to enter the value again.
Oracle10g: Java Programming 13-14
Copyright 2004, Oracle. All rights reserved.
Catching Multiple Exceptions
try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}
Catching Multiple Exceptions
The example constructs a URL and then connects to it. The example uses two catch
blocks, because there are two possible exceptions that can occur. If an exception occurs in
the try block, then JVM checks each catch handler in sequence until it finds one that
deals with that type of exception; the rest of the try block is not executed.
A catch statement catches the exception that is specified as well as any of its subclasses.
For example, the javadoc for MalformedURLException shows that it extends
IOException; thus, you can replace the two catch blocks with one:
catch (IOException e) {
System.err.println("Operation failed: " + e);
}
You will use a single catch block if you wanted your code to behave in the same way for
either exception.
Order of catch Statements
Note that you get a compiler error if you specify a catch handler for a superclass first,
followed by a catch handler for a subclass. This is because the superclass catch handler
hides the subclass catch handler, which will therefore never see any exceptions. For
example, reversing the two catch blocks in the example causes a compiler error.
Oracle10g: Java Programming 13-15
Copyright 2004, Oracle. All rights reserved.
Cleaning Up with a finally Block
FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}
Cleaning Up with a finally Block
The example opens a file and counts the characters in the file. The file is then closed, even if
the read operation causes an exception. A finally block is useful when you want to
release system resources, such as open files.
A finally block is executed regardless of how the try block exits:
Normal termination, by falling through the end brace
Because of return or break statement
Because an exception was thrown
Note: f.close() can throw an IOException and, therefore, must be enclosed in its
own trycatch block inside the finally block.
Oracle10g: Java Programming 13-16
Copyright 2004, Oracle. All rights reserved.
Catching and Handling Exceptions:
Guided Practice
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}
Catching and Handling Exceptions
Examine the code that is shown in the slide, and describe what it is doing. Note that the url
argument is a string such as http://www.oracle.com.
1. What will be printed to standard output if the URL constructor executes without
throwing an exception?
2. What will be printed to standard output if the URL constructor throws a
MalformedURLException?
Oracle10g: Java Programming 13-17
Copyright 2004, Oracle. All rights reserved.
Catching and Handling Exceptions:
Guided Practice
void myMethod () {
try {
getSomething();
} catch (IndexOutOfBoundsException e1) {
System.out.println("Caught IOBException ");
} catch (Exception e2) {
System.out.println("Caught Exception ");
} finally {
System.out.println("No more exceptions ");
}
System.out.println("Goodbye");
}
Catching and Handling Exceptions (continued)
1. What will be printed to standard output if getSomething() throws an
IllegalArgumentException?
2. Would anything change if the order of the two catch blocks was reversed? That is:

try
catch (Exception e) {}
catch (IndexOutOfBoundsException e) {}

Oracle10g: Java Programming 13-18


Copyright 2004, Oracle. All rights reserved.
Allowing an Exception to Pass to the
Calling Method
Use throws in the method declaration.
The exception propagates to the calling method.
public int myMethod() throws exception1 {
// code that might throw exception1
}
public URL changeURL(URL oldURL)
throws MalformedURLException {
return new URL("http://www.oracle.com");
}
Allowing an Exception to Pass to the Calling Method
If you cannot meaningfully handle an exception locally, or you choose not to, then it can be
passed back to the code that called your method.
In the example in the slide, the URL constructor can throw a
MalformedURLException, but the method does not catch this exception locally.
Instead, the exception passes automatically to the method that called changeURL().
If you want an exception to propagate to the calling method, then you must declare the
exception in your method declaration:
public URL changeURL(URL oldURL) throws MalformedURLException
{

}
The method that calls changeURL() can catch MalformedURLException, or it can
also let the exception pass through. If the calling method allows the exception to pass
through, then it must also contain throws MalformedURLException in its
declaration.
Oracle10g: Java Programming 13-19
Copyright 2004, Oracle. All rights reserved.
Throwing Exceptions
Throw exceptions by using the throw keyword.
Use throws in the method declaration.
public String getValue(int index) throws
IndexOutOfBoundsException {
if (index < 0 || index >= values.length) {
throw new IndexOutOfBoundsException();
}

}
throw new Exception1();
Throwing Exceptions
You can throw exceptions in your own code to indicate some abnormal situation. The
exceptions that you throw can be standard system exceptions, or you can create your own.
If you do decide to throw exceptions, remember that what you are really doing is creating an
object and passing it to a higher-level method. Therefore, you must create this exception
object by using the new operator, as shown in the slide.
A method can throw multiple exceptions, in which case the exception names are separated
by commas.
Four types of exception are System, Application, Run-time and Custom. The
java.lang.IndexOutOfBoundsException is a run-time Exception.
Oracle10g: Java Programming 13-20
Copyright 2004, Oracle. All rights reserved.
Creating Exceptions
Extend the Exception class.
public class UserFileException extends Exception {
public UserFileException (String message) {
super(message);
}
}
public class MyException extends Exception { }
Creating Exceptions
You can create your own exceptions by extending the Exception class. You must not
extend the RuntimeException class because this is for common exceptions that need
not be checked.
The example creates an exception called UserFileException with one constructor that
just calls the constructor of the superclass.
You can create multiple exceptions for different circumstances in your code. For example, if
your code accesses different files, then you can throw a different exception for each file.
This approach is useful for several reasons:
You can handle each exception differently.
If your exception handlers print out the exception, then this gives you or your users
more information about where the exception occurred.
You can customize your exception. For example, you can add a
UserFileException constructor that sets an attribute for the line number of the
file and a method that prints out the line number.
Oracle10g: Java Programming 13-21
Copyright 2004, Oracle. All rights reserved.
Catching an Exception and Throwing a
Different Exception
catch (exception1 e) {
throw new exception2();
}
void readUserFile() throws UserFileException {
try {
// code to open and read userfile
}
catch(IOException e) {
throw new UserFileException(e.toString());
}
}
Catching an Exception and Throwing a Different Exception
The example catches IOException and handles it by throwing UserFileException.
You do this if you want this method to throw a different exception from other methods. The
method uses the throws keyword in its declaration to indicate that it throws a
UserFileException.
Oracle10g: Java Programming 13-22
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to do the
following:
Use Java exceptions for robust error handling
Handle exceptions by using try, catch, and
finally
Use the throw keyword to throw an exception
Use a method to declare an exception in its
signature to pass it up the call stack
Oracle10g: Java Programming 13-23
Copyright 2004, Oracle. All rights reserved.
Practice 13: Overview
This practice covers:
Creating a custom exception
Changing DataMan finder methods to throw
exceptions
Handling the exceptions when calling the DataMan
finder methods
Testing the changes to the code
Practice 13: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les12 directory, load the
OrderEntryWorkspaceLes12 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes12 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes12 OrderEntryProjectLes12 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 13-24
Practice 13: Throwing and Catching Exceptions
Goal
The goal of this practice is to learn how to create your own exception classes, throw an
exception object by using your own class, and handle the exceptions.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you want to move on to this practice, then change to the les12 directory, load the
OrderEntryWorkspaceLes12 workspace, and continue with this practice.
Your Assignment
The application does not appropriately handle situations when an invalid customer ID is
supplied to the DataMan.findCustomerById() method, or an invalid product ID is
given to the DataMan.findProductById() method. In both cases, a null value is
returned. Your tasks are to:
Create a user-defined (checked) exception called oe.NotFoundException.
Modify DataMan.findCustomerById() to throw the exception when an invalid
customer ID is provided.
Modify the DataMan.findProductById()method in the DataMan class to
throw the exception if the given product ID is not valid (that is, not found).
Create the NotFoundException Class
1. In the OrderEntryProject, create a new class called NotFoundException.
a. Right-click the project name in the Navigator, and select New from the pop-
up menu. From the New gallery window, ensure that the Category selected is
General and the Item selected is Java Class. Enter the class name
NotFoundException, and make it a subclass of java.lang.Exception.
b. Modify the default no-arg constructor to accept a message String argument,
and pass the string to the superclass constructor. For example:
public NotFoundException(String message) {
super(message);
}
c. Compile and save the NotFoundException class.
Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry
2. Edit DataMan.java, and modify the findCustomerById() method to throw
the NotFoundException when the given customer ID is not found in the array.
a. At the end of the for loop, if the local customer object reference is null (that
is, the customer is not found), then throw an exception object, using the
following error message structure in the constructor argument:
"Customer with id " + custId + " does not exist
b. Compile the DataMan class. Explain the error.
c. Fix the error by modifying the method declaration to propagate the exception.
d. Compile DataMan again. What errors do you get this time? Explain the errors.
Oracle10g: Java Programming 13-25
Practice 13: Throwing and Catching Exceptions (continued)
e. Fix the compilation errors by handling the exceptions with a try-catch block
in the OrderEntry class. For simplicity, use one try-catch block to handle
all the calls to the DataMan.findCustomerById() methods. Alternatively,
if desired, then handle each call in its own try-catch block.
try { // calls to findCustomerById() here
}
catch (NotFoundException e) {
// handle the error here
}
In the catch block, you can use the exceptions inherited methods to display
error information. Use the following two methods to display error information:
- e.printStackTrace() to display the exception, message, and stack
trace
- e.getMessage() to return the error message text as a String.
f. Compile, save, and run OrderEntry.java. Test your code with the errors.
3. Now modify the findProductById() to throw NotFoundException when
the supplied product ID is not found in the product map.
a. The findProductById() method calls get(key) to find a product from
the HashMap. If get(key) returns a null, then throw a
NotFoundException by using the following error message; otherwise, return
product object found. You must also add the product declaration line and modify
the current return statement.
"Product with id " + id + " is not found"
b. Modify the findProductById() declaration to propagate the exception.
c. Compile and save DataMan, and explain the compile time error reported.
d. In the Order class, modify the addOrderItem() to propagate the exception.
e. Compile the Order class, and explain why it compiles successfully.
f. In OrderEntry.java, use a value of 9999 as the product ID in the first call
to order.addOrderItem(2001). Compile and run OrderEntry.
Explain why the application terminates immediately after adding product 9999.
g. In Order.java, remove throws NotFoundException from the end of
the addOrderItem() method declaration. Write a try-catch block to
handle the exception in this method.
Hint: You must return from the method in the catch block to ensure the
itemTotal is not affected.
h. Compile Order and run OrderEntry.java, and explain the difference in
output results.
i. In OrderEntry, replace the 9999 product ID with 2001. Compile, save, and
run.
Copyright 2004, Oracle. All rights reserved.
User Interface Design: Swing Basics
Planning the Application Layout
Oracle10g: Java Programming 14-2
Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
Explain Abstract Window Toolkit (AWT), Swing,
and Java Foundation Classes (JFC)
Detail the Swing UI containment hierarchy
Describe how to use layout managers
Add UI containers to an application to group
components
Embed UI components into UI containers
Use the Swing pluggable look and feel
Lesson Aim
This lesson shows you how to provide a Java applet or application with a graphical user
interface based on Swing components, such as buttons and text fields. Participants learn how
to embed Swing components into Swing containers and how to use layout managers to
provide an interface that is usable across platforms.
Oracle10g: Java Programming 14-3
Copyright 2004, Oracle. All rights reserved.
Running Java UI Applications
Running Java UI Applications
Java applications and applets are not limited to run on any one platform. You can run them
on any platform that supports a Java Virtual Machine (JVM) because each of the platforms
has its own specific display methods and characteristics.
Java provides layout managers that help to optimize the look and feel of your application for
the platform on which it is running. This is performed dynamically without any need for
code modification. This behavior is one of the aspects of the Java write once, run
anywhere (WORA) concept.
The screenshot on the slide uses different layout managers to produce the desired effect. It
uses Border, Grid, and GridBag layouts. By combining different layout managers, you can
obtain the layout that you want and deploy the program on multiple platforms.
Oracle10g: Java Programming 14-4
Copyright 2004, Oracle. All rights reserved.
AWT, Swing, and JFC
AWT, or Abstract Window Toolkit (java.awt):
A graphical user interface library
The predecessor to Swing components and the
foundation for Swing and JFC
Swing (javax.swing):
A more powerful graphical user interface library
Built on top of the AWT class hierarchy
Java Foundation Classes (JFC):
A collection of APIs including: AWT, Swing,
Accessibility API, Pluggable Look and Feel
Java 2D API, Drag and Drop support (since JDK 1.2)
Abstract Window Toolkit (java.awt)
The AWT was Javas original toolkit or set of visual components for the development of
graphical user interface applications. AWT is the foundation upon which Swing and the rest
of the JFC are constructed. AWT was not designed for high-powered UI development,
which can be appreciated when you understand that it has a smaller set of components.
AWT classes are found in the java.awt package and its subpackages.
Swing (javax.swing)
Swing provides lightweight components built on top of the AWT library. It provides many
more components that are intended for high-powered user interface, which are more
efficient than their AWT counterparts. Swing components adhere to the AWT event
handling model that was introduced in JDK 1.1. Swing classes are found in the
javax.swing package and its subpackages.
Oracle10g: Java Programming 14-5
Java Foundation Classes (JFC)
The Java Foundation Classes is a set of classes and APIs that was first released with JDK
1.1. The version of JFC that is included in JDK 1.2 contains:
AWT and the Swing GUI components
Accessibility API for people with disabilities
Pluggable look and feel, to adapt the UI to an operating system look and feel
Java 2D API for two-dimensional graphics and imaging
Drag and drop support
Because Swing is the major component of JFC, the terms Swing and JFC are often used
interchangeably. Oracle JDeveloper 10g supports JDK 1.4.2, so Swing is fully supported.
Note: You can create Java client applications that rely on standard Swing components in
your application. The Java client application in JDeveloper is known as a JClient
application. When a JClient form has been deployed to a client machine, users can use it to
display and manipulate data in the form. This course is not intended to teach you about
JClient, only to show you how to develop Java applications using JDeveloper.
Oracle10g: Java Programming 14-6
Copyright 2004, Oracle. All rights reserved.
JButton JSlider JTree
JComboBox JTextField JProgressBar
InventoryItem
Swing Features
A set of visual components that have been available
since JDK 1.1, but part of core JDK since version 1.2:
Lightweight components compared to AWT
Pluggable look and feel API
Many more components than AWT
The Swing Package
The Swing components are all part of the javax.swing package, which was added in
JDK 1.2. Swing transformed the Java UI development by providing lightweight components
that could adapt to the look and feel of the operating system in which the application
executed. Swing provides many more types of UI components for user interaction than
found in AWT.
Lightweight Versus Heavyweight Components
Swing components are considered lightweight, meaning that they are rendered (visually
constructed) in their container window; that is, they are created within the Java environment.
The container window is usually a native (operating system) window. However, AWT
components are heavyweight, meaning that each component is rendered in its own native
window. This makes Swing components smaller and more efficient than their AWT
counterparts.
Oracle10g: Java Programming 14-7
The Swing Package (continued)
Pluggable Look and Feel
Developers can use the pluggable look and feel feature of Swing to specify the look and feel
of applications that are developed with Swing components. The default is to use the Java
look and feel (called the Metal look and feel). By using the pluggable look and feel API, you
can develop your application to use the native look and feel of whatever platform the
application happens to be running on, or you can develop your own look and feel.
Oracle10g: Java Programming 14-8
Copyright 2004, Oracle. All rights reserved.
Lightweight or Heavyweight Components?
Lightweight components
No dependence on native
peer code
Can have transparent
backgrounds
Most Swing components
are lightweight
When displayed, they can
appear nonrectangular
Must be displayed in
heavyweight container
Heavyweight components
Strong dependency on
native peer code
Each rendered in its own
opaque window
Early AWT components
were mostly
heavyweight
Include some Swing
top-level components
(JFrame, JApplet,
JDialog)
Using Lightweight and Heavyweight Components
Heavyweight components were developed in early releases of the AWT. Each heavyweight
component is tightly associated with a native peer component in the client environment.
When rendered, each heavyweight component relies on the creation of its own native opaque
window. All top-level containers are heavyweight and provide the context for lightweight
containers and components.
Lightweight components must ultimately be displayed in heavyweight top-level containers,
such as JFrame, JApplet, or JDialog. However, lightweight components are visually
more flexible because they can be transparent, and appear nonrectangular. These features
allow lightweight components to be easily adapted to a different look and feel. Lightweight
components do not have a native peer, as they are rendered directly by the Java code.
Therefore, lightweight components are more portable.
Note: As a general rule, avoid mixing heavyweight and lightweight low-level components,
such as buttons, text fields, and so on. In other words, avoid using AWT and Swing
components in the same visual container or application.
Oracle10g: Java Programming 14-9
Copyright 2004, Oracle. All rights reserved.
Planning the UI Layout
Building a UI application involves planning, even more
so when building Swing applications. Planning
requires understanding the following concepts and
their relationship:
UI containment hierarchy (a root component that
comprises nested containers and components)
Container levels and types (such as top-level or
intermediate containers)
Layout managers and their types (used by each
container)
Components that can be added into containers
Planning the UI Layout
Building a Java UI application, whether it is stand-alone or embedded in a browser such as
an applet, requires some basic understanding of:
The Java UI containment hierarchy that provides a layer of containers nested within
containers, and components within containers
The types of Java containers and their relationship in the containment hierarchy
The concept of layout managers and their types
Components that can be added into containers
Most graphical applications have a main display area, usually a main window, or the applet
display area in a Web browser. In Java, the main window, or applet display area, is called a
top-level container. A top-level container is considered the root of the containment hierarchy
for that window or area.
Note: An application can comprise many top-level windows.
A main window can be divided into regions or sections, which are represented by
intermediate containers, and ultimately into components that contain the user data or accept
user input. These components will be positioned within the top-level or intermediate
containers. Together, the top-level and intermediate containers with their components form a
containment hierarchy.
Each container makes use of a layout manager to control the size and placement of
components within a container.
Oracle10g: Java Programming 14-10
Copyright 2004, Oracle. All rights reserved.
The Containment Hierarchy
Top-level containers
Frame
Dialog
Applet
Intermediate containers
Panel
Scroll Pane
Atomic components
Label
Text items
Buttons
Frame
Panel
Atomic
components
Swing Containment Hierarchy
The slide lists the three levels of containers for Swing components that are commonly used
in applications: top-level containers, intermediate-level containers, and atomic components.
Top-level containers provide a place for other Swing components to display or paint
themselves, such as a main application window. Top-level containers cannot be placed
within another top-level container, and usually contain an intermediate container called a
content pane. Commonly used top-level containers are JFrame, JDialog, and JApplet.
Intermediate containers simplify the way you organize visual items within a top-level
container, and can contain other intermediate containers, and lower-level atomic
components. For example, a panel (sometimes called a pane) can be nested within another
panel. Common intermediate containers are: JPanel, JScrollPane, JSplitPane,
and JToolBar.
Oracle10g: Java Programming 14-11
Swing Containment Hierarchy (continued)
Atomic components are self-sufficient entities (or widgets) that are used to present
information to, or receive data from, the user. Common atomic components are JButton,
JLabel, and JTextField (as shown on the slide). Many atomic components exist for
text, combination boxes, check boxes, tables, and lists, to name a few.
Note: The slide shows the following containment hierarchy:
Frame (top-level container contains a )
Panel (intermediate container, which contains )
a Label
a TextField
a Button
Oracle10g: Java Programming 14-12
Copyright 2004, Oracle. All rights reserved.
Top-Level Containers
Swing provides JFrame, JDialog, or JApplet,
with changeable properties such as:
A content pane for holding intermediate containers
or components, by using the getContentPane() or
setContentPane() methods
A border, by using a setBorder() method
A title, by using a setTitle() method
Window decorations such as buttons for closing
and minimizing (excludes applets)
AWT provides Frame, Dialog, or Applet
These do not provide properties such as a content
pane or borders.
Top-Level Containers
Each Swing application has at least one top-level container or frame. The top-level container
can be an instance of JFrame, JDialog, or JApplet. It is easy to customize the top-
level content pane to add a border or set the layout manager. However, using the top-level
content pane methods is tricky. The methods of the top-level containers return a
Container object, not a JComponent object. This means that you must typecast the
return value of the methods in order to use them.
An easier way to achieve the same results is to create your own content pane, typically by
using a JPanel object. You then call the JFrame setContentPane() method to set
the top-level content pane to be your customized JPanel. You now have complete control
of the content pane without the restrictions of the top-level or root container.
Oracle10g: Java Programming 14-13
Top-Level Containers (continued)
The following example creates a top-level container by using a JFrame object, and an
intermediate container as a JPanel. After customizing the panel by changing its layout
manager and applying a border, the top-level containers content pane is modified to use the
panel by calling the setContentPane() method:
JFrame topLevelContainer = new JFrame();
JPanel myContentPane = new JPanel();
myContentPane.setLayout(new BorderLayout());
myContentPane.setBorder(new
LineBorder(Color.lightGray,0));
topLevelContainer.setContentPane(myContentPane); // or
topLevelContainer.getContentPane().add(myContentPane);
Oracle10g: Java Programming 14-14
Copyright 2004, Oracle. All rights reserved.
Intermediate Containers
Designed to contain components (or containers):
Can be nested within other containers
Types of intermediate containers:
Panels for grouping containers or components
Scroll Panes to add scroll bars around components
that can grow, such as a list or a text area
Split Panes to display two components in a fixed
area, which is adjustable by the user
Tabbed Panes for containing multiple components,
showing only one at a time, based on user selection
Tool Bars for grouping components, such as
buttons
Internal Frames for nested windows
Intermediate Containers
The next level of containers in Swing is designed for the sole purpose of containing other
components. These containers may hold any other Swing component including other
containers. By nesting intermediate containers within other containers, you can control the
layout of your application. This technique is described later in this lesson.
The intermediate containers are the following:
Panels: These are the most frequently used intermediate containers. They are
implemented with the JPanel class. They are generally used to group components
for logical presentation to the user. A JPanel can use any layout manager; by default
it uses the FlowLayout, and you can set its border to any border.
Scroll pane: These provide scroll bars around any large component or one that may
grow. They are implemented with JScrollPane.
Split pane: This container is used to present two components in a fixed amount of
space while letting the user adjust the space that is devoted to each item. Split Pane is
implemented with JSplitPane.
Tabbed pane: This container possesses multiple components but the user can see only
one at a time. The user can switch between the components by clicking on the visible
tabs. Tabs are implemented with JTabbedPane.
Toolbar: In addition to holding multiple components, instances of JToolBar can be
repositioned by the user.
Internal frame: Top-level containers can support internal windows or frames, which
are implemented by JInternalFrame and best used with a JDesktopPane.
Oracle10g: Java Programming 14-15
Copyright 2004, Oracle. All rights reserved.
Atomic Components
Buttons
Check boxes
Combo boxes
Text
Lists
Labels
Atomic Components
Atomic components exist solely to present or accept information. They do not serve as
containers for other components. Atomic components inherit from JComponent and thus
support standard component features such as borders and tool tips.
Oracle10g: Java Programming 14-16
Copyright 2004, Oracle. All rights reserved.
Layout Management Overview
Layout Management Overview
You can use layout managers to control the process of placing components onto a container
at run time. Each container has a layout manager by default. The layout manager ultimately
controls the layout and position of components within the container. However, each
component can provide hints about itself to assist the layout manager, such as its preferred
size and position.
Java provides many layout managers. The following five are commonly used:
java.awt.BorderLayout, which is the default for JFrame containers, arranges
the container into five areas that are called North, South, East, West, and Center.
java.awt.FlowLayout, which is the default for Jpanel, organizes items from
left to right, and then from top to bottom. The rows can be centered (default), right
justified, or left justified.
java.awt.GridLayout arranges items in a grid in rows and columns with cells of
the same size.
java.awt.GridBagLayout arranges items in a grid of rows and columns with
different cell sizes. This is the most flexible and complex of all the layout managers,
and it allows components to span multiple rows and column cells.
javax.swing.BoxLayout arranges items in a stack horizontally or vertically.
Oracle10g: Java Programming 14-17
Layout Management Overview (continued)
You can set a container layout property to null forcing the container not to use any layout
manager with the rules described. In this case, absolute positioning, specific position, and
size in pixels control the UI component. Absolute positioning is inflexible to changes in the
shape of the top-level container at run time. However, it can be useful in design stages to
provide precise control over the placement and size of each component.
Oracle10g: Java Programming 14-18
Copyright 2004, Oracle. All rights reserved.
Border Layout
Has five areas: North, South, West, East, and
Center
Has center area that expands to fill the available
space
Displays only one component in each area
Makes each area useful for holding intermediate
panels
Border Layout
Border layout provides five areas for components: north, south, east, west, and center. If the
user enlarges the window, then the center area expands to use as much of the space as
possible. The other areas expand only as much as necessary to fill the available space. For
example, if the user makes the frame wider, then the center will expand horizontally, but the
east and west areas will not; however, the south area will expand to fill the new window
size.
Each area will display only one component. To overcome this restriction and make Border a
useful layout manager, add containers to the areas instead of atomic components. Most
panels that use Border use only one or two of the areas, such as center and south. South may
be used for a toolbar or navigation, whereas center may contain a panel that will hold all the
atomic data components. This technique is useful in creating a resizable frame.
Oracle10g: Java Programming 14-19
Copyright 2004, Oracle. All rights reserved.
GridBag Layout
Is based on a grid
Allows components to span multiple rows and
columns
Allows rows and columns to differ in size
Uses the components preferred size to control
cell size
GridBag Layout
GridBag layout is the most flexible and the most complex of the layout managers. The
flexibility comes from its ability to allow components to span multiple rows and columns. In
addition to spanning multiple columns and rows, the components can provide hints or
suggestions about how the component would like to appear. For instance, a component can
specify how much space to automatically set around the component, both inside and outside
of the components cell. You can also specify minimum, maximum, and preferred size for
each component.
Components can span multiple cells in both directions, row and column. The row and
column sizes are determined by the size of the components that occupy the row or column.
Oracle10g: Java Programming 14-20
Copyright 2004, Oracle. All rights reserved.
GridBag Constraints
Cell position
Cell span
Expansion
weighting
Fill rules
Anchoring
Component
padding
External insets
GridBag Constraints
Each component in a GridBagLayout container has properties that you can set to control
the layout behavior for the component. You edit the constraints by selecting the component
and clicking constraints in the Properties Inspector window. Alternatively, you can right-
click the component and select constraints from the context menu.
Layout Constraints
Cell position: The X and Y properties specify the grid cell for the upper left corner of
the component. The values are integers and represent the cell number in a row and
column.
Cell Span: These properties specify how many columns (Width) and rows (Height) the
component occupies.
External Insets: These values specify the amount of space between the component
and the edge of its display area. You can specify a value for the top, bottom, left, and
right.
Component padding: These values specify the amount of space around a component
within a cell. The width of the component is calculated as the minimum width plus the
width property. The height is calculated as the minimum height plus the height
property.
Oracle10g: Java Programming 14-21
GridBag Constraints (continued)
Layout Constraints (continued)
Expansion weighting: This specifies how extra space is distributed vertically (X) and
horizontally (Y). The range of values is 0 through 1.0. Weight determines what share
of the extra space is allocated to each component.
Fill rules: These values specify what to do if the display area is larger than the
component.
Anchoring: This indicates where to anchor the component if the component is smaller
than the display area.
Oracle10g: Java Programming 14-22
Copyright 2004, Oracle. All rights reserved.
Using Layout Managers
Layout managers are designed to manage multiple
components simultaneously.
Using a layout manager with containers requires:
Creating a container and a layout manager object
Setting the layout property of the container
Adding items (components or other containers) into
the regions that are defined by the layout manager
Different layout managers require different
arguments to control component placement.
Using Layout Managers
These layout managers are designed to manage multiple components at once. The basic
steps to use a layout manager are shown on the slide. The examples on the slide show
creating a frame by using the javax.swing.JFrame class, to which you apply a
java.awt.BorderLayout manager.
First you create the layout manager object, then call the frames setLayout() method,
and start adding components or other containers into the regions that are provided by the
layout manager.
Create container and manager
JFrame myFrame = new JFrame();
BorderLayout layoutMgr = new BorderLayout();
Set properties
myFrame.setLayout(layoutMgr);
Add items
myFrame.add(new JButton(), BorderLayout.NORTH);
myFrame.add(new JTextField(), BorderLayout.SOUTH);
myFrame.add(new JPanel(), BorderLayout.CENTER);
Oracle10g: Java Programming 14-23
Using Layout Managers (continued)
Adding Components to Containers
When adding a component to a container, you must always consider the layout manager that
is used by the container. Each type of layout manager may require different arguments to
control the placements and/or size of component that is added. For example, when adding a
component to a container by using the BorderLayout manager, you are required to
specify the border area in which you want the component placed, such as North, South, and
so on. FlowLayout does not require a placement parameter, and just appends components
in the order that they are added to the container.
For most Swing code, such as the examples shown on the slide, you should import classes
from the following packages: javax.swing, java.awt, and java.awt.event.
Note: If you are using an IDE tool like JDeveloper, then you can set the layout property of a
container to null to force the absolute position to be used. This makes it very convenient
for you when designing and prototyping a user interface. Later, you can switch the layout
property to a suitable Java layout manager class for the application.
Oracle10g: Java Programming 14-24
Copyright 2004, Oracle. All rights reserved.
Combining Layout Managers
VerticalFlow
Grid
GridBag
null
Border
Combining Layout Managers
Different layout managers are good at different tasks. Because you can place multiple panels
in a frame and each one may have a different layout manager, you have a lot of control over
the ultimate layout.
Nesting panels and layout managers is a common practice. In the example on the slide, you
use the Border, null, VerticalFlow, GridBag, and Grid layout managers.
The top-level frame uses Border, which allows you to specify what nested panels go in the
north, south, east, and west areas. The top panel uses null, which allows you to place the
components where you want them to be displayed.
The RentalID panel uses VerticalFlow, which displays the items that are stacked vertically.
You use GridBag in the Rental panel (east) so that you can align components of differing
sizes. Lastly, you use Grid in the bottom panel, which contains only one component.
Using a combination of these layout managers offers very fine control over the layout of
your application. You can create a form that is resizable without losing its general look and
feel.
Oracle10g: Java Programming 14-25
Copyright 2004, Oracle. All rights reserved.
Using Frames or Dialogs
A Java frame is equivalent to an application window.
Use the JFrame for a main window
It has properties for icons, title, window decorations
for minimize, maximize, and close buttons.
It uses BorderLayout by default.
It provides a default content pane that occupies the
center region of the layout.
You can set the frame size with the setSize()
method, and make it visible by using the
setVisible() method.
Use JDialog for a modal window
You must dismiss a modal window before the
application that invokes it can become active.
Using Java Frame Classes
The Java frame is analogous to a top-level application window. These windows contain all
the frills and dressings that are provided by the operating system to manage the window,
such as a bar containing title string, an icon, and the minimize, maximize, and close buttons.
These windows are also resizable unless you programmatically disable this feature.
When you create a Java JFrame object, you automatically get a content pane that provides
the container for the window objects or components. As stated in a previous slide, you
typically replace the content pane with an intermediate component like a JPanel, to
simplify management of the visual contents of the container.
The JFrame uses a BorderLayout manager by default, where default content pane is
located in the center region. You can alter the frame to have a menu and/or a toolbar, to be
commonly placed in the north region, and a status bar that would typically be placed in the
south.
JDialog classes can be modal, or nonmodal. They tend to be modal in nature. It is more
common to create dialogs by using the JOptionPane class methods, such as the
showMessageDialog(), among others. Otherwise you can use the JDialog class to
create custom dialog boxes.
Note: On the next page, there is an example of a simple frame application, with a default
content pane, but no intermediate containers or components.
Oracle10g: Java Programming 14-26
Using Java Frame Classes (continued)
Creating a Simple Frame Application
This example shows how to build a Java GUI application by using the JFrame class. The
code example illustrates the points that are discussed on the slide of the previous page.
import java.awt.Color;
import javax.swing.JFrame;
public class MyFrame extends JFrame
{
public MyFrame()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setBackground(Color.blue);
setTitle("Default Frame Title");
setLocation(50, 50);
setSize(600, 400);
}
public static void main(String[] args)
{
JFrame f = new MyFrame();
f.setResizable(true);
f.setVisible(true);
}
}
Note
By default the JFrame default operation on a close event is to hide the window. The
call to setDefaultCloseOperation(EXIT_ON_CLOSE) changes the default
operation that is performed by the JVM when the window is closed. The
EXIT_ON_CLOSE constant is defined in javax.swing.WindowConstants,
which is an interface implemented by JFrame.
The getContentPane() method is used to access the frames default container and
change the background color to blue.
The setLocation() determines the top left x and y coordinates (in pixels) of the
window relative to the top left corner of the screen.
The setSize() method sets the width and height of the window (in pixels).
The setLocation() and setSize() can be done in one step by calling
setBounds(x, y, width, height).
The example shows how you can set properties of the frame in the constructor, or by
using a reference to the frame (as shown in the main() method).
Oracle10g: Java Programming 14-27
Copyright 2004, Oracle. All rights reserved.
Using JPanel Containers
JPanel is a general purpose container.
Can use any layout manager
(uses Flowlayout by default)
Can use any border
Can have added components
or other panels/containers
by using the add() method
JPanel myPanel = new JPanel(new BorderLayout());
JTextArea jTextArea1 = new JTextArea();
myPanel.setBorder(BorderFactory.createRaisedBevelBorder());
myPanel.add(jTextArea1, BorderLayout.SOUTH);
Using JPanel Containers
JPanel is a general purpose container that is designed to hold other components. You can
use JPanel containers to group components within an area of an application. You may add
a border to the panel to help visually separate the components from other components in the
application.
Setting the Layout Manager
The default layout manager for JPanel is FlowLayout, which places all the components
within the container in a row. You can make the panel use another layout manager by calling
the setLayout() method or by specifying the layout manager when you create the panel.
For example:
JPanel myPanel = new JPanel();
myPanel.setLayout(new BorderLayout());
or
JPanel myPanel = new JPanel(new BorderLayout());
Oracle10g: Java Programming 14-28
Using JPanel Containers (continued)
Adding Components
You can add components to the panel by using the add() method. The arguments that are
provided to the add() method depend on which layout manager is used by the panel. For
example, FlowLayout, GridLayout, and GridBagLayout typically accept one
argument. If the layout manager is BorderLayout, then additional arguments are used to
specify the position of the contained components.
For example:
myPanel.add(button); // if FlowLayout
myPanel.add(button, BorderLayout.NORTH); // if BorderLayout
myFrame.getContentPane().add(myPanel); // add to a frame
Oracle10g: Java Programming 14-29
Copyright 2004, Oracle. All rights reserved.
Adding Borders to Components
Borders are Swing objects.
Defined in javax.swing.borders
Use setBorder() to assign a
border to a component.
Create borders with the class called
javax.swing.BorderFactory.
Create borders separately to use with many
components.
jPanel1.setBorder(BorderFactory.createBevelBorder(
BevelBorder.LOWERED,Color.lightGray,Color.darkGray));
Border etchedBorder =
BorderFactory.createEtchedBorder();//pre-create border
jPanel2.setBorder(etchedBorder); // use border`
Adding Borders to Components
Any JComponent object or subclass may have one or more borders. To place a border
around a component, use its setBorder() method.
Because borders are objects, they must be created. You create a border by using the
BorderFactory class. You can include the border object creation in the call to
setBorder(), or you can create the border object with a separate line of code. If you use
the same border style for multiple components, then it would be easier and more consistent
to create one border object for each style needed. The following code illustrates the
technique for creating reusable Border objects:
import javax.swing.BorderFactory;
import javax.swing.border.*;
Border etchedBorder = BorderFactory.createEtchedBorder();
Border raisedBorder = BorderFactory.createRaisedBevelBorder();
jPanel1.setBorder(raisedBorder);
jPanel2.setBorder(etchedBorder);
Oracle10g: Java Programming 14-30
Copyright 2004, Oracle. All rights reserved.
Using Internal Frames
An internal frame is the equivalent of a document
window that is contained within an application window
for multiple-document interface (MDI) window
applications.
Use JInternalFrame for an internal window:
Similar to JFrame, it can contain intermediate
containers and components and use a layout
manager.
By default it is not closable, iconifiable,
maximizable, or visible.
Use a JDesktopPane as the content pane in which
the internal frames are added:
Controls the size and placement of internal frames
Uses a null layout manager by default
Using Java Internal Frames
The Swing API also provides an internal frame, which is implemented by the
JInternalFrame class. An internal frame creates a window within another window that
you can use to build an application that conforms to the popular multiple document interface
(MDI) model of the Windows platform.
When using a JInternalFrame, the JDesktopPane class is provided as a container to
manage the size and placement of the internal frames within the containing window.
Therefore, you would normally create a JDesktopPane object to replace the existing
frames default content pane. The internal frames are then added to the desktop pane.
Like a JFrame, the JInternalFrame has a window title bar, with a title, icon, and
window decorations such as maximize, iconify, and close buttons, which by default are
disabled. The internal frames can be dragged over each other, and an internal frame provides
methods to control whether it is on top and selected, and so on. For example:
setResizable(boolean), setIconifiable(boolean)
setMaximizable(boolean), setVisible(boolean)
toFront(), toBack()
The desktop pane provides methods to obtain an array of internal frame objects that have
been added to its container; for example:
getAllFrames() returns an array of JInternalFrame objects.
getSelecedFrame() returns the currently selected JInternalFrame.
Note: Most getXXX() methods have a corresponding setXXX() method.
Oracle10g: Java Programming 14-31
Using Java Internal Frames (continued)
Creating a Multiple Document Interface (MDI) Application
This code example uses a JFrame as the main MDI application window, whose default
content pane is replaced with a JDesktopPane object. Two JInternalFrame objects
are then added to the main application window desktop pane.
1 import java.awt.Color;
2 import javax.swing.JFrame;
3 import javax.swing.JInternalFrame;
4 import javax.swing.JDesktopPane;
5
6 public class MdiFrame extends JFrame {
7 public MdiFrame() {
8 setDefaultCloseOperation(EXIT_ON_CLOSE);
9 setTitle("MDI Frame Example");
10 setBounds(50, 50, 600, 400);
11 }
12 public static void main(String[] args) {
13 JFrame f = new MdiFrame();
14 JDesktopPane desktop = new JDesktopPane();
15 JInternalFrame iFrame1 =
16 new MyInternalFrame("Internal 1", Color.red);
17 JInternalFrame iFrame2 =
18 new MyInternalFrame("Internal 2", Color.green);
19 f.setResizable(true);
20 f.setVisible(true);
21 f.setContentPane(desktop);
22 iFrame1.setBounds(10, 20, 350, 200);
23 iFrame2.setBounds(60, 70, 350, 200);
24 desktop.add(iFrame1);
25 desktop.add(iFrame2);
26 iFrame2.toFront(); //only after frames are added
27 }
28 }
29 class MyInternalFrame extends JInternalFrame {
30 public MyInternalFrame(String name, Color c) {
31 super(name); setBackground(c);
32 setResizable(true); setMaximizable(true);
33 setIconifiable(true); setClosable(true);
34 setVisible(true);
35 }
36 }
Note
The text in boldface highlights some of the important parts of the code, such as:
Creation of the desktop pane (line 14), and internal frame objects (from line 16 through
18)
Replacing MdiFrame default content pane with the desktop pane (line 21)
Adding the internal frames into the desktop frame (lines 24 and 25)
Making the second internal frame the front/top internal frame (line 26)
Making the internal frames visible (line 34)
Oracle10g: Java Programming 14-32
Copyright 2004, Oracle. All rights reserved.
Swing Text Controls
Swing Text Controls
Swing provides five text components (along with supporting classes and interfaces) that
meet even the most complex text requirements. All of Swings text components inherit from
JTextComponent.
Text Fields
Also known as text controls, text fields can display and edit only one line of text and are
action-based, like buttons. Use them to get a small amount of textual information from the
user and take some action after all the text has been entered. The text fields are
JTextField and JPasswordField.
Plain Text Areas
JTextArea can display and edit multiple lines of text. This field is useful when you want
the user to enter text of any length or to display large amounts of unformatted text.
JTextArea can display text in any font; however, all of the text displayed must be in the
same font.
Styled Text Areas
Styled text components can display and edit text using more than one font. These
components can display text that is stored in different formats such as HTML and Rich Text
Format (RTF). They also support images and some support buttons and other controls. The
styled text components are JEditorPane and JTextPane.
Oracle10g: Java Programming 14-33
Copyright 2004, Oracle. All rights reserved.
Adding Components
with Oracle JDeveloper 10g
Use the wizard to create a JFrame.
Select a layout manager.
Add components from the Component Palette.
Fine-tune component properties.
Adding Components with JDeveloper
Adding components to an application is a straightforward process with Oracle JDeveloper.
You can use the Frame Wizard to create an empty frame and then add the components that
you want. The components can be Swing containers or Swing atomic components, such as
text fields, buttons, check boxes, and so on. After you add the components, you can fine-
tune the components by using the Properties Inspector or by adding or changing the code in
the Code Editor window.
Oracle10g: Java Programming 14-34
Copyright 2004, Oracle. All rights reserved.
Creating a Frame
Frame
Creating a Frame
To create a new JFrame, select File > New from the JDeveloper menu. Expand the Client
Tier, then select the SWING/AWT node. Look for the Frame item in the Items list. In the
Frame Builder Wizard, change the name of the class and the frame title to something
meaningful. Select javax.swing.JFrame as the base class. You can ask the wizard to
create a menu bar, status bar, toolbar, and about box. These are all optional attributes.
You can use the wizard to specify the preferred superclass for the new frame. JDeveloper
will generate a class with the required import statements and the code that is necessary to
create a usable frame. Now you can use the JDeveloper UI Editor to construct the
application UI structure visually.
Oracle10g: Java Programming 14-35
Copyright 2004, Oracle. All rights reserved.
Adding Components
Use the Component Palette to add
Swing items to the Frame
Adding Components
The JFrame that is created by the Frame Builder Wizard includes the frame and an
intermediate JPanel container. The wizard does not set the layout manager for the
generated JPanel. It uses the default layout manager for its type of container
(FlowLayout).
Because it is a default layout manager, JDeveloper cannot provide the ability to alter the
properties of the layout manager. It is best to change the layout manager so that you can
manipulate the layout properties.
After setting the layout manager, you can then add components by selecting them from the
Swing component toolbar and dragging an area onto the JPanel in the Design window.
Alternatively, you can click the component and then click JPanel in the Component pane of
the structure window. If you choose the latter, then JDeveloper uses default sizes for
components. In either case, the layout manager affects the final location of the component.
Oracle10g: Java Programming 14-36
Adding Components (continued)
To invoke the UI Editor, in the navigator select a class, right-click, and choose UI Editor.
In general, add components to the structure window instead of directly to the panel. This
approach is best if you want to avoid adding a component to the wrong panel by accident.
For instance, adding components to a JTabbedPane inside a panel can be done in an
easier manner by using the structure pane.
When visually adding a component into a frame/panel with JDeveloper, it generates code to:
Declare and instantiate the selected component object
Set minimal properties for the default state
Add the component into the chosen container
Oracle10g: Java Programming 14-37
Copyright 2004, Oracle. All rights reserved.
Setting Pluggable Look and Feel
Swing applications provide support for a different look
and feel to adapt to the visual environment of the
operating system. The look and feel:
Is application-specific:
Can be initialized when the application starts
Can change dynamically
Affects lightweight Swing components
Supports Win, Mac, Java (Metal) and Motif
Uses javax.swing.UIManager class
Provides the setLookAndFeel() method, which
accepts a look and feel class name string.
Pluggable Look and Feel (plaf)
Java provides a set of classes in the javax.swing.plaf package and subpackages that
assist to render components in a platform-specific manner. The default Java look and feel is
known by its code name Metal, which is the name of the project that was assigned to a
team at Sun Microsystems, Inc., to create a unique and distinctive look and feel for Swing
1.0 (JFC 1.1).
Setting UI Look and Feel
Use the javax.swing.UIManager class to initialize, or dynamically change the look
and feel of your application. For example, in the main() method of your frame application,
you can add the following code:
try { UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) { }
Oracle10g: Java Programming 14-38
Setting UI Look and Feel (continued)
The value that is returned by getSystemLookAndFeelClassName() is a string
representing a fully qualified class name that implements the look and feel of the current
platform. The class name string is provided as the parameter to
UIManager.setLookAndFeel(). Some possible values for the class names of
different platforms are:
javax.swing.plaf.metal.MetalLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
Note: If you want to change the look and feel dynamically, then you can call the
SwingUtilities.updateComponentTreeUI(getContent Pane())method.
This method will make the existing components reflect the new look and feel.
Oracle10g: Java Programming 14-39
Copyright 2004, Oracle. All rights reserved.
Summary
In this lesson, you should have learned the following:
Frames are top-level containers.
Panels are intermediate containers that can be
nested.
Each container can have its own layout manager.
Layout managers control component placement.
You can combine layout managers within an
application.
You can control the applications look and feel.
Oracle10g: Java Programming 14-40
Copyright 2004, Oracle. All rights reserved.
Practice 14: Overview
This practice covers:
Creating a class based on JFrame for the main
window of the OrderEntry application.
Add a default menu and status bar.
Add a JDesktopPane and set it as the content pane.
Creating a class based on JInternalFrame to
manage order creation and data entry.
Create the container layout hierarchical structure
for the order-entry frame components.
Add some of the components to this frame.
Setting layout managers for each container
Practice 14: Overview
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you would like to move on to this practice, then change to the les13 directory, load up the
OrderEntryWorkspaceLes13 workspace, and continue with this practice.
Viewing the model: To view the course application model up to this practice, load the
OrderEntryWorkspaceLes13 workspace. In the Applications Navigator node,
expand the OrderEntryWorkspaceLes13 OrderEntryProjectLes13 -
Application Sources oe, and double-click the UML Class Diagram1 entry.
This diagram displays all the classes created to this point in the course.
Oracle10g: Java Programming 14-41
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout
Goal
The goal of this practice is to use JDeveloper to create the main application frame as an MDI
window, and the internal order frames that will be contained within the main window. These
frames will serve as a way to explore Swing classes and ways of building GUI applications.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you would like to move on to this practice, then change to the les13 directory, load up the
OrderEntryWorkspaceLes13 workspace, and continue with this practice.
Your Assignment
Create the main window as an extension of the JFrame class. This class will contain a
JDesktopPane object to manage the internal frame layout. You will also create a class
based on the JInternalFrame class in which the customer and order details will be
entered via atomic Swing components. The components layout will be managed through the
use of panels and associated layout managers. You use the JDeveloper Frame Wizard to
create a basic menu for the application, and a status bar in the main application window.
Create the Main Application Window
1. In OrderEntryProject, create a new subclass of the JFrame class.
a. Right-click the project name in the navigator, and select New from the context
menu. Select the Frame item from Client tier > Swing/AWT category, and click
the OK button.
b. In the Create Frame dialog box, enter the class name OrderEntryMDIFrame,
and extend javax.swing.JFrame. In the Optional Attributes section, set the
Title field to: Order Entry Application, and select only the Menu Bar
and Status Bar check boxes. Then click the OK button.
c. Examine the code for the new class that is generated by JDeveloper by selecting
the Source tab. You will notice that JDeveloper creates a jbInit() method
that is called from the default no-arg constructor. The jbInit() method should
contain all code to initialize the user interface structure. You should modify the
code if required, to match with the one displayed.
d. In the Editor window, select the Design tab, and examine the visual container
hierarchy and presentation of the frame. The container hierarchy is visible in the
JDeveloper Structure pane (located under the Navigator pane).
e. Return to the Code Editor for the class by selecting the Source tab
and make the following changes:
Replace the JPanel panelCenter variable declaration, with:
JDesktopPane desktopPane = new JDesktopPane();
Note: Remember to import javax.swing.JDesktopPane.
In the jbInit() method, replace panelCenter references with
desktopPane.
f. Compile and save the OrderEntryMDIFrame class.
g. Modify OrderEntry.java by renaming the main() method to test1().
Create a new public static void main(String[] args) method,
which creates an instance of the OrderEntryMDIFrame and makes it visible.
Oracle10g: Java Programming 14-42
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
h. Compile, save, and run the OrderEntry application.
Create the JInternalFrame Class for Order Data
This frame will contain the bulk of the UI code for data entry and user interaction for an
order, and assigning a customer and adding items to the order.
2. Right-click the OrderEntryProject and select New from the context menu.
a. Navigate to the Client Tier > Swing/AWT node and select the Frame item. In the
New FrameWizard, enter the class name OrderEntryFrame, and extend the
javax.swing.JInternalFrame. Set the title to the text Order.Then
click the OK button.
Note: The JInternalFrame class can be selected by clicking the Browse
button.
b. The OrderEntryFrame that is generated does not have the desired layout
manager or content pane. To set the layout manager, and add a panel to the
content pane, open OrderEntryFrame with the UI Editor.
Note: When the UI Editor is activated (UI Editor can be invoked by clicking the
Design tab), the Property Inspector window is also displayed, showing the
properties of the object that is selected in the UI Editor.
c. Select the internal frame object by clicking the frame title bar in the UI Editor or
the node labeled this in the structure window. (You may have to expand the UI
node to view objects in the containment hierarchy.) In the Inspector pane, locate
the layout property and select BorderLayout from the pop-up list options.
d. Which lines of code has JDeveloper added or changed in your class? When
creating a Swing UI by using the JDeveloper UI Editor, it is wise to view
changes that are made to the source code as an aid to learning what you would
need to write yourself if you are building the UI manually. Remove the
private declaration from the BorderLayout.
e. JDeveloper provides a Component Palette in the toolbar (ask the instructor, if
needed). In the palette, choose Swing Containers from the pop-up list.
Click the JPanel icon, and then click the center of the frame in the UI Editor (or
click the node labeled this in the UI Structure pane) to add a new panel to the
center region of the border layout.
If the JPanel icon is not visible, they have to expand the Component Palette
window by increasing the height.
Note: Confirm that the panel is in the center by selecting the JPanel object
added and checking that its constraints property (in the Inspector) has the
value Center. If not, then set it to Center.
3. The panel was added to the frames content pane, and will be used to lay out the rest of
the application UI objects. The panel will be divided into two areas: a top (for order
and customer data), and a bottom (for order item data). Divide the panel into two by
using a GridLayout for the layout, with one column and two rows:
a. Select jPanel1, and set its layout manager property to GridLayout.
b. Expand jPanel1 in the UI Structure pane, select the gridLayout1 object,
set the columns property to 1 and press the Enter key, set the rows property
to 2, and then press Enter.
Oracle10g: Java Programming 14-43
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Using the following picture as a visual guide to the desired results for the layout of
these containers, add another panel to the top, and a scroll pane to the bottom
of the content panel.
c. Add a second panel to the top half (or first row) of the first panel, by clicking the
JPanel icon in the Swing Components palette, and then clicking the jPanel1
object in the UI Editor, or in the Structure pane.
Note: Confirm that the new panel is called jPanel2, and more importantly,
that it is nested inside jPanel1 in the hierarchy.
d. Add a raised-bevel border to the new panel, called jPanel2, by selecting its
border property in the Inspector, and select Swing Border from the pop-up
list. In the Border dialog box, choose BevelBorder and select the RAISED
option button, then click the OK button.
Note: jPanel2 should visually occupy the top half of the jPanel1.
e. Add a scroll pane object to the bottom half (second row) of the jPanel1, by
clicking the JScrollPane icon in the Swing Components palette, and click the
bottom area of the jPanel1. (Alternatively, click the jPanel1 object in the
Structure pane to add the JScrollPane.)
f. Use the Structure pane to check whether you have the following containment
hierarchy:
g. Save your OrderEntryFrame class. Then compile the class.
Oracle10g: Java Programming 14-44
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Modify OrderEntryMDIFrame Class to Contain an Internal OrderEntryFrame
4. To view the visual results of your internal frame at run time modify the constructor in
OrderEntryMDIFrame to create an instance of OrderEntryFrame, and make it
visible.
a. Edit OrderEntryMDIFrame.java, and at the end of the constructor add the
following lines of code:
OrderEntryFrame iFrame = new OrderEntryFrame();
iFrame.setVisible(true);
desktopPane.add(iFrame);
Note: The bounds (size and location) of the internal frame must now
be set, otherwise it will not become visible. In addition, you must also alter the
dimensions of OrderEntryMDIFrame to be larger than the initial size of the
internal frame OrderEntryFrame.
b. In the jbInit() method of the OrderEntryMDIFrame class, locate the
following statement:
this.setSize(new Dimension(400,300));
Then modify the dimension arguments to be 700,500.
c. In the OrderEntryFrame, add the following line into the jbInit()
method:
this.setBounds(0, 0, 400, 300);
d. Compile and save OrderEntryMDIFrame and OrderEntryFrame.
e. Run the OrderEntry class to view the results.
5. You will notice that the internal frame cannot be maximized, iconified (minimized),
or closed. Make changes to OrderEntryFrame to enable these features.
a. In the jbInit() method, add the following lines of code to enable the internal
frame to maximized, iconified, and closed.
this.setMaximizable(true);
this.setIconifiable(true);
this.setClosable(true);
b. Compile and save the changes to OrderEntryFrame.java.
c. Run the OrderEntry application, and observe the changes.
Add UI Components to OrderEntryFrame
6. Before adding UI components to jPanel2 in OrderEntryFrame, set its layout to
null.
Note: You could also use the JDeveloper XYLayout.
In either case, JDeveloper will use absolute positioning and sizing for components that
are added to the panel. It is easier to use absolute positioning when building the initial
UI layout. You will change the layout again in a subsequent lesson.
Use the following image as a guide to the desired results:
Oracle10g: Java Programming 14-45
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
a. In the Design mode, select the Swing option in the Component Palette pop-up
list. Then add a Jlabel to jPanel2 and set its text property to Order Id.
Resize the label to see the label value, if needed. What lines of code have been
added to your class?
Hint: You should find at least five lines of code (some of them in the
jbInit() method). Try to identify the three that make the object visible in the
panel.
Note: The setBounds value can be modified if required in the source to make
the label clearly visible.
b. From Swing icons, select and add a JTextField component into jPanel2, to
the right of the label, then delete the default value in the text property of the
text field (remember to press the Enter key after deleting the text value).
Note: setBounds values can be changed if required.
c. Compile and save OrderEntryFrame, and run OrderEntry to view the
results.