Oracle E10: Java Programming: Instructor R Guide - Volume 1
Oracle E10: Java Programming: Instructor R Guide - Volume 1
Oracle
D17249GC11
Edition 1.1
August 2004
D39815
Authors Copyright © 2004, Orac
cle. All rights reserved.
Poornima G The information in this document is subject to change without notice. If you find any
problems in the documentation,
ntation please report them in writing to Education Products
Products,
Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.
Oracle Corporation does s not warrant that this document is error-free.
All references to Oracle and Oracle products are trademarks or registered trademarks
of Oracle Corporation.
Preface
I Introduction
Objectives I-2
Course Overview I-3
1 Introducing
t oduc g the
t e Java
Ja a a
anddOOracle
ac e Platforms
at o s
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-211 21
Integrated Development Environment 1-22
Exploring the JDeveloper Environment 1-23
Oracle10g Products 1-24
Summary 1-25
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
iv
Guided Practice: Declaring Variables 4-17
What Are Operators? 4-19
Categorizing
g g Operators
p 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
4-28
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
4 35
v
Adding a New J2SE 6-12
Looking at the Directory Structure 6-13
Exploring
p g the Skeleton Java Application
pp 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 6-22
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
vi
Setting the CLASSPATH with Packages 7-29
Access Modifiers 7-30
Summary y 7-32
Practice 7: Overview 7-33
vii
About System.out.println 9-23
About OutputStream and PrintStream 9-24
j
What Is Object Serialization? 9-25
Serialization Streams, Interfaces, and Modifiers 9-28
Summary 9-29
Practice 9: Overview 9-30
viii
Working with Variable-Length Structures 11-15
Modifying a Vector 11-16
Accessingg 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
ix
Cleaning Up with a finally Block 13-15
Catching and Handling Exceptions: Guided Practice 13-16
Allowing
g an Exception
p to Pass to the Calling
g 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
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
15-26
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
15 35
Summary 15-36
Practice 15-2: Overview 15-37
xi
Mapping Database Types to Java Types 16-26
Handling an Unknown SQL Statement 16-28
Handlingg Exceptions
p 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 16-38
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
g and Deploying
p y g 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 17-19
19
Practice 17: Overview 17-20
Appendix A: Practice Solutions
Appendix B: Java Language Quick-Reference Guide
Appendix C: Order Entry Solution
xii
Preface
Profile
Prerequisites
• Required: Previous experience with another 3GL programming language, preferably a structured
l
language suchh as Pascal
P l or C
• Suggested: Familiarity with basic HTML
Preface - 3
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 user’s guides
• Read-me files
• International Oracle User’s Group (IOUG) articles
• Oracle Magazine
Preface - 4
Typographic Conventions
Bold italic Glossary terms (if there is a The algorithm inserts the new key.
glossary)
Preface - 5
Typographic Conventions (continued)
Quotation Lesson and chapter This subject is covered in Unit II, Lesson 3, “Working
marks titles in cross with Objects.”
references, interface
elements with long Select the “Include a reusable module component” and
names that have click Finish.
only initial caps
Use the “WHERE clause of query” property.
Preface - 6
Typographic Conventions (continued)
This simplified
p ppath translates to the following:
g
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) = M
Menu (H) = Hyperlink
H li k
(T) = Tab (B) = Button
Preface - 7
Introduction
Instructor Note
The database used for this course is 9.2. It is the latest edition supported by the Development
Tools.
Lesson Aim
This lesson introduces the background and usefulness of the Java language. It discusses Java’s
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.
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 Developer’s 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-3
Key Benefits of Java
• Object-oriented
• Interpreted and platform-independent
• Dynamic and distributed
• Multithreaded
• Robust and secure
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.
Compile JVM
(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 JVM is 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.
• Servlets • Enterprise
• JavaServer JavaBeans (EJB)
Pages (JSPs) • CORBA
Operating system
JVM
Application
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
Class loader
Bytecode verifier
Interface-specific access
• 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.
Web Application
Client server server Data
Business
Presentation
logic
Oracle
database
Oracle
Application Server
Development Debug
UML Exchange
ADF Database
SCM Deployment
Component Palette
• 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
getName
getAge()
setBirthdate name getAge Message
address
birthdate
Client or
getAddress setAddress sender
Person
• A subclass object
“is-a-kind-of”
superclass
object.
Account Pen
• A subclass must
have all the
attributes and
behaviors of the
superclass.
Load passengers
Product
Company Individual id: int
name: String
contact: String description: String
discount: int licNumber: String
retailPrice: double
getContact() setLicNumber()
getPrice()
setContact() getLicNumber()
:
: :
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.
J2SE
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
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.
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
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).
• Variables:
– customerName, customerCreditLimit
• Constants:
– MIN_WIDTH, MAX_NUMBER_OF_ITEMS
• Uppercase and lowercase characters
• Numerics and special characters
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.
Access modifier
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-15
Defining Java Methods
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.
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-17
Declaring Variables
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.
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;
}
About JavaBeans
A JavaBean is a reusable platform-independent software component that can be manipulated
visually in a builder tool such as JDeveloper. The JavaBean’s 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 extend—unlike, 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).
Instructor Note
Students will probably find that even if JavaBeans are new to them, many of the concepts and
rules that are associated with JavaBeans are familiar.
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
JDeveloper’s 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.
Getter Setter
private
methods T var; methods
(public) T[] arr; (public void)
Setting CLASSPATH
C:\>set CLASSPATH=D:labs\les03\classes\oe
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.
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.
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.
8. Close Notepad, but do not exit the DOS window, because you continue to work with this
environment for some time.
Lesson Aim
This lesson introduces Java’s 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.
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.
Floating True
Integer Character
Point False
byte
short float
char boolean
int double
long
Title: “Blue
Moon”
Type
Identifier
int myAge; Initial value
boolean isAMovie;
float maxItemCost = 17.98F;
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.
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.
class Rental {
private int instVar; // instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3; // local variable
}
}
0 1 42 -23795 (decimal)
02 077 0123 (octal)
Integer literals
0x0 0x2a 0X1FF (hex)
365L 077L 0x1000L (long)
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).
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.
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.
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
byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2; // ERROR: result is an int
// b3 is byte
byte
short
int
char long
• Java does not automatically “downcast.”
short
byte int long
char
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.
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
int var1 = 0;
var1 = 2 + 3 * 4; // var1 now equals 14
int var1 = 0;
var1 = 12 - 6 + 3; // var1 now equals 9
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.
Lesson Aim
This lesson introduces Java’s 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.
Sequential Iteration
Selection Transfer
if ( boolean_expr )
General: statement1;
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
Examples: else
System.out.println("Odd");
… if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
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.
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 if…else…if Construct
The “dangling else” problem can be solved with a prudent use of braces, but a cleaner
approach is to use the if…else… 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.
int x = 3, y = 5;
1
if (x >= 0)
if (y < x)
System.out.println("y is less than x");
else
System.out.println("x is negative");
int x = 7; 2
if (x = 0)
System.out.println("x is zero");
switch ( integer_expr ) {
case constant_expr1:
statement1;
• The switch
break;
statement is useful
case constant_expr2:
when selecting an
statement2;
action from several
break;
alternative integer
[default: values.
statement3;] • Integer_expr must
} be byte, int, char,
or short.
switch (choice) {
• case labels
case 37:
must be
System.out.println("Coffee?");
constants.
break;
• Use break to
jump out of a
case 45:
switch.
System.out.println("Tea?");
• It is break;
recommended
to always default:
provide a System.out.println("???");
default.
break;
}
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,
do…while, 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 do…while 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-13
Using the while Loop
while ( boolean_expr )
statement;
Example: int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
do
statement;
while ( termination );
Example: int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
Example:
for (i = 0; i < 10; i++)
System.out.println(i);
Instructor Note
The for loop integrates the four parts (initialization, iteration, body, and termination) in the
statement.
Oracle10g: Java Programming 5-16
More About the for Loop
int x = 10; 1
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); 2
x--;
int sum = 0;
for (; i < 10; sum += i++);
3
System.out.println("Sum is " + sum);
…
while (age <= 65) {
balance = (balance+payment) * (1 + interest);
if (balance >= 250000)
break;
age++;
}
…
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.
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).
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.
Component Palette
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.
• Contain related
files
• Manage project and
environment
Project
settings
• Manage compiler
and debug options
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-7
Creating JDeveloper Items
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.
In the General
category, select
Application
Workspace to invoke
the Property pane.
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).
Instructor Note
You may want to encourage students to explore these features. JVM is required to use the
Code Coach and Profiler features. To use a custom J2SE version (other than the one
provided by JDeveloper), they can follow the installation guide provided by JDeveloper on
how to install the OJVM on the custom J2SE.
Oracle10g: Java Programming 6-16
Customizing JDeveloper
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.
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.
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 Patterns–MVC, 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
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.
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.
Methods Objects
Attributes Object
references
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.
Movie
• An object is an
instance of a public void displayDetails()
class.
• Objects have public void setRating()
their own
memory. private String title;
• Class definitions
private String rating;
must be loaded
to create
instances.
mov1 mov2
title: “Gone with…” title: “Last Action…”
rating: “PG” rating: “PG-13”
j 3 mov1
title: null
rating: null
mov2
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
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.
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
title
rating
min title
Price rating
title
rating
Movie class variable Movie objects
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.
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.
oe
OrderEntry OrderItem
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.
CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06
acmevideo acmetools
public public
protected
private
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.
Same Class Y Y Y Y
Subclass in Y Y N N
Different Package
Non-Subclass in Y N N N
Different Package
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.
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.
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.
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.
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.
title : null
void anyMethod() { rating: “PG”
Movie mov1 = new Movie(); mov1
Movie mov2 = new Movie(); title: null
mov1.setRating("PG"); … mov2 rating: null
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-7
Defining and Overloading 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
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.
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.
Enclosing class
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.
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.
Instructor Note
This lesson covers a number of classes: String, Stringbuffer, and the various wrapper
classes with their own set of methods. It would be beyond the scope of the course notes to list
the complete syntax of every method that is mentioned, so you may find it useful to show the
J2SE online documentation for the various classes as a way of describing selected methods
and classes in more detail. The String, StringBuffer, and wrapper classes are in the
java.lang package, and the DateFormat, DecimalFormat, and MessageFormat
classes are in the java.text package.
• 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.
• Use a constructor:
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 JDeveloper’s 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.
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";
• Trim whitespace:
String trim(); String nospaces =
str.trim();
• Use String.valueOf():
String seven = String.valueOf(7);
String onePoint0 = String.valueOf(1.0f);
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.
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 date–time 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() ));
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);
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);
b.
Instructor Note
Students must be able to answer these questions on paper (or interactively, as a class
discussion) with reference to the online J2SE documentation.
Answers
1a. Equal B
s == "Friday" tests whether the string s and the string "Friday" point to exactly the
same location in memory. This is not true, so "Equal A" is not printed.
s.equals("Friday") tests whether the string s and the string "Friday" contain
exactly the same characters, which is true, so "Equal B" is printed.
1b. 4
String.valueOf(num) converts the integer 1234567 to the string "1234567".
"1234567".charAt(3) returns the character at index 3. Indexes always start from zero,
so the character at index 0 is 1, and the character at index 3 is 4.
b.
// 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"));
Instructor Note
Answers
2a. ayTu
The result of s1.concat(s2) is "MondayTuesday".
"MondayTuesday".substring(4,8) returns the substring beginning at 4 and ending
at 7 (remember that substring(beginIndex, endIndex) returns a substring
beginning at beginIndex and ending at endIndex - 1).
Counting from the beginning of the string, starting with index 0, gives:
MondayTuesday
01234567
Characters 4, 5, 6, and 7 are "a", "y", "T", and "u".
2b. 5
3
You want to find out the index of the first character of "day" in " Monday ". The
first two characters of " Monday " are spaces. Counting from the left, starting with
index 0, gives index 5 for "d".
The result of " Monday ".trim() is "Monday". Again, counting from the left,
starting with index 0, gives index 3 for "d".
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
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.
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.
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.
import java.text.DecimalFormat;
b. Add the following toMoney() method code to the class, to format a double:
import java.util.Date;
import java.text.SimpleDateFormat;
b. Save and compile the Order class, and then run the OrderEntry class to view
the changes to the displayed order details.
a. In the toString() method, replace the return statement with the following:
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 day’s date for the values of the day, month, and year
arguments supplied to the Util.getDate() method.
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.
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.
• Inheritance
• Constructors referenced by subclass
• Polymorphism
• Inheritance as an OO fundamental
Superclass
InventoryItem
Subclasses
Movie Game Vcr
Movie
2
3
InventoryItem
calcDeposit(){…}
Vcr Movie
calcDeposit(){…} calcDeposit(){…}
ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();
…
}
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-26
Ensuring Genuine Inheritance
Customer
int nextCustomerId
int id
String name
String address
Person
String phoneclass
toString()
getNamen()
setName()
getAddress()
setAddress()
…
Company Individual
String contact String licNumber
int discount Person class
Person class toString()
toString()
setContact() setLicNumber()
getContact() getLicNumber()
setDiscount()
getDiscount()
order.setCustomer(DataMan.customer3);
Oracle10g: Java Programming 10-33
int se Ctrl + F to display a search
d alog box
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
Optional Extra Credit
Refine the Util and Customer Classes and Test Results
t 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 herefore 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>
f 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 herefore the solution is to use
inherited code called from the Customer
class that dynamically determines the
run time object type name
ou can determine the run time object
type name of any ava object by calling
its getClass() method which is inherited
from the java.lang.Object class he 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 or example if you add this
line to the ustomer class
String myClassName = this.getClass().getName();
he variable myClassName will contain a fully
qualified class name that includes the
package name he value that is stored in
myClassName will be oe.Customer
o extract only the class name you must
strip off the package
Oracle10g: name and
Java Programming 10-34 the dot
that precedes the class name his can be
done by using a lastIndexOf() method in the
Practice 10: Reusing Code with Inheritance and Polymorphism (continued)
8 pen Customer.java in the ode ditor
a refix 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 ave and compile Customer.java
c un the OrderEntry.java application to
view the results
d n the above code what does this
represent nd why do you pass a
parameter value this to the
Util.getClassName() method
xplain why the compiler accepts
the syntax that is used
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.
[0] 1
[0] Action
[1] 2
[1] Comedy
[2] 4
[2] Drama
[3] 8
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.
powers null
Declaring an Array
There are two ways to declare an array:
Syntax E xam ple
type[] arrayname; int[] powers;
type arrayname[]; int powers[];
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.
Instructor Note
Although an array is an object, there is no array class. Instead, for every primitive type or
class, Java automatically provides an array class.
arrVar
1. Declare the array: null
ClassName[] arrVar;
arrVar
… or … null
ClassName arrVar[];
null
null
2. Create the array object: arrVar
Action
System.out.println
("Length is " + categories[2].length());
• ArrayIndexOutOfBoundsException occurs
when an array index is invalid:
String[] list = new String[4];
//The following throws ArrayIndexOutOfBoundsException
System.out.println(list[4]);
[2] 0 0
[3] 0 0
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];
}
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.
Instructor Note
To use vectors, you must import the Vector class:
import java.util.Vector;
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.
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.
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"));
}
}
static
{
buildCustomers();
}
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.
Abstract InventoryItem
superclass
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.
• 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.
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.
Nonsteerable Steerable
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.
Instructor Note
Interface is a way to bypass the multiple inheritance restriction that Java has.
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);
}
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.
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.
Instructor Note
Use the sort examples to demonstrate. Open the Demo.jws. There are two projects: Sort and
ExtendedSort. Start with the Sort project and launch the SortApplication.java for a
simple demonstration. Use the ExtendedSort project for a more complex demonstration. Launch
the ExtendedSortApplication.java file to demonstrate a double sort application.
MyApplication
Sort
The movie sortObjects()
returns the 3 2 asks a movie to
result of the compare itself with
comparison. another movie.
Movie
Value Meaning
Holds sortObjects():
Implements Sortable:
class myApplication {
Movie[] movielist;
… // build the array of Movie
Sort.sortObjects(movielist);
}
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.
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.
Instructor Note
There are some instances when errors can be caught and handled. For example, under some
circumstances your code can catch the error java.lang.ThreadDeath. See the
javadoc for details.
Exception object
Handler
for this
Yes exception? No
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).
Instructor Note
The term try means that the code is trying something that may throw an exception; catch
means that the code is handling the exception.
method2 method2
Exception
ex
method3 method3
Error
method4 code method4
If method3 ignores the The exception must be
error, then it will never be caught and handled
handled. somewhere.
Throwable
Error Exception
Unchecked (run-time)
exceptions
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.
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
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);
}
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();
}
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.
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.
catch (exception1 e) {
throw new exception2(…);
}
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.
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.
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-14
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.
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.
• Is based on a grid
• Allows components to span multiple rows and
columns
• Allows rows and columns to differ in size
• Uses the component’s 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 component’s 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.
External insets
Component
Cell position padding
Cell span
Expansion
weighting Anchoring
Fill rules
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.
Border
null
VerticalFlow
GridBag
Grid
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 frame’s 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).
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.
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.
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:
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.
Lesson Aim
This lesson shows how to provide a Java applet (or application) with a graphical user
interface based on components, such as buttons and text fields. You learn how to use
standard Java Swing components as well as the more sophisticated controls provided by
JDeveloper. You also learn how to provide event handler methods, to deal with events such
as button clicks and text changes.
Instructor Note
Further reading: The Java tutorial has a very good section on the Swing components:
http://java.sun.com/docs/books/tutorial/
• Text controls
– JTextField
– JPasswordField
– JTextArea
– JEditorPane
– JTextPane
• Graphic controls
– JTree
– JTable
– JToggleButton
Swing Components
Swing text components display text and can optionally allow the user to edit text. There are
five different text components that support the varying complexities and requirements. They
are:
• JTextField: Can display and edit only one line of text at a time
• JPasswordField: A subclass of JTextField (It works the same as
JTextField except that the input is hidden from the user.)
• JTextArea: Can display and edit multiple lines of text (This component is used to
allow the user to enter text of any length. It can display text in any font.)
• JEditorPane: Allows the use of more sophisticated text styles including multiple
fonts and embedded images (JEditorPane can read and write plain text, HTML,
and RTF text.)
• JTextPane: In addition to the facilities that are provided by JEditorPane, it
allows embedded components.
Code Editor
System Navigator
Context menu
UI Editor
You can invoke the Context menu by right-clicking the class in the Application Navigator
and selecting Open to view the class. The class will be displayed in the Code Editor. On the
bottom of the pane, there will be three tabs: Source, Class, and Design. Clicking the Design
tab will display the class using the UI Editor.
Generated Code
Whenever you modify a UI in JDeveloper, it automatically updates the source code for that
class in order to achieve the design that you have just specified. In fact, the source code is all
that matters; the Designer tool is just an easy way to generate the source code that is
required to achieve a certain visual appearance.
Instance Variables and Their Names
Each time you add a component to the UI, JDeveloper adds a corresponding instance
variable to your class. By default, the instance variable is assigned a default name based on
the class name and number, for example, jButton1 (as shown on the slide). To give the
variable a more meaningful name, change its name property in the Inspector, to replace all
usages of the name in the class. If you change the variable name manually in the source
code, then you must remember to replace all occurrences of the variable in the class.
The code lines that are generated in the jbInit() method to initialize the component and
add it to its container will vary based on the type of layout manager that is used by the
container. On the slide, the second parameter to the add() method on the content pane uses
the XYConstraints object because the container layout manager is XYLayout.
Context menu
when
right-clicking a
Click
menu item
menu bar
object in
Structure pane
to display
menu bar
Use the JDeveloper UI Editor to modify the menu to include the Order menu and its
menu items, as shown above.
Note: File > Exit already exists.
a. Edit the OrderEntryMDIFrame by using the UI Editor, expand the Menu
item in the Structure pane, and click the menuBar entry to display the initial
menu structure in the UI Editor window.
Oracle10g: Java Programming 15-17
Practice 15-1: Adding User Interface Components (continued)
b. Add the Order menu after the File menu. Right-click the outlined box on the right
side of the File menu item, and select the Insert Menu option from the context
menu.
c. The new menu should be selected and shown as jMenu1. With the menu
selected enter the text: Order, overwriting the default menu label text, and then
press the Enter key.
d. Select the new Order menu, and replace the name property value of jMenu1
with: menuOrder, and press the Enter key.
e. Save your work, and compile the class ensuring that there are no compilation
errors. What lines has JDeveloper added to the OrderEntryMDIFrame class?
2. Add the menu items and a separator to the Order menu.
a. Create each menu item by selecting the blank outline box at the bottom of the
Order menu, and enter the menu label text in the box. You can select the
menuOrder menu from the Structure so that the outline boxes are visible. After
creating the menu item entry, select the menu item box and set its name
property in the Inspector, according to the following table:
Menu item text Menu name property value
New newMenuItem
Open openMenuItem
Save saveMenuItem
Close closeMenuItem
<separator> See step b.
Print printMenuItem
Hint: You may want to add all menu labels first, and then set the name
properties.
b. Save and compile the class. Then run OrderEntry.java to view the menu.
Add Components to OrderEntryFrame to Form its Visual Structure
3. To add UI components, open OrderEntryFrame.java by right-clicking its name
in the Navigator; select the Design tab to invoke the UI Editor.
a. In the top panel, add Jlabel and JTextField components for the Customer
details. (These components can be found in the Swing pulldown.) Use the sample
window on the previous pages as a guide for the layout. Create label and text
field items by using the following table:
JLabel text property JTextField name property
Customer Id custIdTxt
Name custNameTxt
Address custAddressTxt
Phone custPhoneTxt
Hint: Aligning UI components works best with XYLayout manager, in which
alignment is relative to the first component clicked. Select additional
components, while holding [Shift] or [Control]. Right-click a selected component
and choose an Align option from the context menu. (Null layout hints on next
page).
Oracle10g: Java Programming 15-18
Practice 15-1: Adding User Interface Components (continued)
Hint: If you are using the null layout manager, then JDeveloper generates calls
to each component setBounds() method, with a Rectangle parameter
defining the components x, y location, width, and height. You can alter the
parameters (x, y, width, height) in the Rectangle constructor to manually
align and size components, or set the bounds property for each component in
the Inspector.
b. Select the JTextField1 component next to the Order Id label. Change its
name property to orderIdTxt.
c. Multiselect all customer JTextField items that you created in 3a, and delete
the text property, then press the Enter key.
Note: Selecting multiple components and changing a property value sets the
property to the same value for all the selected items.
d. Add a JButton to the right of the customer ID text field, and set the text
property to Find, and the name property to findBtn. Then save your work.
4. Add the components for the other order information, and components for adding
products to the order.
a. Create a JLabel and set the text property to Product Id. To the right of
the label add a JTextField and set its name property to prodIdTxt and
delete the value in the text property (and press the Enter key).
b. Below the product ID label and text field create a JButton component, and set
the name and text properties as follows:
Name property Text property
addBtn Add
c. Add two Jlabel components at the top-right side of the top panel, for the order
date. Set the first label text property to Order Date. Set the second label’s
name to orderDateLbl and its text property to the empty string. Select the
Swing Border option from the list and from the Border window, select the
LineBorder value. Set the border thickness to 1, if its not already set.
d. Add two more Jlabel components under the order date labels, for the order
total. Set the first label text property to Order Total. Set the second label’s
name to orderTotalLbl and its text property to the empty string. Select
the Swing Border option from the list and from the Border window, select the
LineBorder value. Set the border thickness to 1, if its not already set.
e. Add a JList component into the scroll pane in the bottom panel of the
OrderEntryFrame. The list component should fill the entire bottom section
of the frame (just click in the lower pane, and the Jlist will expand and take
up the entire pane). Set the list name property to orderItemList.
f. Save and compile the OrderEntryFrame class.
g. Run the OrderEntry.java application to view the resulting UI layout in the
internal frame. Quickly make minor adjustments to the UI layout to make all
items pleasantly visible.
• How it works:
– Event originates from source and generates an
event object.
– An event listener hears a specific event.
– An event handler determines what to do.
• Setting it up:
1. Create an event source object.
2. Create an event listener object implementing an
interface with methods to handle the event object.
3. Write an event-specific method to handle the event.
4. Register the listener object with the event source
for the specified event.
Source
Event listener object
OK
Handler method
Source
Event listener object
OK
Notified Handler method
Source
Event listener object
OK Handler method:
Source
save changes and quit
Swing components, by default, implicitly create and store data in a default model that suits
their requirement. You can use all components to explicitly create and use an appropriate
model, usually based on those shown in the table above.
List Components
The JList and JComboBox are Swing components that handle lists of data. The slide
discusses some of the methods that are provided by the JList class.
Vector vector = new Vector();
Jlist list = new JList(vector);
For example, if you create a JList object with the constructor accepting a vector, then the
vector elements are copied to an internally created DefaultListModel object. Thus, if
you add elements to the vector, with the addElement() method, then the new elements
will not be visible through the Jlist unless you call the
JList.setListData() method passing the updated
vector object as an argument his is
inefficient as the elements are copied
from the vector again and a new
DefaultListModel object is created internally
t is better to create the DefaultListModel
object first and use it like you would a
Vector and create the JList with the
appropriate constructor for example
DefaultListModel model = new DefaultListMode();
Jlist list = new JList(model);
Oracle10g: Java
or call the setModel() Programming s
method 15-31
elements
are added to the DefaultListModel object by
What Events Can
a Component Generate?
Event handler
methods
void findButton_actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
int custId = 0;
Customer customer = null;
if (custIdTxt.getText().length() > 0) {
try {
custId = Integer.parseInt(custIdTxt.getText());
customer = DataMan.findCustomerById(custId);
order.setCustomer(customer);
custNameTxt.setText(customer.getName());
Oracle10g: Java Programming 15-40
custAddressTxt.setText(customer.getAddress());
custPhoneTxt.setText(customer.getPhone());
Practice 15-2: Adding Event Handling (continued)
catch (NumberFormatException err) {
JOptionPane.showMessageDialog(this,
"The Customer Id: " + err.getMessage() +
" is not a valid number",
"Error", JOptionPane.ERROR_MESSAGE);
custIdTxt.setText("");
}
catch (NotFoundException err) {
JOptionPane.showMessageDialog(this,
err.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
custIdTxt.setText("");
}
}
else {
JOptionPane.showMessageDialog(this,
"Please enter a Customer Id", "Error",
JOptionPane.ERROR_MESSAGE);
}
Note: Remember to import javax.swing.JOptionPane.
c. Compile and save your changes. Run the OrderEntry application to test your
code changes (customer IDs range from 1 to 6).
Optional Extra Credit
Add Event Handling for Add Product Button
Write code to add products to the order. The code reads the product ID that is entered and
supplies it to the order.addOrderItem() method. You also update the Order Total field with
the latest total after each product is added to the order. Handle errors as appropriate. The
Remove button should be disabled if an item is not selected from the list.
4 dit the OrderEntryFrame class in the
ditor
a. Select the Add button to generate its actionPerformed event handler containing
the following code:
void addBtn_actionPerformed(ActionEvent e)
Product p = null;
int prodId = 0;
if (prodIdTxt.getText().length() > 0) {
try {
prodId = Integer.parseInt(prodIdTxt.getText());
p = DataMan.findProductById(prodId);
order.addOrderItem(p.getId());
orderTotalLbl.setText(
Util.toMoney(order.getOrderTotal()));
}
Lesson Aim
This lesson introduces you to using Java to access an Oracle database. This lesson
introduces you to the basic use of JDBC to query a database from a Java class. It presents
the different steps required to perform SQL statements.
Web Application
Client server server Data
Business
Presentation
logic
Oracle
Oracle database
Application Server 10g
J2EE Certified Environment
JDBC
// Standard packages
import java.sql.*;
import java.math.*; // optional
// Oracle extension to JDBC packages
import oracle.jdbc.*;
import oracle.sql.*;
2. Obtain a connection.
OracleDriver
Database
JDBC calls • Thin client commands
• OCI Database
• Server-based
•…
Applet
JDBC
Oracle
Thin driver
Client Server
Application
JDBC
OCI driver
Oracle
ocixxx.dll
Client Server
Applet Thin
Thin
EJB, servlet
(on the middle tier)
OCI
jdbc:<subprotocol>:<subname>
jdbc:oracle:<driver>:@<database>
JDBC URLs
JDBC uses a URL to identify the database connection. A JDBC URL looks different from an
HTTP or FTP URL. But, like any URL, it is a locator for a particular resource; in this case, a
database. The structure of a JDBC URL is flexible, allowing the driver writer to specify
what to include in the URL. End users need to learn what structure their vendor uses.
The slide shows the general syntax for a JDBC URL and the syntax that Oracle uses for
connecting with an Oracle driver. The general syntax of a JDBC URL is as follows:
jdbc:<subprotocol>:<subname>
• jdbc is the protocol. All URLs start with their protocol.
• <subprotocol> is the name of a driver or database connectivity mechanism. Driver
developers register their subprotocols with JavaSoft to make sure that no one else uses
the same subprotocol name. For all Oracle JDBC drivers, the subprotocol is oracle.
• <subname> identifies the database. The structure and contents of this string are
determined by the driver developer. For Oracle JDBC drivers, the subname is
<driver>:@<database>, where:
- <driver> is the driver
- <database> provides database connectivity information
The following slides describe the syntax of an Oracle JDBC URL for the different JDBC
drivers for client-side Java application code.
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");
Statement stmt = conn.createStatement();
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM order_items
WHERE order_id = 2354");
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("CREATE TABLE temp (col1 NUMBER(5,2),
col2 VARCHAR2(30)");
import java.sql.*;
class TestJdbc {
public static void main (String args [ ]) throws SQLException {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myHost:1521:ORCL","scott", "tiger");
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery
("SELECT ename FROM emp");
while (rset.next ())
System.out.println (rset.getString ("ename"));
rset.close();
stmt.close();
conn.close();
}
}
Handling Exceptions
You can use the try-catch-finally block structure for closing resources.
Code Example
Connection conn = null; Statement stmt = null;
ResultSet rset = null; // initialize
stmt = conn.createStatement();
try {
rset = stmt.executeQuery("SELECT empno, ename FROM emp");
}
catch (java.sql.SQLException e)
{ ... /* handle errors */ }
...
// Clean up resources
finally {
try { if (rset != null) rset.close(); } catch (Exception e) {}
try { if (stmt != null) stmt.close(); } catch (Exception e) {}
try { if (conn != null) conn.close(); } catch (Exception e) {}
}
Oracle10g: Java Programming 16-29
Managing Transactions
PreparedStatement
PreparedStatement is inherited from Statement; the difference is that
PreparedStatement holds precompiled SQL statements.
If you execute a Statement object many times, its SQL statement is compiled each time.
PreparedStatement is more efficient because its SQL statement is compiled only once,
when you first prepare PreparedStatement. After that, each time you execute the SQL
statement in PreparedStatement, the SQL statement does not have to be recompiled.
Therefore, if you need to execute the same SQL statement several times in an application, it
is more efficient to use PreparedStatement than Statement.
PreparedStatement Parameters
PreparedStatement does not have to execute exactly the same query each time. You
can specify parameters in the PreparedStatement SQL string and supply the actual
values for these parameters when the statement is executed.
The next slide shows how to supply parameters and execute a prepared statement.
PreparedStatement pstmt =
conn.prepareStatement
("UPDATE emp SET ename = ? WHERE empno = ?");
PreparedStatement pstmt =
conn.prepareStatement
("SELECT ename FROM emp WHERE empno = ?");
Creating a PreparedStatement
To write changes to the database, such as for INSERT or UPDATE operations, you typically
create a PreparedStatement object. You can use the PreparedStatement object
to execute a statement with varying sets of input parameters. The prepareStatement()
method of your JDBC Connection object allows you to define a statement that takes bind
variable parameters, and returns a JDBC PreparedStatement object with your
statement definition.
Java servlet
Data source
ConnectionPoolDataSource
JDBC Database
driver
Database
commands
Lesson Aim
This lesson describes how to deploy a Java application by using WebStart. The lesson covers the
sequence of steps necessary to create a deployment profile and an application archive. After the
application archive has been created and deployed, the lesson describes the role of the Java
Network Launching Protocol (JNLP) file and how to create it.
1. Request the
application.
2. Launch Web Start on
1 HTTP 2
the local machine.
3. Download the
application.
3
4. Launch the
HTTP
application (Draw).
4
(The command depends on the DOS Path environment variable being set to use the
Java JDK and run-time environment. The Path environment must include something
like D:\jdev\jdk\jre\bin).
Note: If this command prompts you for an administrator password as follows:
Enter an admin password to use:
Click Enter to accept and use the default. The default password is welcome.
Remember the password; you will need it while creating a Connection.
Important: When OC4J starts, text similar to the following should be displayed:
Oracle Application Server Containers for J2EE 10g
(9.0.4.0.0) initialized.
Do not close the DOS window. Later, you start another DOS window and
enter a command to gracefully shut down the OC4J server.
Create an Application Server Connection in JDeveloper
4. To deploy the application to the OC4J server, you must create a connection in
JDeveloper.
a. In the Navigator, select the Connections tab, then right-click the Application Server
node, and select the New Application Server Connection option.
b. Click Next in the Welcome page of the Connection Wizard. In Step 1 of 4: Type
page, enter the connection name OC4J, leaving the Connection Type at its default
(Standalone OC4J). Click Next.
c. In the Step 2 of 4: Authentication page, enter welcome in the Password field,
leaving the Username at its default (admin). Do not select the Deploy Password
check box. Click Next.
d. In the Step 3 of 4: Connection page, accept the default values and click Next.
e. In the Step 4 of 4: Test page, click the Test Connection button, and verify whether
you can successfully connect to the running OC4J application server. Correct any
problems, asking the instructor for help, if necessary.
Note: If you were successful in making a connection, the area below the Test
Connection button should display the text: Success!
f. Click Finish, to complete this step.