Sunteți pe pagina 1din 435

Oracle10g: Java Programming

Electronic Presentation

D17249GC11
Edition 1.1
August 2004
D39817

Authors

Copyright 2004, Oracle. All rights reserved.

Jeff Gallus
Glenn Stokol

This documentation contains proprietary information of Oracle Corporation. It is provided under a


license agreement containing restrictions on use and disclosure and is also protected by copyright
law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S.
Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the
following legend is applicable:

Technical Contributors
and Reviewers
Kenneth Cooper
Peter Driver
Christian Dugas
Craig Hollister
Chika Izumi
Pete Laseau
Glenn Maslen
Monica Motley
Gayathri Rajagopal
Publisher
Poornima G

Restricted Rights Legend


Use, duplication or disclosure by the Government is subject to restrictions for commercial computer
software and shall be deemed to be Restricted Rights software under Federal law, as set forth in
subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software
(October 1988).
This material or any portion of it may not be copied in any form or by any means without the express
prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and
may result in civil and/or criminal penalties.
If this documentation is delivered to a U.S. Government Agency not within the Department of
Defense, then it is delivered with Restricted Rights, as defined in FAR 52.227-14, Rights in DataGeneral, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you find any problems in the
documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle
Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this
document is error-free.
All references to Oracle and Oracle products are trademarks or registered trademarks of Oracle
Corporation.
All other products or company names are used for identification purposes only, and may be
trademarks of their respective owners.

Introduction

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this course, you should be able to do


the following:
Write stand-alone applications with the Java
programming language
Develop and deploy an application
Build, generate, and test application components
by using Oracle JDeveloper 10g

I-2

Copyright 2004, Oracle. All rights reserved.

Course Overview

I-3

This course teaches you how to write Java


applications.
You also learn how to build, debug, and deploy
applications by using Oracle JDeveloper 10g.
The development environment is Oracle
JDeveloper 10g and the Oracle Database.

Copyright 2004, Oracle. All rights reserved.

Introducing the Java


and Oracle Platforms

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Identify the key elements of Java
Describe the Java Virtual Machine (JVM)
Examine how Java is used to build applications
Identify the key components of the J2SE Java
Development Kit (known as JDK or SDK)
Describe Java deployment options

1-2

Copyright 2004, Oracle. All rights reserved.

What Is Java?

Java:
Is a platform and an object-oriented language
Was originally designed by Sun Microsystems for
consumer electronics
Contains a class library
Uses a virtual machine for program execution

1-3

Copyright 2004, Oracle. All rights reserved.

Key Benefits of Java

1-4

Object-oriented
Interpreted and platform-independent
Dynamic and distributed
Multithreaded
Robust and secure

Copyright 2004, Oracle. All rights reserved.

An Object-Oriented Approach

Objects and classes


An object is a run-time representation of a thing.
A class is a static definition of things.

Class models elaborate:

Existing classes and objects


Behavior, purpose, and structure
Relationships between classes
Relationships between run-time objects

Same models exist throughout the project.


Analysis

Design

Implementation

CLASS MODELS

1-5

Copyright 2004, Oracle. All rights reserved.

Integration
and testing

Platform Independence

Java source code is stored as text in a .java file.


The .java file is compiled into .class files.
A .class file contains Java bytecodes
(instructions).
The bytecodes are interpreted at run time.
The Java .class file is the executable code.

Compile
(javac)
Movie.java
1-6

JVM
(java)
Movie.class

Running program

Copyright 2004, Oracle. All rights reserved.

Using Java with Enterprise


Internet Computing
Client

Web
server

Application
server

Presentation

Business
logic

Servlets
JavaServer
Pages (JSPs)
1-7

Enterprise
JavaBeans (EJB)
CORBA

Copyright 2004, Oracle. All rights reserved.

Data

Using the Java Virtual Machine

Operating system

JVM
Application

1-8

Copyright 2004, Oracle. All rights reserved.

How Does JVM Work?

The class loader loads all required classes.


JVM uses a CLASSPATH setting to locate class files.

JVM Verifier checks for illegal bytecodes.


JVM Verifier executes bytecodes.
JVM may invoke a Just-In-Time (JIT) compiler.

Memory Manager releases memory used by the


dereferenced object back to the OS.
JVM handles Garbage collection.

1-9

Copyright 2004, Oracle. All rights reserved.

Benefits of Just-In-Time (JIT) Compilers

JIT compilers:
Improve performance
Are useful if the same bytecodes are executed
repeatedly
Translate bytecodes to native instruction
Optimize repetitive code, such as loops
Use Java HotSpot VM for better performance and
reliability

1-10

Copyright 2004, Oracle. All rights reserved.

Implementing Security
in the Java Environment
Language and compiler

Class loader

Bytecode verifier

Interface-specific access

1-11

Copyright 2004, Oracle. All rights reserved.

Deployment of Java Applications

Client-side deployment:
JVM runs stand-alone applications from the
command line.
Classes load from a local disk, eliminating the need
to load classes over a network.

Server-side deployment:
Serves multiple clients from a single source
Is compatible with a multitier model for Internet
computing.

1-12

Copyright 2004, Oracle. All rights reserved.

Using Java with Oracle 10g

Client

Web
server

Application
server

Presentation

Business
logic

Oracle
Application Server

1-13

Copyright 2004, Oracle. All rights reserved.

Data

Oracle
database

Java Software Development Kit

Sun Java J2SE (known as JDK and Java SDK)


provides:
Compiler (javac)
Core class library
classes.zip
rt.jar

1-14

Debugger (jdb)

Bytecode interpreter: The JVM (java)


Documentation generator (javadoc)
Java Archive utility (jar)

Others
Copyright 2004, Oracle. All rights reserved.

J2SE

Using the Appropriate Development Kit

Java2 comes in three sizes:


J2ME (Micro Edition): Version specifically targeted
at the consumer space
J2SE (Standard Edition): Complete ground-up
development environment for the Internet
J2EE (Enterprise Edition): Everything in the J2SE
plus an application server and prototyping tools

1-15

Copyright 2004, Oracle. All rights reserved.

Integrated Development Environment

Development

Debug

UML

Exchange

ADF

Database

Synchronized changes

XML
SCM

1-16

HTML

Deployment

Copyright 2004, Oracle. All rights reserved.

Exploring the JDeveloper Environment

Component Palette

System Navigator
1-17

Code Editor
Copyright 2004, Oracle. All rights reserved.

Property Inspector

Oracle10g Products

1-18

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


Java code is compiled into platform-independent
bytecodes.
Bytecodes are interpreted by JVM.
Java applications can be stand-alone or
implemented across an Internet-computing model.

1-19

Copyright 2004, Oracle. All rights reserved.

Defining Object-Oriented Principles

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define objects and explain how they are used
Associate objects so that they can communicate
and interact via messages
Define classes and explain how they are used
Describe object-oriented (OO) principles: classes,
objects, and methods
Describe the value of Reusable Software
Components
Examine the OO model that is used in this course

2-2

Copyright 2004, Oracle. All rights reserved.

What Is Modeling?

Models perform the following functions:


Describe exactly what the business needs
Facilitate discussion
Prevent mistakes

2-3

Modeling and implementation are treated


separately.
Before coding can begin, the model must be
correct.

Copyright 2004, Oracle. All rights reserved.

What Are Classes and Objects?

A class:
Models an abstraction of objects
Defines the attributes and behaviors of
objects
Is the blueprint that defines an object

An object:
Is stamped out of the class mold
Is a single instance of a class
Retains the structure and behavior
of a class

2-4

Copyright 2004, Oracle. All rights reserved.

An Objects Attributes Maintain Its State

Objects have knowledge about their current state.


Each piece of knowledge is called an attribute.
The values of attributes dictate the objects state.

2-5

Object: My blue pen

Attribute: Ink amount

Object: Acme Bank ATM

Attribute: Cash available

Copyright 2004, Oracle. All rights reserved.

Objects Have Behavior

An object exists to provide behavior (functionality)


to the system.
Each distinct behavior is called an operation.

Object: My blue pen

Object: Acme Bank ATM


2-6

Operation: Write

Operation: Withdraw

Copyright 2004, Oracle. All rights reserved.

Objects Are Modeled as Abstractions

A Java object is modeled as an abstract


representation of a real-world object.
Model only those attributes and operations that
are relevant to the context of the problem.

Context: Product catalog


Real-world attributes/operations that you may want to model:
Attributes: Model, manufacturer, price
Operations: Change price

Real-world attributes/operations that you may not want to model:


Attributes: Ink color
Operations: Refill, change color, point, write

2-7

Copyright 2004, Oracle. All rights reserved.

Defining Object Composition

Objects can be composed of other objects.


Objects can be part of other objects.
This relationship between objects is known as
aggregation.

A PC may be
an object.

2-8

A PC may have a
keyboard, mouse, and
network card, all of which
may be objects.
Copyright 2004, Oracle. All rights reserved.

A PC may have a
CD drive, which
may be an object.

The Donut Diagram

getName

setBirthdate

name
address
birthdate

getAddress

getAge

getAge()
Message

setAddress

Person
2-9

Copyright 2004, Oracle. All rights reserved.

Client or
sender

Guided Practice:
Spot the Operations and Attributes

2-10

Copyright 2004, Oracle. All rights reserved.

Collaborating Objects

Collaborating objects work together to complete a task


and form the basis of an application system.
All methods are defined within a class and are not
defined globally as in traditional languages.
All objects are created from classes and contain
all the attributes and methods of that class.
Objects must associate with each other to
collaborate on common tasks.
Associated objects communicate by sending
messages.

2-11

Copyright 2004, Oracle. All rights reserved.

Objects Interact Through Messages

Objects communicate by sending messages.


A sending object must be associated with or
linked to the receiving object.
The message sender requests the receiver to
perform the operation that is named in the
message.
This communication is similar to calling a
procedure:
The sender calls a method of the receiver.
The receiver executes the called method.

Calling a method is always in the context of a


particular object:
myPen.write( ): Object-oriented programming
write (myPen): Traditional structured
programming

2-12

Copyright 2004, Oracle. All rights reserved.

What Is a Class?

A class is a template for objects.


A class definition specifies the operations and
attributes for all instances of that class.
A class is used to manage complexity.

When you create my blue pen, you do not have to


specify its operations or attributes. You simply
say what class it belongs to.

2-13

Copyright 2004, Oracle. All rights reserved.

How Do You Identify a Class?

Identify the common behavior and structure for a


group of objects.
Recognize a single coherent concept.
Caution: A common misconception is the use of
the words classes and objects interchangeably.
Classes define objects.
My blue pen

ops:
attribs:

Your blue pen ops:


attribs:

2-14

write, refill
ink amount, color of ink
write, refill
ink amount

Copyright 2004, Oracle. All rights reserved.

Comparing Classes and Objects

2-15

Classes are static definitions that you can use to


understand all the objects of that class.
Objects are the dynamic entities that exist in the
real world and your simulation of it.
Caution: OO people almost always use the words
classes and objects interchangeably; you must
understand the context to differentiate between
the two meanings.

Copyright 2004, Oracle. All rights reserved.

What Is Encapsulation?

Encapsulation hides the internal structure and


operations of an object behind an interface.
A bank ATM is an object that gives its users cash.
The ATM hides (encapsulates) the actual operation
of withdrawal from the user.
The interface (way to operate the ATM) is provided
by the keyboard functions, screen, cash dispenser,
and so on.
Bypassing the encapsulation is bank robbery.

2-16

Bypassing encapsulation in object-oriented


programming is impossible.

Copyright 2004, Oracle. All rights reserved.

What Is Inheritance?

There may be a commonality between different


classes.
Define the common properties in a superclass.

Savings account

2-17

Account

Checking account

The subclasses use inheritance to include those


properties.
Copyright 2004, Oracle. All rights reserved.

Using the Is-a-Kind-of Relationship

2-18

A subclass object
is-a-kind-of
superclass
object.
A subclass must
have all the
attributes and
behaviors of the
superclass.

Account

Pen

Savings account

Pencil

Copyright 2004, Oracle. All rights reserved.

What Is Polymorphism?

Polymorphism refers to:


Many forms of the same operation
The ability to request an operation with the same
meaning to different objects. However, each object
implements the operation in a unique way.
The principles of inheritance and object
substitution.

Load passengers
2-19

Copyright 2004, Oracle. All rights reserved.

Architecture Rules for Reuse

Write code that contains:


Events that can interact with your Java application
Properties that can be exposed
Methods that can be invoked
Write code that supports:
Introspection or reflection
Customization
Persistence

2-20

Copyright 2004, Oracle. All rights reserved.

Engineering for a Black Box Environment

JavaBeans follow the black box approach which


enables you to:
Simplify something of arbitrary complexity down
to a single object that everyone can understand
Think of large systems as a collection of
interconnected entities (black boxes)
communicating via their interfaces

2-21

Copyright 2004, Oracle. All rights reserved.

Order Entry UML Diagram

2-22

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


An object is an abstraction of a real-world object.
A class is a template or blueprint for objects.
Classes form inheritance trees: Operations that
are defined in one class are inherited by all
subclasses.
Polymorphism frees the caller from knowing the
class of the receiving object.

2-23

Copyright 2004, Oracle. All rights reserved.

Practice 2: Overview

This practice covers:


Identifying business objects for the Order Entry
system
Identifying methods for the classes
Identifying attributes for the classes
Searching for inheritance in the classes
Examining UML class model for course
application

2-24

Copyright 2004, Oracle. All rights reserved.

Order Entry System


Partial UML Class Model
Order
Customer

id: int
orderDate: Date
shipDate: Date
shipMode: String
orderTotal: double

name: String
address: String
phone: String
getName()
setName()
setAddress()
getAddress()
:

addItem()
removeItem()
setOrderDate()
getOrderDate()
setShipDate()
:

OrderItem
lineNo: int
quantity: int
price: double
getQuantity()
setQuantity()
setPrice()
getPrice()
getItemTotal()
:

Product
Company

Individual

contact: String
discount: int

licNumber: String

getContact()
setContact()
:

setLicNumber()
getLicNumber()
:

2-25

Copyright 2004, Oracle. All rights reserved.

id: int
name: String
description: String
retailPrice: double
getPrice()
:

Basic Java Syntax and Coding


Conventions

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Identify the key components of the Java language
Identify the three top-level constructs in a Java
program
Identify and describe Java packages
Describe basic language syntax and identify Java
keywords
Identify the basic constructs of a Java program
Compile and run a Java application
Examine the JavaBean architecture as an example
of standard coding practices
Use the CLASSPATH variable and understand its
importance during compile and run time
3-2

Copyright 2004, Oracle. All rights reserved.

Examining Toolkit Components

The J2SE/J2EE from Sun provides:


Compiler
Bytecode interpreter
Documentation generator

J2SE

3-3

Copyright 2004, Oracle. All rights reserved.

Exploring Packages in J2SE/J2EE

The J2SE/J2EE from Sun provides standard packages


for:
Language
Windowing
Input/output
Network communication

J2SE

3-4

Copyright 2004, Oracle. All rights reserved.

Documenting Using the J2SE

The J2SE/J2EE from Sun provides documentation


support for:
Comments
Implementation
Documentation

Documentation generator

J2SE

3-5

Copyright 2004, Oracle. All rights reserved.

Contents of a Java Source

A Java source file can contain three top-level


constructs:
Only one package keyword followed by the package
name, per file
Zero or more import statements followed by fully
qualified class names or * qualified by a package
name
One or more class or interface definitions
followed by a name and block

3-6

File name must have the same name as the public


class or public interface.

Copyright 2004, Oracle. All rights reserved.

Establishing Naming Conventions

Naming conventions include:


Class names
Customer, RentalItem, InventoryItem

File names
Customer.java, RentalItem.java

Method names
getCustomerName(), setRentalItemPrice()

Package names
oracle.xml.xsql, java.awt, java.io

3-7

Copyright 2004, Oracle. All rights reserved.

More About Naming Conventions

Variables:
customerName, customerCreditLimit

Constants:
MIN_WIDTH, MAX_NUMBER_OF_ITEMS

3-8

Uppercase and lowercase characters


Numerics and special characters

Copyright 2004, Oracle. All rights reserved.

Defining a Class

Class definitions typically include:


Access modifier
Class keyword
Instance fields
Constructors
Instance methods
Class fields
Class methods

3-9

Copyright 2004, Oracle. All rights reserved.

Rental Class: Example


Access modifier
public class Rental {
//Class variable
static int lateFee;
// Instance variables
int rentalId;
String rentalDate;
float rentalAmountDue;

// Instance methods
float getAmountDue (int rentId) {

3-10

Copyright 2004, Oracle. All rights reserved.

Declaration

Instance
variable

Instance
method

Creating Code Blocks

Enclose all class declarations.


Enclose all method declarations.
Group other related code segments.
public class SayHello {
public static void main(String[] args) {
System.out.println("Hello world");
}
}

3-11

Copyright 2004, Oracle. All rights reserved.

Defining Java Methods

Always define within a class.


Specify:

Access modifier
Static keyword
Arguments
Return type

[access-modifiers] [static] "return-type"


"method-name" ([arguments]) {
"java code block }
return

3-12

Copyright 2004, Oracle. All rights reserved.

Examples of a Method
public float getAmountDue (String cust){
// method variables
int numberOfDays;
float due;
float lateFee = 1.50F;
String customerName;
// method body
numberOfDays = getOverDueDays();
due = numberOfDays * lateFee;
customerName = getCustomerName(cust);
return due;
}

3-13

Copyright 2004, Oracle. All rights reserved.

Declaration

Method
variables

Method
statements

Return

Declaring Variables

3-14

You can declare variables anywhere in a class


block, and outside any method.
You must declare variables before they are used
inside a method.
It is typical to declare variables at the beginning of
a class block.
The scope or visibility of variables is determined
in the code block.
You must initialize method variables before using
them.
Class and instance variables are automatically
initialized.
Copyright 2004, Oracle. All rights reserved.

Examples of Variables
in the Context of a Method
public float getAmountDue (String cust) {
float due = 0;
int numberOfDays = 0;
float lateFee = 1.50F;
{int tempCount = 1; // new code block
due = numberOfDays * lateFee;
tempCount++;

}
// end code block
return due;
}

3-15

Copyright 2004, Oracle. All rights reserved.

Method
variables

Temporary
variables

Rules for Creating Statements

3-16

Use a semicolon to terminate statements.


Define multiple statements within braces.
Use braces for control statements.

Copyright 2004, Oracle. All rights reserved.

What Are JavaBeans?

A JavaBean is a platform-neutral reusable software


component that:
Can be manipulated visually in a builder tool
Communicates with other JavaBeans via events
Comprises visible components that must inherit
from other visible components
Provides an architecture for constructing the
building blocks of an application

3-17

Copyright 2004, Oracle. All rights reserved.

Managing Bean Properties

Properties are the bean class member variables.


(Variables can be primitive types or objects.)
A property can be:
Unbound, which is a simple property
Bound, which triggers an event when the field is
altered
Constrained, in which changes are accepted or
vetoed by interested listener objects

3-18

Copyright 2004, Oracle. All rights reserved.

Exposing Properties and Methods

Getter
methods
(public)

3-19

private
T var;
T[] arr;

getVar()

Setter
methods
(public void)

setVar(T val)

T[] getArr()

setArr(T[] val)

boolean isVar()

setVar(boolean val)

Copyright 2004, Oracle. All rights reserved.

JavaBean Standards at Design Time

The benefits at design time include:


A facilitated interaction between designer, tool,
and bean
Instantiated and functioning beans in a visual tool
Highly iterative development environment
Building applications in small bits that plug in and
out
Storage and recovery of instantiated
objects

3-20

Copyright 2004, Oracle. All rights reserved.

Compiling and Running


a Java Application

To compile a .java file:


prompt> javac SayHello.java
compiler output

To execute a .class file:


prompt> java SayHello
Hello world
prompt>

3-21

Remember that case matters.

Copyright 2004, Oracle. All rights reserved.

The CLASSPATH Variable

Is defined in the operating system


Directs the JVM and Java applications where to
find .class files

References built-in libraries or user-defined


libraries
Enables interpreter to search paths, and loads
built-in classes before user-defined classes
Can be used with javac and java commands

3-22

Copyright 2004, Oracle. All rights reserved.

CLASSPATH: Example
Location of .class files in the oe package

Setting CLASSPATH
C:\>set CLASSPATH=D:labs\les03\classes\oe

3-23

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


J2SE provides basic Java tools.
J2SE provides a rich set of predefined classes and
methods.
Java programs are made up of classes, objects,
and methods.
Adhering to programming standards makes code
easier to read and reuse.

3-24

Copyright 2004, Oracle. All rights reserved.

Practice 3: Overview

This practice covers:


Examining the Java environment
Writing and running a simple Java application
Examining the course solution application
Inspecting classes, methods, and variables
Creating class files and an application class with a
main( ) method

3-25

Compiling and running an application

Copyright 2004, Oracle. All rights reserved.

Exploring Primitive Data Types


and Operators

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Distinguish between reserved words and other
names in Java
Describe Java primitive data types and variables
Declare and initialize primitive variables
Use operators to manipulate primitive variables
Describe uses of literals and Java operators
Identify valid operator categories and operator
precedence
Use String object literals and the concatenation
operator
4-2

Copyright 2004, Oracle. All rights reserved.

Reserved Keywords

boolean
byte
char
double
float
int
long
short
void
true
false
null

4-3

abstract
final
native
private
protected
public
static
synchronized
transient
volatile
strictfp

break
case
catch
continue
default
do
else
finally
for
if
return
switch
throw
try
while

Copyright 2004, Oracle. All rights reserved.

class
extends
implements
interface
throws
import
package
instanceof
new
super
this

Variable Types

Eight primitive data types:


Six numeric types
A character type
A Boolean type (for truth values)

User-defined types:
Classes
Interfaces
Arrays

4-4

Copyright 2004, Oracle. All rights reserved.

ab

Primitive Data Types


Integer

Floating
Point

Character

True
False

byte
short
int
long

float
double

char

boolean

1, 2, 3, 42
07
0xff

3.0F
.3337F
4.022E23

'a' '\141'
'\u0061'
'\n'

true
false

0.0f

\u0000

false

Append uppercase or lowercase L or F to the number


to specify a long or a float number.
4-5

Copyright 2004, Oracle. All rights reserved.

What Are Variables?

A variable is a basic unit of storage.


Variables must be explicitly declared.
Each variable has a type, an identifier, and a
scope.
There are three types of variables: class, instance,
and method.
Title: Blue
Moon
Type
Identifier
int myAge;
boolean isAMovie;
float maxItemCost = 17.98F;

4-6

Copyright 2004, Oracle. All rights reserved.

Initial value

Declaring Variables

Basic form of variable declaration:


type identifier [ = value];

public static void main(String[] args) {


int itemsRented = 1;
float itemCost;
int i, j, k;
double interestRate;
}

4-7

Variables can be initialized when declared.

Copyright 2004, Oracle. All rights reserved.

Local Variables

Local variables are defined only within a method


or code block.
They must be initialized before their contents are
read or referenced.

class Rental {
private int instVar;
// instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3;
// local variable
}
}

4-8

Copyright 2004, Oracle. All rights reserved.

Defining Variable Names

Variable names must start with a letter of the


alphabet, an underscore, or a $ symbol.
Other characters may include digits.
a
itemCost
item$Cost

4-9

item_Cost
_itemCost
itemCost2

item#Cost
item*Cost
2itemCost

item-Cost
abstract

Use meaningful names for variables, such as


customerFirstName and ageNextBirthday.

Copyright 2004, Oracle. All rights reserved.

What Are Numeric Literals?


Six types: byte, short, int, long, float, double

4-10

Integer literals

0 1 42 -23795
02 077 0123
0x0 0x2a 0X1FF
365L 077L 0x1000L

Floating-point
literals

1.0 4.2 .47


1.22e19 4.61E-9
6.2f 6.21F

Copyright 2004, Oracle. All rights reserved.

(decimal)
(octal)
(hex)
(long)

What Are Nonnumeric Literals?

Boolean literals

Character literals

String literals

4-11

true false

'a'

'\n'

'\t'

'\077' '\u006F'

"Hello, world\n"

Copyright 2004, Oracle. All rights reserved.

Guided Practice: Declaring Variables

Find the mistakes in this code and fix them:


1
2
3
4
5
6
7
8
9
10
11

4-12

byte sizeof = 200;


short mom = 43;
short hello mom;
int big = sizeof * sizeof * sizeof;
long bigger = big + big + big
// ouch
double old = 78.0;
double new = 0.1;
boolean consequence = true;
boolean max = big > bigger;
char maine = "New England state";
char ming = 'd';

Copyright 2004, Oracle. All rights reserved.

What Are Operators?

4-13

Operators manipulate data and objects.


Operators take one or more arguments and
produce a value.
There are 44 different operators.
Some operators change the value of the operand.

Copyright 2004, Oracle. All rights reserved.

Categorizing Operators

There are five types of operators:


Assignment
Arithmetic
Integer bitwise
Relational
Boolean

4-14

Copyright 2004, Oracle. All rights reserved.

Using the Assignment Operator

The result of an assignment operation is a value and


can be used whenever an expression is permitted.
The value on the right is assigned to the identifier
on the left:
int var1 = 0, var2 = 0;
var1 = 50;
// var1 now equals 50
var2 = var1 + 10; // var2 now equals 60

The expression on the right is always evaluated


before the assignment.
Assignments can be strung together:
var1 = var2 = var3 = 50;

4-15

Copyright 2004, Oracle. All rights reserved.

Working with Arithmetic Operators

Perform basic arithmetic operations.


Work on numeric variables and literals.
int
a =
b =
c =
d =
e =

4-16

a, b, c, d, e;
2 + 2;
// addition
a * 3;
// multiplication
b - 2;
// subtraction
b / 2;
// division
b % 2;
// returns the remainder of division

Copyright 2004, Oracle. All rights reserved.

More on Arithmetic Operators

Most operations result in int or long:


byte, char, and short values are promoted to
int before the operation.
If either argument is of the long type, then the
other is also promoted to long, and the result is of
the long type.
byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2;
// ERROR: result is an int
// b3 is byte

4-17

Copyright 2004, Oracle. All rights reserved.

Examining Conversions and Casts

Java automatically converts a value of one


numeric type to a larger type.

byte

int

long

Java does not automatically downcast.


byte

4-18

short
char

short
char

int

Copyright 2004, Oracle. All rights reserved.

long

Incrementing and Decrementing Values

The ++ and -- operators increment and decrement


by 1, respectively:
int var1 = 3;
var1++;

// var1 now equals 4

The ++ and -- operators can be used in two ways:


int var1 = 3, var2 = 0;
var2 = ++var1;
// Prefix: Increment var1 first,
//
then assign to var2.
var2 = var1++;
// Postfix: Assign to var2 first,
//
then increment var1.

4-19

Copyright 2004, Oracle. All rights reserved.

Relational and Equality Operators

>
>=
<
<=
==
!=

greater than
greater than or equal to
less than
less than or equal to
equal to
not equal to

int var1 = 7, var2 = 13;


boolean res = true;
res = (var1 == var2);
res = (var2 > var1);

4-20

// res now equals false


// res now equals true

Copyright 2004, Oracle. All rights reserved.

Using the Conditional Operator (?:)

Useful alternative to ifelse:


boolean_expr ? expr1 : expr2

If boolean_expr is true, the result is expr1;


otherwise, the result is expr2:
int val1 = 120, val2 = 0;
int highest;
highest = (val1 > val2) ? val1 : val2;
System.out.println("Highest value is " + highest);

4-21

Copyright 2004, Oracle. All rights reserved.

Using Logical Operators

Results of Boolean expressions can be combined by


using logical operators:
&&
||
^
!

&
|

and (with or without short-circuit evaluation)


or (with or without short-circuit evaluation)
exclusive or
not

int var0 = 0, var1 = 1, var2 = 2;


boolean res = true;
highest = (val1 > val2)? val1 : val2;
res = !res;

4-22

Copyright 2004, Oracle. All rights reserved.

Compound Assignment Operators

An assignment operator can be combined with any


conventional binary operator:
double total=0, num = 1;
double percentage = .50;

total = total + num;


// total is now 1
total += num;
// total is now 2
total -= num;
// total is now 1
total *= percentage;
// total is now .5
total /= 2;
// total is now 0.25
num %= percentage;
// num is now 0

4-23

Copyright 2004, Oracle. All rights reserved.

Operator Precedence
Order
1
2
3
4
5
6
7
8
9
10
11
12
13

4-24

Operators

Comments

++ -- + - ~
! (type)
* / %
+ - +
<< >> >>>
< > <= >=
instanceof
==
!=
&
^
|
&&
||
?:
= op=

Unary operators

Multiply, divide, remainder


Add, subtract, add string
Shift (>>> is zero-fill shift)
Relational, type compare

L
L
L
L

Equality
Bit/logical AND
Bit/logical exclusive OR
Bit/logical inclusive OR
Logical AND
Logical OR
Conditional operator
Assignment operators

L
L
L
L
L
L
R
R

Copyright 2004, Oracle. All rights reserved.

Assoc.

More on Operator Precedence

Operator precedence determines the order in


which operators are executed:
int var1 = 0;
var1 = 2 + 3 * 4;

Operators with the same precedence are executed


from left to right (see note in text below):
int var1 = 0;
var1 = 12 - 6 + 3;

4-25

// var1 now equals 14

// var1 now equals 9

Use parentheses to override the default order.


Copyright 2004, Oracle. All rights reserved.

Concatenating Strings

The + operator creates and concatenates strings:


String
String
String
name =

name = "Jane ";


lastName = "Hathaway";
fullName;
name + lastName;
// name is now
//"Jane Hathaway"
//
OR
name += lastName ;
// same result
fullName = name;

4-26

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


Java has eight primitive data types.
A variable must be declared before it can be used.
Java provides a comprehensive set of operators.
Explicit casting may be necessary if you use data
types smaller than int.
The + and += operators can be used to create and
concatenate strings.

4-27

Copyright 2004, Oracle. All rights reserved.

Practice 4: Overview

This practice covers:


Declaring and initializing variables
Using various operators to compute new values
Displaying results on the console

4-28

Copyright 2004, Oracle. All rights reserved.

Controlling Program Flow

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Use decision-making constructs
Perform loop operations
Write switch statements

5-2

Copyright 2004, Oracle. All rights reserved.

Categorizing Basic Flow Control Types

Flow control can be categorized into four types:

5-3

Sequential

Iteration

Selection

Transfer

Copyright 2004, Oracle. All rights reserved.

Using Flow Control in Java

Each simple statement terminates with a


semicolon (;).
Group statements by using the braces { }.
Each block executes as a single statement within
the flow of control structure.

boolean finished = true;


System.out.println("i = " + i);
i++;
}

5-4

Copyright 2004, Oracle. All rights reserved.

Using the if Statement

General:

Examples:

if ( boolean_expr )
statement1;
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");

if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}

5-5

Copyright 2004, Oracle. All rights reserved.

Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed >= 25 but <= 65");
else
System.out.println("Speed under 25");

if (speed > 65)


System.out.println("Speed over 65");
else if (speed >= 25)
System.out.println("Speed greater to 65");
else
System.out.println("Speed under 25");
5-6

Copyright 2004, Oracle. All rights reserved.

Guided Practice: Spot the Mistakes

5-7

int x = 3, y = 5;
if (x >= 0)
if (y < x)
System.out.println("y is less than x");
else
System.out.println("x is negative");

int x = 7;
if (x = 0)
System.out.println("x is zero");

int x = 14, y = 24;


if ( x % 2 == 0 && y % 2 == 0 );
System.out.println("x and y are even");

Copyright 2004, Oracle. All rights reserved.

Defining the switch Statement

switch ( integer_expr ) {
case constant_expr1:
statement1;
break;
case constant_expr2:
statement2;
break;
[default:
statement3;]
}

5-8

The switch
statement is useful
when selecting an
action from several
alternative integer
values.
Integer_expr must
be byte, int, char,
or short.

Copyright 2004, Oracle. All rights reserved.

More About the switch Statement

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;

5-9

Copyright 2004, Oracle. All rights reserved.

Looping in Java

There are three types of loops in Java:


while
dowhile
for

All loops have four parts:

5-10

Initialization
Iteration condition
Body
Termination

Copyright 2004, Oracle. All rights reserved.

Using the while Loop

while is the simplest loop statement and contains the


following general form:
while ( boolean_expr )
statement;

Example:

5-11

int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}

Copyright 2004, Oracle. All rights reserved.

Using the dowhile Loop

dowhile loops place the test at the end:


do
statement;
while ( termination );

Example:

int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 10);

5-12

Copyright 2004, Oracle. All rights reserved.

Using the for Loop

for loops are the most common loops:


for ( initialization; termination; iteration )
statement;

Example:
for (i = 0; i < 10; i++)
System.out.println(i);

How would this for loop look using a while loop?

5-13

Copyright 2004, Oracle. All rights reserved.

More About the for Loop

Variables can be declared in the initialization part


of a for loop:
for (int i = 0; i < 10; i++)
System.out.println("i = " + i);

Initialization and iteration can consist of a list of


comma-separated expressions:
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i);
System.out.println("j = " + j);
}

5-14

Copyright 2004, Oracle. All rights reserved.

Guided Practice: Spot the Mistakes

int x = 10;
while (x > 0);
System.out.println(x--);
System.out.println("We have lift off!");
int x = 10;
while (x > 0)
System.out.println("x is " + x);
x--;
int sum = 0;
for (; i < 10; sum += i++);
System.out.println("Sum is " + sum);

5-15

Copyright 2004, Oracle. All rights reserved.

The break Statement

Breaks out of a loop or switch statement


Transfers control to the first statement after the
loop body or switch statement

Can simplify code but must be used sparingly

while (age <= 65) {


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

5-16

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


The primary means of decision-making is the if
statement, with the optional else.
Java also offers the switch statement.
Java provides three loop statements: while,
dowhile, and for.
Use break and continue sparingly.

5-17

Copyright 2004, Oracle. All rights reserved.

Practice 5: Overview

This practice covers:


Performing tests by using ifelse statements

5-18

Using loops to perform iterative operations


Using the break statement to exit a loop
Using the &&, ||, and ! operators in Boolean
expressions

Copyright 2004, Oracle. All rights reserved.

Building Applications with


Oracle JDeveloper 10g

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Create new projects, workspaces, and
applications
Build Java applications in JDeveloper
Enhance user interface frame design
Debug an application by using JDeveloper
debugger
Define classes by using JDeveloper
Describe how JDeveloper can be used to build
enterprise applications

6-2

Copyright 2004, Oracle. All rights reserved.

What Is Oracle JDeveloper 10g?

6-3

Oracle JDeveloper 10g provides an integrated


development environment (IDE).
Build, compile, and run Java applications by using
Oracle JDeveloper.
Use wizards to help build source code.
View objects from many perspectives: code,
structure, layout, and so on.

Copyright 2004, Oracle. All rights reserved.

Exploring the JDeveloper Environment

Component Palette

System Navigator
6-4

Code Editor
Copyright 2004, Oracle. All rights reserved.

Property Inspector

Examining Workspaces

Contain multiple projects


Enable you to view
currently used objects
Workspace
Navigator
pane

Structure
pane

6-5

Copyright 2004, Oracle. All rights reserved.

What Are Projects?

Contain related
files
Manage project and
environment
Project
settings
Manage compiler
and debug options
Project
files

6-6

Copyright 2004, Oracle. All rights reserved.

Creating JDeveloper Items

JDeveloper items are


invoked by selecting
File > New.
They are categorized by
type:

6-7

General
Business Tier
Client Tier
Database Tier
Web Tier

Create any JDeveloper


element.
Copyright 2004, Oracle. All rights reserved.

Creating an Application Workspace

In the General
category, select
Application
Workspace to invoke
the Property pane.

6-8

Copyright 2004, Oracle. All rights reserved.

Specifying Project Details

6-9

Copyright 2004, Oracle. All rights reserved.

Selecting Additional Libraries

6-10

Copyright 2004, Oracle. All rights reserved.

Adding a New J2SE

New J2SE definitions include:


Java executable
A classpath
A source path
A doc path

6-11

Copyright 2004, Oracle. All rights reserved.

Looking at the Directory Structure

JDeveloper creates and stores .java and .class files


by using the following convention:
<ORACLE_HOME>\jdev\mywork

Followed by the workspace


name
Followed by the project name
\classes\<package name>\
\src\<package_name>\

6-12

Followed by class and src files

Copyright 2004, Oracle. All rights reserved.

Exploring the Skeleton Java Application


Contains application and frame classes

6-13

Copyright 2004, Oracle. All rights reserved.

Finding Methods and Fields


Find methods and fields by using the Structure pane.

6-14

Copyright 2004, Oracle. All rights reserved.

Supporting Code Development


with Profiler and Code Coach

Improve code quality with Code Coach.


Evaluate execution stack with Execution Sample
profiler.
Examine heap memory usage with Memory
profiler.
Analyze event occurrence and duration with Event
profiler for:
JVM events
Business Components for Java events
Custom events

6-15

Copyright 2004, Oracle. All rights reserved.

Customizing JDeveloper

Customize the IDE


Look and feel
General environment
Dockable windows
Component Palette
Load preset keymaps
Rename classes and packages by using refactoring.

6-16

Copyright 2004, Oracle. All rights reserved.

Using the Help System

6-17

Copyright 2004, Oracle. All rights reserved.

Obtaining Help on a Topic


Use [F1] to invoke
context-specific Help.

6-18

Copyright 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g Debugger

Helps find and fix program errors:


Run-time errors
Logic errors

6-19

Allows control of execution


Allows examination of variables

Copyright 2004, Oracle. All rights reserved.

Setting Breakpoints

Setting breakpoints:
Manage multiple breakpoints
Manage conditional breakpoints
Define columns displayed in window
Description
Type
Status, and so on

Control scope of action


Global > Workspace > Project

6-20

Copyright 2004, Oracle. All rights reserved.

Using the Debugger Windows

View Debug information:


Classes: Displays list of loaded classes and status
Watch: Evaluates and displays expressions
Monitors: Displays information about active
monitors
Threads: Displays the names and statuses of all
threads
Smart Data: Analyzes source code near execution
point
and more

6-21

Copyright 2004, Oracle. All rights reserved.

Stepping Through a Program

Step through a program by using the buttons on the


Debugger toolbar:
Start the debugger.
Resume the program.
Step over a method call.
Step into a method call.
Step out of a method call.
Step to the end of the method.
Pause execution.
Stop the debugger.

6-22

Copyright 2004, Oracle. All rights reserved.

Watching Data and Variables

The Smart Data tab displays analyzed variables


and fields.
The Data tab displays arguments, local variables,
and static fields from the current context.
To watch other variables:
Select a variable in the source window and rightclick.
Select Watch... at Cursor from the context menu.
View the variable in the Watch tab.
Right-click a data item to modify it.

6-23

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how:


JDeveloper builds, debugs, and runs all types of
Java applications
JDeveloper can be used to develop:

6-24

Java applications
Java servlets
JSPs
EJBs

JDeveloper can be used to build enterprise


applications

Copyright 2004, Oracle. All rights reserved.

Practice 6: Overview

This practice covers:


Exploring the Oracle JDeveloper 10g IDE
Creating a workspace and project
Including application files from the earlier lesson

6-25

Copyright 2004, Oracle. All rights reserved.

Creating Classes and Objects

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define instance variables and methods
Define the no-arg (default) constructor method
Instantiate classes and call instance methods
Perform encapsulation by using packages to
group related classes
Control access with public and private access
modifiers
Use class variables and methods

7-2

Copyright 2004, Oracle. All rights reserved.

Using Java Classes

Methods

Objects

Contained in a class

Attributes

7-3

Packages

Object
references

Copyright 2004, Oracle. All rights reserved.

Comparing Classes and Objects


Movie

An object is an
instance of a
class.
Objects have
their own
memory.
Class definitions
must be loaded
to create
instances.

mov1

7-4

public void displayDetails()


public void setRating()

title: Gone with


rating: PG

private String title;


private String rating;

title: Last Action


rating: PG-13

Copyright 2004, Oracle. All rights reserved.

mov2

Creating Objects

Objects are typically created by using the new


operator:
ClassName objectRef = new ClassName();

For example, to create two Movie objects:


Movie mov1 = new Movie("Gone ...");
Movie mov2 = new Movie("Last ...");

title: Gone with


rating: PG

7-5

title: Last Action


rating: PG-13

Copyright 2004, Oracle. All rights reserved.

Using the new Operator

The new operator performs the following actions:

Allocates and initializes memory for the new


object
Calls a special initialization method in the class,
called a constructor
Returns a reference to the new object

Movie mov1 = new Movie("Gone with");

mov1
(When instantiated)

7-6

title: Gone with


rating: PG

Copyright 2004, Oracle. All rights reserved.

Comparing Primitives and Objects

Primitive variables
hold a value.
int i;

Object variables
hold references.
Movie mov1;
mov1

0
null
Movie mov1 = new Movie();

int j = 3;
j

7-7

mov1
title: null
rating: null

Copyright 2004, Oracle. All rights reserved.

Using the null Reference

A special null value may be assigned to an object


reference, but not to a primitive.
You can compare object references to null.
You can remove the association to an object by
setting the object reference to null.
Movie mov1;

if (mov1 == null)
mov1 = new Movie();

mov1 = null;

7-8

//Declare object reference


//Ref not initialized?
//Create a Movie object
//Forget the Movie object

Copyright 2004, Oracle. All rights reserved.

Assigning References

Assigning one reference to another results in two


references to the same object:
Movie mov1 = new Movie("Gone...");
mov1

Movie mov2 = mov1;

title: Gone with


rating: PG

mov2

7-9

Copyright 2004, Oracle. All rights reserved.

Declaring Instance Variables


Instance variables are declared within the class, but
outside the methods or instance or static intializers.
public class Movie {
public String title;
public String rating;
public float getPrice(){
return price;
}
}

mov1
title: null
rating: null
mov2

Create movies:

title: null
rating: null

Movie mov1 = new Movie();


Movie mov2 = new Movie();
7-10

Copyright 2004, Oracle. All rights reserved.

Accessing public Instance Variables

public instance variables can be accessed by using


the dot operator:
public class Movie {
public String title;
public String rating;

Movie mov1 = new Movie();


}
mov1.title = "Gone ...";

if (mov1.title.equals("Gone ... ") )


mov1.rating = "PG";

7-11

Copyright 2004, Oracle. All rights reserved.

Defining Methods

A method in Java is equivalent to a function or


subroutine in other languages.

modifier returnType methodName (argumentList) {


// method body

};

7-12

Copyright 2004, Oracle. All rights reserved.

Calling a Method

Objects communicate by using messages:


All methods are defined within a class and are not
defined globally as in traditional languages.
When you call a method, it is always in the context
of a particular object.
myPen.write( ): Object-oriented programming
Write (myPen): Traditional structured
programming

7-13

Copyright 2004, Oracle. All rights reserved.

Specifying Method Arguments: Examples

Specify the number and type of arguments in the


method definition:
public void setRating(String newRating) {
rating = newRating;
}

If the method takes no arguments, then leave the


parentheses empty:
public void displayDetails() {
System.out.println("Title is " + title);
System.out.println("Rating is " + rating);
}

7-14

Copyright 2004, Oracle. All rights reserved.

Returning a Value from a Method

Use a return statement to exit a method and to


return a value from a method:
public class Movie {
private String rating;

public String getRating () {


return rating
}
}

7-15

If the return type is void, then no return is needed.


You can use a return without a value to terminate
a method with a void return type.

Copyright 2004, Oracle. All rights reserved.

Calling Instance Methods

public class Movie {


private String title, rating;
public String getRating(){
return rating;
}
public void setRating(String newRating){
rating = newRating;
}
Movie mov1 = new Movie();
}
String r = mov1.getRating();
if (r.equals("G"))
Use the dot

operator:

7-16

Copyright 2004, Oracle. All rights reserved.

Applying Encapsulation in Java

Instance variables must be


declared as private.

Only instance methods can access


private instance variables.
private decouples the interface
of the class from its internal operation.

var
aMethod

aMethod()

Movie mov1 = new Movie();


String rating = mov1.getRating();
String r = mov1.rating; // error: private
...
if (rating.equals("G"))

7-17

Copyright 2004, Oracle. All rights reserved.

Passing Primitives into Methods

When a primitive or object reference value is passed


into a method, a copy of the value is generated:
int num = 150;

num
150

anObj.aMethod(num);
System.out.println("num: " + num);
public void aMethod(int arg) {
arg
if (arg < 0 || arg > 100)
150
arg = 0;
System.out.println("arg: " + arg);
}

7-18

Copyright 2004, Oracle. All rights reserved.

Passing Object References into Methods

When an object reference is passed into a method, the


object is not copied but the pointer to the object is
copied:
Movie mov1 =
new Movie("Gone");
mov1.setRating("PG");
anObj.aMethod(mov1);

mov1
title: Gone with
rating: PG

ref2
public void aMethod(Movie ref2) {
ref2.setRating("R");
}

7-19

Copyright 2004, Oracle. All rights reserved.

What Are Class Variables?

Class variables:
Belong to a class and are common to all instances
of that class
Are declared as static in class definitions
public class Movie {
private static double minPrice;
private String title, rating;
title
rating
min
Price
Movie class variable
7-20

// class var
// inst vars

title
rating

Movie objects

Copyright 2004, Oracle. All rights reserved.

title
rating

Initializing Class Variables

Class variables can be initialized at declaration.


Initialization takes place when the class is loaded.
Use a static initializer block for complex
initialization.
All class variables are initialized implicitly to
default values depending on data type.
public class Movie {
private static double minPrice = 1.29;
private String title, rating;
private int length = 0;

7-21

Copyright 2004, Oracle. All rights reserved.

What Are Class Methods?

Class methods are:


Shared by all instances
Useful for manipulating class variables
Declared as static
public static void increaseMinPrice(double inc) {
minPrice += inc;
}

A class method is called by using the name of the


class or an object reference.
Movie.increaseMinPrice(.50);
mov1.increaseMinPrice(.50);

7-22

Copyright 2004, Oracle. All rights reserved.

Guided Practice: Class Methods


or Instance Methods
public class Movie {
private static float price = 3.50f;
private String rating;

public static void setPrice(float newPrice) {


price = newPrice;
}
public String getRating() {
return String;
Movie.setPrice(3.98f); Movie
}
mov1 = new Movie();
}
mov1.setPrice(3.98f);
String a = Movie.getRating();
Legal or not?
String b = mov1.getRating();

7-23

Copyright 2004, Oracle. All rights reserved.

Examples in Java

Examples of static methods and variables:

main()

Math.sqrt()

System.out.println()
public class MyClass {
public static void main(String[] args) {
double num, root;

root = Math.sqrt(num);
System.out.println("Root is " + root);
}

7-24

Copyright 2004, Oracle. All rights reserved.

Creating Classes Using the Class Editor

7-25

Copyright 2004, Oracle. All rights reserved.

What Are Java Packages?


oe

Customer Order

Util

OrderEntry OrderItem

7-26

Copyright 2004, Oracle. All rights reserved.

Grouping Classes in a Package

Include the package keyword followed by the


package name at the top of the Java source file.
Use the dot notation to show the package path.
If you omit the package keyword, then the
compiler places the class in a default unnamed
package.
Use the d flag with the javac compiler to create
the package tree structure relative to the specified
directory.
Running a main() method in a packaged class
requires:
That the CLASSPATH contains the directory having
the root name of the package tree
That the class name must be qualified by its
package name

7-27

Copyright 2004, Oracle. All rights reserved.

Setting the CLASSPATH with Packages

The CLASSPATH includes the directory containing the


top level of the package tree:
.class location

Package name

CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06

7-28

Copyright 2004, Oracle. All rights reserved.

Access Modifiers

acmevideo

public

public

protected

private

7-29

Copyright 2004, Oracle. All rights reserved.

acmetools

Summary

In this lesson, you should have learned the following:


A class definition specifies a template for building
objects with identical features, such as instance
variables and methods.
An object is an instance of a particular class.
Create an object by using new.
Manipulate an object by using its public instance
methods.

7-30

Copyright 2004, Oracle. All rights reserved.

Practice 7: Overview

This practice covers:


Defining new classes
Specifying the classes instance variables and
instance methods
Creating Customer objects in main()
Manipulating Customer objects by using public
instance methods

7-31

Copyright 2004, Oracle. All rights reserved.

Object Life Cycle and Inner Classes

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Provide two or more methods with the same name
in a class
Provide one or more constructors for a class
Use initializers to initialize both instance and class
variables
Describe the class loading and initializing
process, and the object life cycle
Define and use inner classes

8-2

Copyright 2004, Oracle. All rights reserved.

Overloading Methods

Several methods in a class can have the same


name.
The methods must have different signatures.
public class Movie {
public void setPrice() {
price = 3.50F;
}
public void setPrice(float newPrice) {
price = newPrice;
Movie mov1 = new Movie();
}
mov1.setPrice();
}
mov1.setPrice(3.25F);

8-3

Copyright 2004, Oracle. All rights reserved.

Using the this Reference

Instance methods receive an argument called this,


which refers to the current object.
public class Movie {
public void setRating(String newRating) {
this.rating = newRating; this
}

void anyMethod() {
Movie mov1 = new Movie();
Movie mov2 = new Movie();
mov1.setRating("PG");

8-4

title : null
rating: PG
mov1

mov2

Copyright 2004, Oracle. All rights reserved.

title: null
rating: null

Initializing Instance Variables

Instance variables can be explicitly initialized at


declaration.
Initialization happens at object creation.
public class Movie {
private String title;
private String rating = "G";
private int numOfOscars = 0;

8-5

All instance variables are initialized implicitly to


default values depending on data type.
More complex initialization must be placed in a
constructor.

Copyright 2004, Oracle. All rights reserved.

What Are Constructors?

For proper initialization, a class must provide a


constructor.
A constructor is called automatically when an
object is created:
It is usually declared public.
It has the same name as the class.
It must not specify a return type.

The compiler supplies a no-arg constructor if and


only if a constructor is not explicitly provided.
If any constructor is explicitly provided, then the
compiler does not generate the no-arg constructor.

8-6

Copyright 2004, Oracle. All rights reserved.

Defining and Overloading Constructors

public class Movie {


private String title;
private String rating = "PG";
public Movie() {
The Movie class
now provides two
title = "Last Action ";
constructors.
}
public Movie(String newTitle) {
title = newTitle;
}
Movie mov1 = new Movie();
}

8-7

Movie mov2 = new Movie("Gone ");


Movie mov3 = new Movie("The Good ");

Copyright 2004, Oracle. All rights reserved.

Sharing Code Between Constructors


Movie mov2 = new Movie();
A constructor
can call another
constructor by
using this().

public class Movie {


private String title;
private String rating;
public Movie() {
this("G");
}
public Movie(String newRating) {
rating = newRating;
}

What happens
here?
}

8-8

Copyright 2004, Oracle. All rights reserved.

final Variables, Methods, and Classes

A final variable is a constant and cannot be


modified.
It must therefore be initialized.
It is often declared public static for external
use.

A final method cannot be overridden by a


subclass.
A final class cannot be subclassed.

public final class Color {


public final static Color black=new Color(0,0,0);

8-9

Copyright 2004, Oracle. All rights reserved.

Reclaiming Memory

8-10

When all references to an object are lost, the


object is marked for garbage collection.
Garbage collection reclaims memory that is used
by the object.
Garbage collection is automatic.
There is no need for the programmer to do
anything, but the programmer can give a hint to
System.gc();.

Copyright 2004, Oracle. All rights reserved.

Using the finalize() Method

If an object holds a resource such as a file, then


the object should be able to clean it up.
You can provide a finalize() method in that
class.
The finalize() method is called just before
garbage collection.
public class Movie {

public void finalize() {


System.out.println("Goodbye");
}
}

8-11

Copyright 2004, Oracle. All rights reserved.

Any problems?

What Are Inner Classes?

Inner classes are nested classes, defined in a


class or method.
They enforce a relationship between two classes.
They are of four types:

Static
Member
Local
Anonymous

public class Outer {


class Inner {
}
}
Enclosing class

8-12

Copyright 2004, Oracle. All rights reserved.

Using Member Inner Class

It is declared within another class.


Nesting is allowed.
It can access variables within its own class and
any enclosing classes.
It can only declare final static methods.
public class CalendarPopup {
...
class MonthSelector {
class DayOfMonth{...};
DayOfMonth[] NumberOfDaysInMonth
...
}
}

8-13

Copyright 2004, Oracle. All rights reserved.

Using Local Inner Class

It is declared within a code block (inside a


method).
All final variables or parameters declared in the
block are accessible by the methods of the inner
class.
public class CalendarPopup {
...
public void handlerMethod(){
class DateHandler{};
DateHandler sc = new DateHandler();
...
}
}

8-14

Copyright 2004, Oracle. All rights reserved.

Defining Anonymous Inner Classes

They are defined at method level.


They are declared within a code block.
They lack the class, extends, and implements
keywords.
They cannot have a constructor.
public class Outer {
...
public void outerMethod(){
...
myObject.myAnonymous(new SomeOtherClass(){
...
} )
}
}

8-15

Copyright 2004, Oracle. All rights reserved.

Using the Calendar Class

It converts between a date object and a set of


integer fields.
It represents a specific moment in time.
Subclasses interpret a date according to the
specific calendar system.
public class Order {
...
public void String getShipDate(){
...
Calendar c = Calendar.getInstance();
c.setTime(orderDate);
...
}
}

8-16

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


Methods can be overloaded in Java.
Instance methods receive a this reference to the
current object.
Most classes provide one or more constructors to
initialize new objects.
Class variables and class methods can be defined
for classwide properties and behaviors.
Classes can be defined in various ways within a
class.

8-17

Copyright 2004, Oracle. All rights reserved.

Practice 8: Overview

This practice covers:


Defining and using overloaded methods
Providing a no-arg constructor for a class
Providing additional constructors for a class
Defining static variables and static methods for
classwide behavior
Using static methods

8-18

Copyright 2004, Oracle. All rights reserved.

Using Strings, String Buffer, Wrapper,


and Text-Formatting Classes

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Create strings in Java
Use the conversion methods that are provided by
the predefined wrapper classes
Use the StringBuffer class for manipulating
character data
Introduce the DateFormat, DecimalFormat, and
MessageFormat classes

9-2

Examine standard output and serialization

Copyright 2004, Oracle. All rights reserved.

What Is a String?

9-3

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.

Copyright 2004, Oracle. All rights reserved.

Creating a String

Assign a double-quoted constant to a String


variable:
String category = "Action";

Concatenate other strings:


String empName = firstName + " " + lastName;

Use a constructor:
String empName = new String(Bob Smith");

9-4

Copyright 2004, Oracle. All rights reserved.

Concatenating Strings

Use the + operator to concatenate strings.


System.out.println("Name = " + empName);

You can concatenate primitives and strings.


int age = getAge();
System.out.println("Age = " + age);

9-5

The String class has a concat() instance


method that can be used to concatenate strings.

Copyright 2004, Oracle. All rights reserved.

Performing Operations on Strings

Find the length of a string:


int length();

String str = "Comedy";


int len = str.length();

Find the character at a specific index:


char charAt(int index);

Return a substring of a string:


String substring
(int beginIndex,
int endIndex);

9-6

String str = "Comedy";


char c = str.charAt(1);

String str = "Comedy";


String sub =
str.substring(2,4);

Copyright 2004, Oracle. All rights reserved.

Performing More Operations on Strings

Convert to uppercase or lowercase:

String toUpperCase();
String toLowerCase();

Trim whitespace:
String nospaces =
str.trim();

String trim();

Find the index of a substring:

int indexOf (String str);


int lastIndexOf
(String str);
9-7

String caps =
str.toUpperCase();

int index =
str.indexOf("me");

Copyright 2004, Oracle. All rights reserved.

Comparing String Objects

Use equals()if you want case to count:

String passwd = connection.getPassword();


if (passwd.equals("fgHPUw")) // Case is important

Use equalsIgnoreCase()if you want to ignore


case:

String cat = getCategory();


if (cat.equalsIgnoreCase("Drama"))
// We just want the word to match

9-8

Do not use ==.

Copyright 2004, Oracle. All rights reserved.

Producing Strings from Other Objects

Use the Object.toString() method.


Your class can override toString().
public Class Movie {
public String toString () {
return name + " (" + Year + ")";
}

System.out.println() automatically calls an


objects toString() method if a reference is
passed to it.
Movie mov = new Movie();
System.out.println(mov);

9-9

Copyright 2004, Oracle. All rights reserved.

Producing Strings from Primitives

Use String.valueOf():
String seven = String.valueOf(7);
String onePoint0 = String.valueOf(1.0f);

There is a version of System.out.println()for


each primitive type:
int count;

System.out.println(count);

9-10

Copyright 2004, Oracle. All rights reserved.

Producing Primitives from Strings

Use the primitive wrapper classes.


There is one wrapper class for each primitive type:

Integer wraps the int type.


Float wraps the float type.
Character wraps the char type.
Boolean wraps the boolean type.

And so on

9-11

Wrapper classes provide methods to convert a


String to a primitive, and primitives to a String.

Copyright 2004, Oracle. All rights reserved.

Wrapper Class Conversion Methods

Example: Use the methods to process data from fields


as they are declared.
String qtyVal = "17";
String priceVal = "425.00";
int qty = Integer.parseInt(qtyVal);
float price = Float.parseFloat(priceVal);
float itemTotal = qty * price;

9-12

Copyright 2004, Oracle. All rights reserved.

Changing the Contents of a String

Use the StringBuffer class for modifiable


strings of characters:
public String reverseIt(String s) {
StringBuffer sb = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--)
sb.append(s.charAt(i));
return sb.toString();
}

Use StringBuffer if you need to keep adding


characters to a string.
Note: StringBuffer has a reverse() method.

9-13

Copyright 2004, Oracle. All rights reserved.

Formatting Classes

The java.text package contains:


An abstract class called Format with the format
() method shown in the following example:
public abstract class Format {
public final String format(Object obj){
//Formats an object and produces a string.
}

Classes that format locale-sensitive information


such as dates, numbers, and messages
DateFormat, NumberFormat, and MessageFormat

9-14

Copyright 2004, Oracle. All rights reserved.

Using the SimpleDateFormat Class

The SimpleDateFormat:

Is a concrete class for formatting and parsing


dates in a locale-sensitive manner
Allows you to start by choosing any user-defined
patterns for datetime formatting
Uses time-pattern string to display the date:
y
M
m

9-15

year
month in year
minute in hour

1996
July or 07
30

Copyright 2004, Oracle. All rights reserved.

Using the MessageFormat Class

The MessageFormat:

9-16

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

Copyright 2004, Oracle. All rights reserved.

Using DecimalFormat

The DecimalFormat:
Is a concrete subclass of NumberFormat for
formatting decimal numbers
Allows for a variety of parameters and for
localization to Western, Arabic, or Indic numbers
Uses standard number notation in format
public DecimalFormat(String pattern);

9-17

Copyright 2004, Oracle. All rights reserved.

Guided Practice

1. What is the output of each code fragment?


a.
String s = new String("Friday");
if(s == "Friday")
System.out.println("Equal A");
if(s.equals("Friday"))
System.out.println("Equal B");

b.
int num = 1234567;
System.out.println(String.valueOf(num).charAt(3));

9-18

Copyright 2004, Oracle. All rights reserved.

Guided Practice

2. What is the output of each code fragment?


a.
String s1 = "Monday";
String s2 = "Tuesday";
System.out.println(s1.concat(s2).substring(4,8));

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"));

9-19

Copyright 2004, Oracle. All rights reserved.

Using Regular Expressions

Matches character sequences against patterns


specified by regular expressions
Includes a Matcher class which is the engine that
performs match operations
Employs a Pattern class to provide a compiled
representation of a regular expression
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

9-20

Copyright 2004, Oracle. All rights reserved.

About System.out.println

Understanding System.out.println()
System is a class in the java.lang package.
out is a public final static (class) variable.
Declared as a PrintStream object reference

println() is an overloaded method of the


PrintStream class.
PrintStream is a FilterOutputStream that
subclasses OutputStream.

9-21

System.err is also provided as a PrintStream


object reference to write to standard error.

Copyright 2004, Oracle. All rights reserved.

About OutputStream and PrintStream

OutputStream provides basic byte I/O operations:


write(int b) to write one byte
write(byte[] b) to write an array of bytes
write(byte[] b,int off,int len) to write a
subset of an array of bytes
flush() and close() to flush and close the stream

PrintStream is a subclass of (Filter)Output


Stream, which
Converts Unicode to environment byte encoding
Terminates lines in a platform-independent way
Flushes the output stream

9-22

Copyright 2004, Oracle. All rights reserved.

What Is Object Serialization?

Serialization is a lightweight persistence mechanism


for saving and restoring streams of bytes containing
primitives and objects.
A class indicates that its instances can be
serialized by:
Implementing java.io.Serializable or
java.io.Externalizable interface
Ensuring that all its fields are serializable, including
other objects referenced
Using the transient modifier to prevent fields
from being saved and restored

9-23

Copyright 2004, Oracle. All rights reserved.

Serialization Streams, Interfaces,


and Modifiers

Example of implementing java.io.Serializable


Mark fields with the transient modifier to prevent
them from being saved; that is, to protect the
information.

import java.io.Serializable;
public class Member implements Serializable {
private int id;
private String name;
private transient String password;

9-24

Write object with java.io.ObjectOutputStream.


Read object with java.io.ObjectInputStream.
Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create strings in Java
Use the conversion methods that are provided by
the predefined wrapper classes
Use the StringBuffer class for manipulating
character data
Manipulate objects by using the DateFormat,
DecimalFormat, and MessageFormat classes

9-25

Copyright 2004, Oracle. All rights reserved.

Practice 9: Overview

This practice covers:


Creating a new Order class
Populating and formatting orderDate
Formatting existing orderDate values with the
GregorianCalendar class
Formatting orderTotal

9-26

Copyright 2004, Oracle. All rights reserved.

Reusing Code with Inheritance


and Polymorphism

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define inheritance
Use inheritance to define new classes
Provide suitable constructors
Override methods in the superclass
Describe polymorphism
Use polymorphism effectively

10-2

Copyright 2004, Oracle. All rights reserved.

Key Object-Oriented Components

Inheritance
Constructors referenced by subclass
Polymorphism
Inheritance as an OO fundamental

Superclass
InventoryItem
Subclasses
Movie

10-3

Game

Copyright 2004, Oracle. All rights reserved.

Vcr

Example of Inheritance

The InventoryItem class defines methods and


variables.
InventoryItem

Movie

Movie extends InventoryItem and can:


Add new variables
Add new methods
Override methods in InventoryItem class

10-4

Copyright 2004, Oracle. All rights reserved.

Specifying Inheritance in Java

Inheritance is achieved by specifying which


superclass the subclass extends.
public class InventoryItem {

}
public class Movie extends InventoryItem {

10-5

Movie inherits all the variables and methods of


InventoryItem.
If the extends keyword is missing, then the
java.lang.Object is the implicit superclass.
Copyright 2004, Oracle. All rights reserved.

Defining Inheritance
by Using Oracle JDeveloper 10g

10-6

When specifying a class, JDeveloper asks for its


superclass:

JDeveloper generates the code automatically.


Copyright 2004, Oracle. All rights reserved.

What Does a Subclass Object


Look Like?
A subclass inherits all the instance variables of its
superclass.
public class InventoryItem {
private float price;
private String condition;
}
public class
Movie extends InventoryItem {
private String title;
private int length;
}

10-7

Copyright 2004, Oracle. All rights reserved.

Movie
price
condition

title
length

Default Initialization

What happens when a subclass


object is created?
Movie movie1 = new Movie();

If no constructors are defined:


First, the default no-arg
constructor is called in the
superclass.
Then, the default no-arg
constructor is called in the
subclass.

10-8

Copyright 2004, Oracle. All rights reserved.

Movie
price
condition

title
length

The super Reference

10-9

Refers to the base, top-level class


Is useful for calling base class constructors
Must be the first line in the derived class
constructor
Can be used to call any base class methods

Copyright 2004, Oracle. All rights reserved.

The super Reference Example


public class InventoryItem {
InventoryItem(String cond) {
System.out.println("InventoryItem");

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

System.out.println("Movie");
}
}

10-10

Copyright 2004, Oracle. All rights reserved.

Base class
constructor

Calls base
class
constructor

Using Superclass Constructors

Use super() to call a superclass constructor:

public class InventoryItem {


InventoryItem(float p, String cond) {
price = p;
condition = cond;
}
public class Movie extends InventoryItem {
Movie(String t, float p, String cond) {
super(p, cond);
title = t;
}

10-11

Copyright 2004, Oracle. All rights reserved.

Specifying Additional Methods

The superclass defines methods for all types of


InventoryItem.

The subclass can specify additional methods that


are specific to Movie.
public class InventoryItem {
public float calcDeposit()
public String calcDateDue()

public class Movie extends InventoryItem {


public void getTitle()
public String getLength()

10-12

Copyright 2004, Oracle. All rights reserved.

Overriding Superclass Methods

A subclass inherits all the methods of its


superclass.
The subclass can override a method with its own
specialized version.
The subclass method must have the same signature
and semantics as the superclass method.

public class InventoryItem {


public float calcDeposit(int custId) {
if
public class Vcr extends InventoryItem {
return itemDeposit;
public float calcDeposit(int custId) {
}
if
return itemDeposit;
}
10-13

Copyright 2004, Oracle. All rights reserved.

Invoking Superclass Methods

If a subclass overrides a method, then it can still


call the original superclass method.
Use super.method() to call a superclass method
from the subclass.

public class InventoryItem {


public float calcDeposit(int custId) {
if public class Vcr extends InventoryItem {
return
33.00;
public
float calcDeposit(int custId) {
}
itemDeposit = super.calcDeposit(custId);
return (itemDeposit + vcrDeposit);
}

10-14

Copyright 2004, Oracle. All rights reserved.

Example of Polymorphism in Java

Recall that the java.lang.Object class is the root


class for all Java Class.
Methods in the Object class are inherited by its
subclasses.
The toString() method is most commonly
overridden to achieve polymorphic behavior.
For example: public class InventoryItem {
public String toString() {
return "InventoryItem value";
}
} = new InventoryItem();
InventoryItem item
System.out.println(item); // toString() called
10-15

Copyright 2004, Oracle. All rights reserved.

Treating a Subclass as Its Superclass

A Java object instance of a subclass is assignable to


its superclass definition.
You can assign a subclass object to a reference
that is declared with the superclass.
public static void main(String[] args) {
InventoryItem item = new Vcr();
double deposit = item.calcDeposit();
}

10-16

The compiler treats the object via its reference


(that is, in terms of its superclass definition).
The JVM run-time environment creates a subclass
object, executing subclass methods, if overridden.
Copyright 2004, Oracle. All rights reserved.

Browsing Superclass References


by Using Oracle JDeveloper 10g

Oracle JDeveloper makes it


easy to browse the contents
of your superclass.

10-17

Copyright 2004, Oracle. All rights reserved.

Acme Video and Polymorphism

10-18

Acme Video started renting only videos.


Acme Video added games and Vcrs.
What is next?
Polymorphism solves the problem.

Copyright 2004, Oracle. All rights reserved.

Using Polymorphism for Acme Video


InventoryItem
calcDeposit(){}
Vcr
calcDeposit(){}

Movie
calcDeposit(){}

ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();

10-19

Copyright 2004, Oracle. All rights reserved.

Using the instanceof Operator

You can determine the true type of an object by


using an instanceof operator.

An object reference can be downcast to the


correct type, if necessary.

public void aMethod(InventoryItem i) {

if (i instanceof Vcr)
((Vcr)i).playTestTape();
}

10-20

Copyright 2004, Oracle. All rights reserved.

Limiting Methods and Classes with final

You can mark a method as final to prevent it


from being overridden.
public final boolean checkPassword(String p) {

You can mark a whole class as final to prevent it


from being extended.
public final class Color {

10-21

Copyright 2004, Oracle. All rights reserved.

Ensuring Genuine Inheritance

Inheritance must be used only for genuine is a


kind of relationships:
It must always be possible to substitute a subclass
object for a superclass object.
All methods in the superclass must make sense in
the subclass.

10-22

Inheritance for short-term convenience leads to


problems in the future.

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


A subclass inherits all the variables and methods
of its superclass.
You can specify additional variables and methods
and override methods.
A subclass can call an overridden superclass
method by using super.

10-23

Polymorphism ensures that the correct version of


a method is called at run time.

Copyright 2004, Oracle. All rights reserved.

Practice 10: Overview

This practice covers:


Defining subclasses of Customer

10-24

Providing subclass constructors


Adding new methods in the subclasses
Overriding existing superclass methods

Copyright 2004, Oracle. All rights reserved.

Using Arrays and Collections

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe how to create arrays of primitives and
objects
Process command-line variables
Work with vectors
Explore other Java collections such as
Enumerators, Iterators, ArrayLists, and
Hashtables

11-2

Process command-line and system properties

Copyright 2004, Oracle. All rights reserved.

What Is an Array?

An array is a collection of variables of the same type.


Each element can hold a single item.
Items can be primitives or object references.
The length of the array is fixed when it is created.

[0]
[1]
[2]
[3]
11-3

[0]

Action

[1]

Comedy

[2]

Drama

2
4
8

Copyright 2004, Oracle. All rights reserved.

Creating an Array of Primitives

1. Declare the array:


type[] arrayName;
or
type arrayName[];

Null
arrayName

0
arrayName
0

type is a primitive, such as int and so on.

2. Create the array object:


// Create array object syntax
arrayName
arrayName = new type[size];

3. Initialize the array elements


(optional).
11-4

Copyright 2004, Oracle. All rights reserved.

1
2
4

Declaring an Array of Primitives

Create a variable to reference the array object:


int[] powers;

// Example

When an array variable is declared:


Its instance variable is initialized to null until the
array object has been created
powers

null

Its method variable is unknown until the object is


created

11-5

Copyright 2004, Oracle. All rights reserved.

Creating an Array Object for


an Array of Primitives

Create an array of the required length and assign


it to the array variable:
int[] powers;
// Declare array variable
powers = new int[4]; //Create array object

The array object is created by using the new


operator.

11-6

The contents of an array of primitives are


initialized automatically.
powers

Copyright 2004, Oracle. All rights reserved.

0
0
0
0

Initializing Array Elements

Assign values to individual elements:


arrayName[index] = value;
powers
powers[0] = 1;

Create and initialize arrays at


the same time:
type[] arrayName = {valueList};
int[] primes = {2, 3, 5, 7};

11-7

1
0
0
0

[0]
3 [1]
5 [2]
7 [3]
2

primes

Copyright 2004, Oracle. All rights reserved.

[0]
[1]
[2]
[3]

Creating an Array of Object References


arrVar

1. Declare the array:


ClassName[] arrVar;
or
ClassName arrVar[];

null
arrVar

null
null
null

2. Create the array object:

arrVar
Action

// Create array object syntax


arrVar = new ClassName[size];

3. Initialize the objects in the array.


11-8

Copyright 2004, Oracle. All rights reserved.

Comedy
Drama

Initializing the Objects in the Array

Assign a value to each array element:


// Create an array of four empty Strings
String[] arr = new String[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = new String();
}

Create and initialize the array at the same time:


String[] categories =
{"Action", "Comedy", "Drama"};

11-9

Copyright 2004, Oracle. All rights reserved.

Using an Array of Object References

Any element can be assigned to an object of the


correct type:
String category = categories[0];

Each element can be treated as an individual


object:
System.out.println
("Length is " + categories[2].length());

11-10

An array element can be passed to any method;


array elements are passed by reference.

Copyright 2004, Oracle. All rights reserved.

Arrays and Exceptions

ArrayIndexOutOfBoundsException occurs
when an array index is invalid:

String[] list = new String[4];


//The following throws ArrayIndexOutOfBoundsException
System.out.println(list[4]);

NullPointerException occurs when you try to


access an element that has not been initialized:

Movie[] movieList = new Movie[3];


// The following will throw NullPointerException
String director = movieList[0].getDirector();

11-11

Copyright 2004, Oracle. All rights reserved.

Multidimensional Arrays

Java supports arrays of arrays:


type[][] arrayname = new type[n1][n2];
int[][] mdarr = new int[4][2];
mdarr[0][0] = 1;
mdarr[0][1] = 7;
mdarr

[0][0]

[0][1]

[1]

[2]

[3]

[0]

11-12

Copyright 2004, Oracle. All rights reserved.

main() Revisited

main() has a single parameter, args.


args is an array of Strings that holds commandline parameters:
C:\> java SayHello Hello World
public class SayHello {
public static void main(String[] args) {
if (args.length != 2)
System.out.println("Specify 2 arguments");
else
System.out.println(args[0]+" "+args[1]);
}

11-13

Copyright 2004, Oracle. All rights reserved.

Working with Variable-Length Structures

The Vector class implements a resizable array of


any type of object:
Creating an empty vector:
Vector members = new Vector();

Creating a vector with an initial size:


// Create a vector with 10 elements. The vector //
can be expanded later.
Vector members = new Vector(10);

11-14

Copyright 2004, Oracle. All rights reserved.

Modifying a Vector

Add an element to the end of the vector:


String name = MyMovie.getNextName();
members.addElement(name);

Add an element at a specific position:


// Insert a string at the beginning
members.insertElementAt(name, 0);

Remove the element at a specific index:


// Remove the first element
members.removeElementAt(0);

11-15

Copyright 2004, Oracle. All rights reserved.

Accessing a Vector

Get the first element:


String s = (String)members.firstElement();

Get an element at a specific position:


String s = (String)members.elementAt(2);

Find an object in a vector:


int position = members.indexOf(name);

Get the size of a vector:


int size = members.size();

11-16

Copyright 2004, Oracle. All rights reserved.

Java Collections Framework

Java Collections Framework is an API architecture for


managing a group of objects that can be manipulated
independently of their internal implementation. It is:
Found in the java.util package
Defined by six core interfaces and some
implementation classes:

Collection interface: Generic group of elements


Set interface: Group of unique elements
List interface: Ordered group of elements
Map interface: Group of unique keys and their
values
SortedSet and SortedMap for a sorted Set and
Map

11-17

Copyright 2004, Oracle. All rights reserved.

Collections Framework Components

Collections Framework is a set of interfaces and


classes used to store and manipulate groups of data
as a single unit.
Core Interfaces are the interfaces used to
manipulate collections, and to pass them from one
method to another.
Implementations are the actual data objects used
to store collections, which implement the core
collection interface.
Algorithms are pieces of reusable functionality
provided by the JDK.

11-18

Copyright 2004, Oracle. All rights reserved.

Using ArrayList and Hashtable

The ArrayList class:


Is a resizable implementation of the List interface

Allows manipulation of the array size


Has capacity that grows as elements are added to
the list
The Hashtable class:
Is a legacy class similar to Map implementations

11-19

Is used to store arbitrary objects that are indexed


by another arbitrary object
Is commonly used with String as the key to store
objects as values
Copyright 2004, Oracle. All rights reserved.

Using Iterators

The Iterator interface, which is part of Java


Collection Framework, can be used to process a series
of Objects. The java.util.Iterator interface:

Implements an object-oriented approach for


accessing elements in a collection
Replaces the java.util.Enumeration approach

Contains the following methods:


hasNext() returns true if more elements exist.
next() returns the next Object, if any.
remove() removes the last element returned.

11-20

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Create Java arrays of primitives
Create arrays of object references
Initialize arrays of primitives or object references
Process command-line arguments in the main()
method
Use the Vector object to implement resizable
arrays
Use ArrayList and Hashtable classes

11-21

Copyright 2004, Oracle. All rights reserved.

Practice 11: Overview

This practice covers:


Modifying the DataMan class
Create an array to hold the Customer, Company, and
Individual objects.
Add a method to ensure that the array is
successfully created and initialized.
Add a method to find a customer by an ID value.

11-22

Copyright 2004, Oracle. All rights reserved.

Structuring Code by Using


Abstract Classes and Interfaces

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define abstract classes
Define abstract methods
Define interfaces
Implement interfaces

12-2

Copyright 2004, Oracle. All rights reserved.

Defining Abstract Classes

An abstract class cannot be instantiated.


Abstract methods must be implemented by
subclasses.
Interfaces support multiple inheritance.

Abstract
superclass

InventoryItem

Concrete
subclasses

12-3

Movie

Copyright 2004, Oracle. All rights reserved.

VCR

Creating Abstract Classes

Use the abstract keyword to declare a class as


abstract.
public abstract class InventoryItem {
private float price;
public boolean isRentable()
}

public class Movie


extends InventoryItem {
private String title;
public int getLength()

12-4

public class Vcr


extends InventoryItem {
private int serialNbr;
public void setTimer()

Copyright 2004, Oracle. All rights reserved.

What Are Abstract Methods?

An abstract method:
Is an implementation placeholder
Is part of an abstract class
Must be overridden by a concrete subclass

12-5

Each concrete subclass can implement the


method differently.

Copyright 2004, Oracle. All rights reserved.

Defining Abstract Methods

Use the abstract keyword to declare a method as


abstract:
Provide the method signature only.
The class must also be abstract.

Why is this useful?


Declare the structure of a given class without
providing complete implementation of every
method.
public abstract class InventoryItem {
public abstract boolean isRentable();

12-6

Copyright 2004, Oracle. All rights reserved.

Defining and Using Interfaces

An interface is like a fully abstract class:


All its methods are abstract.
All variables are public static final.

12-7

An interface lists a set of method signatures


without any code details.
A class that implements the interface must
provide code details for all the methods of the
interface.
A class can implement many interfaces but can
extend only one class.

Copyright 2004, Oracle. All rights reserved.

Examples of Interfaces

Interfaces describe an aspect of behavior that


different classes require.
For example, classes that can be steered support
the steerable interface.
Classes can be unrelated.

Nonsteerable

12-8

Steerable

Copyright 2004, Oracle. All rights reserved.

Creating Interfaces

Use the interface keyword:


public interface Steerable {
int MAXTURN = 45;
void turnLeft(int deg);
void turnRight(int deg);
}

12-9

All methods are public abstract.


All variables are public static final.

Copyright 2004, Oracle. All rights reserved.

Implementing Interfaces

Use the implements keyword:


public class Yacht extends Boat
implements Steerable {
public void turnLeft(int deg) {}
public void turnRight(int deg) {}
}

12-10

Copyright 2004, Oracle. All rights reserved.

Sort: A Real-World Example

12-11

Is used by several unrelated classes


Contains a known set of methods
Is needed to sort any type of object
Uses comparison rules that are known only to the
sortable object
Supports good code reuse

Copyright 2004, Oracle. All rights reserved.

Overview of the Classes

Created by the sort expert:


public interface
Sortable

Created by the movie expert:


public class Movie
implements Sortable

12-12

public abstract
class Sort

public class
MyApplication

Copyright 2004, Oracle. All rights reserved.

How the Sort Works


MyApplication

sortObjects()
returns the
sorted list.

MyApplication passes
an array of movies to
Sort.sortObjects().

Sort
The movie
returns the
result of the
comparison.

sortObjects()
asks a movie to
2
compare itself with
another movie.

3
Movie

12-13

Copyright 2004, Oracle. All rights reserved.

The Sortable Interface

Specifies the compare() method:


public interface Sortable {
// compare(): Compare this object to another object
// Returns:
//
0 if this object is equal to obj2
//
a value < 0 if this object < obj2
//
a value > 0 if this object > obj2
int compare(Object obj2);
}

12-14

Copyright 2004, Oracle. All rights reserved.

The Sort Class

Holds sortObjects():
public abstract class Sort {
public static void sortObjects(Sortable[] items) {
// Step through the array comparing and swapping;
// do this length-1 times
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length - 1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempitem = items[j+1];
items[j+1] = items[j];
items[j] = tempitem; } } } } }

12-15

Copyright 2004, Oracle. All rights reserved.

The Movie Class

Implements Sortable:
public class Movie extends InventoryItem
implements Sortable {
String title;
public int compare(Object movie2) {
String title1 = this.title;
String title2 = ((Movie)movie2).getTitle();
return(title1.compareTo(title2));
}
}

12-16

Copyright 2004, Oracle. All rights reserved.

Using the Sort

Call Sort.sortObjects(Sortable []) with an array


of Movie as the argument:
class myApplication {
Movie[] movielist;

// build the array of Movie


Sort.sortObjects(movielist);
}

12-17

Copyright 2004, Oracle. All rights reserved.

Using instanceof with Interfaces

Use the instanceof operator to determine


whether an object implements an interface.
Use downcasting to call methods that are defined
in the interface:
public void aMethod(Object obj) {

if (obj instanceof Sortable)


((Sortable)obj).compare(obj2);
}

12-18

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


An abstract class cannot be instantiated.
An abstract method has a signature but no code.
An interface is a collection of abstract methods to
be implemented elsewhere.
A class can implement many interfaces.
Implementing more than one interface is
comparable to multiple inheritance.

12-19

Copyright 2004, Oracle. All rights reserved.

Practice 12: Overview

This practice covers:


Making an interface and abstract class
Implementing the java.lang.Comparable
interface to sort objects
Testing the abstract and interface classes

12-20

Copyright 2004, Oracle. All rights reserved.

Throwing and Catching Exceptions

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Explain the basic concepts of exception handling
Write code to catch and handle exceptions
Write code to throw exceptions
Create your own exceptions

13-2

Copyright 2004, Oracle. All rights reserved.

What Is an Exception?

An exception is an unexpected event.

13-3

Copyright 2004, Oracle. All rights reserved.

How Does Java Handle Exceptions?

A method throws an exception.


A handler catches the exception.

Exception object

Yes

13-4

Handler
for this
exception?

No

Copyright 2004, Oracle. All rights reserved.

Advantages of Java Exceptions:


Separating Error Handling Code

13-5

In traditional programming, error handling often


makes code more confusing to read.
Java separates the details of handling unexpected
errors from the main work of the program.
The resulting code is clearer to read and,
therefore, less prone to bugs.

Copyright 2004, Oracle. All rights reserved.

Advantages of Java Exceptions:


Passing Errors Up the Call Stack
Traditional error
handling
method1
//handle error
method2

Java exceptions

Error
code

method3

Error
code

method4

Error
code

Each method checks for


errors and returns an error
code to its calling method.

13-6

Method1
//handle ex
method2
method3

Exception
ex

method4
method4 throws an
exception; eventually
method1 catches it.

Copyright 2004, Oracle. All rights reserved.

Advantages of Java Exceptions:


Exceptions Cannot Be Ignored
Traditional error
handling

Java exceptions

method1
//handle error

method1
//handle ex

method2

method2

method3

method3

method4

Error
code

If method3 ignores the


error, then it will never be
handled.

13-7

Exception
ex

method4
The exception must be
caught and handled
somewhere.

Copyright 2004, Oracle. All rights reserved.

Checked Exceptions, Unchecked


Exceptions, and Errors
All errors and exceptions extend the Throwable class.
Throwable

Error

Unrecoverable
errors

Exception

Checked
exceptions

RuntimeException

Unchecked (run-time)
exceptions
13-8

Copyright 2004, Oracle. All rights reserved.

What to Do with an Exception

13-9

Catch the exception and handle it.


Allow the exception to pass to the calling method.
Catch the exception and throw a different
exception.

Copyright 2004, Oracle. All rights reserved.

Catching and Handling Exceptions

Enclose the method


call in a try block.

Handle each
exception in a catch
block.
Perform any final
processing in a
finally block.

13-10

try {
// call the method
}
catch (exception1) {
// handle exception1
}
catch (exception2) {
// handle exception2
}
finally {
// any final processing
}

Copyright 2004, Oracle. All rights reserved.

Catching a Single Exception

int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here

13-11

Copyright 2004, Oracle. All rights reserved.

Catching Multiple Exceptions


try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}

13-12

Copyright 2004, Oracle. All rights reserved.

Cleaning Up with a finally Block


FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}

13-13

Copyright 2004, Oracle. All rights reserved.

Catching and Handling Exceptions:


Guided Practice
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}

13-14

Copyright 2004, Oracle. All rights reserved.

Catching and Handling Exceptions:


Guided Practice
void myMethod () {
try {
getSomething();
} catch (IndexOutOfBoundsException e1) {
System.out.println("Caught IOBException ");
} catch (Exception e2) {
System.out.println("Caught Exception ");
} finally {
System.out.println("No more exceptions ");
}
System.out.println("Goodbye");
}

13-15

Copyright 2004, Oracle. All rights reserved.

Allowing an Exception to Pass to the


Calling Method

Use throws in the method declaration.

The exception propagates to the calling method.


public int myMethod() throws exception1 {
// code that might throw exception1
}
public URL changeURL(URL oldURL)
throws MalformedURLException {
return new URL("http://www.oracle.com");
}

13-16

Copyright 2004, Oracle. All rights reserved.

Throwing Exceptions

Throw exceptions by using the throw keyword.


Use throws in the method declaration.
throw new Exception1();
public String getValue(int index) throws
IndexOutOfBoundsException {
if (index < 0 || index >= values.length) {
throw new IndexOutOfBoundsException();
}

13-17

Copyright 2004, Oracle. All rights reserved.

Creating Exceptions

Extend the Exception class.


public class MyException extends Exception { }
public class UserFileException extends Exception {
public UserFileException (String message) {
super(message);
}
}

13-18

Copyright 2004, Oracle. All rights reserved.

Catching an Exception and Throwing a


Different Exception
catch (exception1 e) {
throw new exception2();
}
void readUserFile() throws UserFileException {
try {
// code to open and read userfile
}
catch(IOException e) {
throw new UserFileException(e.toString());
}
}

13-19

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to do the


following:
Use Java exceptions for robust error handling
Handle exceptions by using try, catch, and
finally
Use the throw keyword to throw an exception

13-20

Use a method to declare an exception in its


signature to pass it up the call stack

Copyright 2004, Oracle. All rights reserved.

Practice 13: Overview

This practice covers:


Creating a custom exception
Changing DataMan finder methods to throw
exceptions
Handling the exceptions when calling the DataMan
finder methods
Testing the changes to the code

13-21

Copyright 2004, Oracle. All rights reserved.

User Interface Design: Swing Basics


Planning the Application Layout

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Explain Abstract Window Toolkit (AWT), Swing,
and Java Foundation Classes (JFC)
Detail the Swing UI containment hierarchy
Describe how to use layout managers
Add UI containers to an application to group
components
Embed UI components into UI containers
Use the Swing pluggable look and feel

14-2

Copyright 2004, Oracle. All rights reserved.

Running Java UI Applications

14-3

Copyright 2004, Oracle. All rights reserved.

AWT, Swing, and JFC

AWT, or Abstract Window Toolkit (java.awt):


A graphical user interface library
The predecessor to Swing components and the
foundation for Swing and JFC

Swing (javax.swing):
A more powerful graphical user interface library
Built on top of the AWT class hierarchy

Java Foundation Classes (JFC):


A collection of APIs including: AWT, Swing,
Accessibility API, Pluggable Look and Feel
Java 2D API, Drag and Drop support (since JDK 1.2)

14-4

Copyright 2004, Oracle. All rights reserved.

Swing Features
A set of visual components that have been available
since JDK 1.1, but part of core JDK since version 1.2:
Lightweight components compared to AWT
Pluggable look and feel API
InventoryItem
Many more components than AWT

14-5

JButton

JSlider

JComboBox

JTextField

JTree

JProgressBar

Copyright 2004, Oracle. All rights reserved.

Lightweight or Heavyweight Components?

Heavyweight components
Strong dependency on
native peer code
Each rendered in its own
opaque window
Early AWT components
were mostly
heavyweight
Include some Swing
top-level components
(JFrame, JApplet,
JDialog)

14-6

Lightweight components
No dependence on native
peer code
Can have transparent
backgrounds
Most Swing components
are lightweight
When displayed, they can
appear nonrectangular
Must be displayed in
heavyweight container

Copyright 2004, Oracle. All rights reserved.

Planning the UI Layout

Building a UI application involves planning, even more


so when building Swing applications. Planning
requires understanding the following concepts and
their relationship:
UI containment hierarchy (a root component that
comprises nested containers and components)
Container levels and types (such as top-level or
intermediate containers)
Layout managers and their types (used by each
container)
Components that can be added into containers

14-7

Copyright 2004, Oracle. All rights reserved.

The Containment Hierarchy

Top-level containers

Frame

Frame
Dialog
Applet

Intermediate containers
Panel
Scroll Pane

Atomic components
Label
Text items
Buttons

14-8

Panel

Copyright 2004, Oracle. All rights reserved.

Atomic
components

Top-Level Containers

Swing provides JFrame, JDialog, or JApplet,


with changeable properties such as:
A content pane for holding intermediate containers
or components, by using the getContentPane() or
setContentPane() methods
A border, by using a setBorder() method
A title, by using a setTitle() method
Window decorations such as buttons for closing
and minimizing (excludes applets)

AWT provides Frame, Dialog, or Applet


These do not provide properties such as a content
pane or borders.

14-9

Copyright 2004, Oracle. All rights reserved.

Intermediate Containers

Designed to contain components (or containers):


Can be nested within other containers
Types of intermediate containers:
Panels for grouping containers or components
Scroll Panes to add scroll bars around components
that can grow, such as a list or a text area
Split Panes to display two components in a fixed
area, which is adjustable by the user
Tabbed Panes for containing multiple components,
showing only one at a time, based on user selection
Tool Bars for grouping components, such as
buttons
Internal Frames for nested windows

14-10

Copyright 2004, Oracle. All rights reserved.

Atomic Components

14-11

Buttons
Check boxes
Combo boxes
Text
Lists
Labels

Copyright 2004, Oracle. All rights reserved.

Layout Management Overview

14-12

Copyright 2004, Oracle. All rights reserved.

Border Layout

14-13

Has five areas: North, South, West, East, and


Center
Has center area that expands to fill the available
space
Displays only one component in each area
Makes each area useful for holding intermediate
panels

Copyright 2004, Oracle. All rights reserved.

GridBag Layout

14-14

Is based on a grid
Allows components to span multiple rows and
columns
Allows rows and columns to differ in size
Uses the components preferred size to control
cell size

Copyright 2004, Oracle. All rights reserved.

GridBag Constraints

External insets
Component
padding

Cell position
Cell span
Expansion
weighting

Anchoring

Fill rules

14-15

Copyright 2004, Oracle. All rights reserved.

Using Layout Managers

Layout managers are designed to manage multiple


components simultaneously.
Using a layout manager with containers requires:
Creating a container and a layout manager object
Setting the layout property of the container
Adding items (components or other containers) into
the regions that are defined by the layout manager

14-16

Different layout managers require different


arguments to control component placement.

Copyright 2004, Oracle. All rights reserved.

Combining Layout Managers

Border
null

VerticalFlow

GridBag

Grid

14-17

Copyright 2004, Oracle. All rights reserved.

Using Frames or Dialogs

A Java frame is equivalent to an application window.


Use the JFrame for a main window
It has properties for icons, title, window decorations
for minimize, maximize, and close buttons.
It uses BorderLayout by default.
It provides a default content pane that occupies the
center region of the layout.
You can set the frame size with the setSize()
method, and make it visible by using the
setVisible() method.

Use JDialog for a modal window


You must dismiss a modal window before the
application that invokes it can become active.

14-18

Copyright 2004, Oracle. All rights reserved.

Using JPanel Containers

JPanel is a general purpose container.

Can use any layout manager


(uses Flowlayout by default)

Can use any border


Can have added components
or other panels/containers
by using the add() method

JPanel myPanel = new JPanel(new BorderLayout());


JTextArea jTextArea1 = new JTextArea();
myPanel.setBorder(BorderFactory.createRaisedBevelBorder());
myPanel.add(jTextArea1, BorderLayout.SOUTH);

14-19

Copyright 2004, Oracle. All rights reserved.

Adding Borders to Components

Borders are Swing objects.


Defined in javax.swing.borders

Use setBorder() to assign a


border to a component.
Create borders with the class called
javax.swing.BorderFactory.
Create borders separately to use with many
components.

jPanel1.setBorder(BorderFactory.createBevelBorder(
BevelBorder.LOWERED,Color.lightGray,Color.darkGray));
Border etchedBorder =
BorderFactory.createEtchedBorder();//pre-create border
jPanel2.setBorder(etchedBorder);
// use border`

14-20

Copyright 2004, Oracle. All rights reserved.

Using Internal Frames

An internal frame is the equivalent of a document


window that is contained within an application window
for multiple-document interface (MDI) window
applications.
Use JInternalFrame for an internal window:
Similar to JFrame, it can contain intermediate
containers and components and use a layout
manager.
By default it is not closable, iconifiable,
maximizable, or visible.

Use a JDesktopPane as the content pane in which


the internal frames are added:
Controls the size and placement of internal frames
Uses a null layout manager by default

14-21

Copyright 2004, Oracle. All rights reserved.

Swing Text Controls

14-22

Copyright 2004, Oracle. All rights reserved.

Adding Components
with Oracle JDeveloper 10g

14-23

Use the wizard to create a JFrame.

Select a layout manager.


Add components from the Component Palette.
Fine-tune component properties.

Copyright 2004, Oracle. All rights reserved.

Creating a Frame

Frame

14-24

Copyright 2004, Oracle. All rights reserved.

Adding Components
Use the Component Palette to add
Swing items to the Frame

14-25

Copyright 2004, Oracle. All rights reserved.

Setting Pluggable Look and Feel

Swing applications provide support for a different look


and feel to adapt to the visual environment of the
operating system. The look and feel:
Is application-specific:
Can be initialized when the application starts
Can change dynamically

Affects lightweight Swing components


Supports Win, Mac, Java (Metal) and Motif
Uses javax.swing.UIManager class
Provides the setLookAndFeel() method, which
accepts a look and feel class name string.

14-26

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


Frames are top-level containers.
Panels are intermediate containers that can be
nested.
Each container can have its own layout manager.
Layout managers control component placement.
You can combine layout managers within an
application.
You can control the applications look and feel.

14-27

Copyright 2004, Oracle. All rights reserved.

Practice 14: Overview

This practice covers:


Creating a class based on JFrame for the main
window of the OrderEntry application.
Add a default menu and status bar.
Add a JDesktopPane and set it as the content pane.

Creating a class based on JInternalFrame to


manage order creation and data entry.
Create the container layout hierarchical structure
for the order-entry frame components.
Add some of the components to this frame.

14-28

Setting layout managers for each container

Copyright 2004, Oracle. All rights reserved.

Adding User Interface Components


and Event Handling

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Add Swing components to an application
Get and modify the contents of the components
Provide event handlers for common types of
events
Create a menu bar

15-2

Copyright 2004, Oracle. All rights reserved.

Swing Components

Text controls

JTextField
JPasswordField
JTextArea
JEditorPane
JTextPane

Graphic controls
JTree
JTable
JToggleButton

15-3

Copyright 2004, Oracle. All rights reserved.

Swing Components in JDeveloper

Use the Swing Component Palette to add items.

15-4

Copyright 2004, Oracle. All rights reserved.

Invoking the UI Editor


Right-click and select Open from the Context menu.

Code Editor
System Navigator
Context menu
15-5

Copyright 2004, Oracle. All rights reserved.

How to Add a Component to a Form


1: Open the Component
Palette; select the Swing
category.

2: Drag the component to the form. The


class updates automatically.

15-6

Copyright 2004, Oracle. All rights reserved.

Edit the Properties of a Component

Change property values


in the Inspector.
15-7

Copyright 2004, Oracle. All rights reserved.

Code Generated by JDeveloper

For example: Adding a JButton to a Jframe:


import javax.swing.JButton;
public class JFrame1 extends JFrame {
JButton jButton1 = new JButton();
...
public void jbInit() throws Exception {
...
jbutton1.setText("jButton1");
...
this.getContentPane().add(jButton1,
new XYConstraints(21, 20, 118, 48));
}

15-8

Copyright 2004, Oracle. All rights reserved.

Creating a Menu

Select Create Menu Bar during application


creation.
Add a JMenuBar from the Component Palette.
JDeveloper creates:
JMenuBar for visual container for menus
JMenu, which represents a menu of items, added to
a menu bar
JMenuItems, which are placed in a JMenu

15-9

Each JMenuItem supports events, interfaces, and


handler methods in the same way as with other
Swing UI components.
A JMenuBar can be added to any top-level
container, such as Frames, Dialogs, or Applets.
Copyright 2004, Oracle. All rights reserved.

Using JDeveloper Menu Editor

In the JDeveloper Menu Editor, use the Structure


pane:
Expand the Menu node.
Click the menu bar object for a visual
representation.
Right-click menu or menu items to alter
structure from the Context menu options.

Context menu
when
right-clicking a
menu item

Click
menu bar
object in
Structure pane
to display
menu bar

15-10

Copyright 2004, Oracle. All rights reserved.

Practice 15-1: Overview

This practice covers:


Creating the OrderEntryMDIFrame menu

15-11

Adding the menu items and a separator to the


Order menu
Adding components to OrderEntryFrame to form
its visual structure

Copyright 2004, Oracle. All rights reserved.

UI for Java Application

15-12

Copyright 2004, Oracle. All rights reserved.

Java Event Handling Model

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.

15-13

Copyright 2004, Oracle. All rights reserved.

Event Handling Code Basics

Create the event source.


Jbutton findBtn = new Jbutton("Find");

Create the event listener implementing the


required event interface.
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// handler logic
}
}

Register the listener with the event source.


findBtn.addActionListener(new MyListener());

15-14

Copyright 2004, Oracle. All rights reserved.

Event Handling Process: Registration

Source
OK

Event listener object


Handler method

MyListener actionListenerObj = new MyListener();


public void jbInit() {
button1.addActionListener(actionListenerObj);

15-15

Copyright 2004, Oracle. All rights reserved.

Event Handling Process:


The Event Occurs
Source
OK

Event listener object


Notified

Handler method

public void jbInit() {


button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
}); }

15-16

Copyright 2004, Oracle. All rights reserved.

Event Handling Process:


Running the Event Handler

Source
OK
Source

15-17

Event listener object


Handler method:
save changes and quit

Copyright 2004, Oracle. All rights reserved.

Using Adapter Classes for Listeners


Adapter classes are convenience classes that
implement event listener interface:
They provide empty method implementations.
They are extended and the desired method
overridden.
interface MouseListener {
// Declares five methods
}
class MouseAdapter implements MouseListener {
// Empty implementations of all five methods
}
public class MyListener extends MouseAdapter {
// Override only the methods you need
}
15-18

Copyright 2004, Oracle. All rights reserved.

Swing Model View Controller Architecture

Model, View, Controller principles


Event

Controller

modify

modify

View
View

Notify update

Model

Get changed data

Terms explained:
Model represents the data or information.
View provides a visual representation of the data.
Controller handles events modifying the
view/model.

15-19

Always update Swing components on the event


thread queue, or use SwingUtilities methods.
Copyright 2004, Oracle. All rights reserved.

Basic Text Component Methods

Text item (JLabel, JTextField, and JButton)


methods:
void setText(String value)
String getText()

Additional methods in JTextArea:


void append(String value)
void insert(String value, int pos)

Changes to component contents are usually done


in the event handling thread.
Note: Consult the Java API documentation for details
about each components capabilities.

15-20

Copyright 2004, Oracle. All rights reserved.

Basic JList Component Methods

Subset of JList component methods include:


void setListData(Vector)
Copies Vector to a ListModel applied with
setModel

void setModel(ListModel)
Sets model representing the data and clears
selection. Uses DefaultListModel class for the
model.

Object getSelectedValue()
Returns the selected object, or null if nothing is
selected

int getSelectedIndex()
Returns the index of the selected item, or 1 if
nothing is selected

15-21

Copyright 2004, Oracle. All rights reserved.

What Events Can


a Component Generate?
Events that a component can
generate

Event handler
methods
15-22

Copyright 2004, Oracle. All rights reserved.

How to Define an Event Handler


in JDeveloper
1: Select the event that you
want to handle.

2: Click the right column to fill in


a method name.
3: Double-click the right column to
create the method.

15-23

Copyright 2004, Oracle. All rights reserved.

Default Event Handling Code Style


Generated by JDeveloper
public void jbInit() throws Exception {
Find

findButton.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
findButton_actionPerformed(e);
}
});
void findButton_actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}

15-24

Copyright 2004, Oracle. All rights reserved.

Completing the Event Handler Method

public class JFrame1 extends JFrame {

void findButton_actionPerformed(ActionEvent e){


// When the user clicks the button, display
// the list of customers in jTextArea1
String findList = (Supplies-R-Us " + "\n" +
Consulting Inc. " + "\n" +
Just-In-Time Training ");
jTextArea1.setText(findList);
}
}

15-25

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:


Add a Swing component to a visual container
Get and modify the contents of the components
Use the AWT event handling model to:
Create an event source
Create an event listener and handler code
Register an event listener for the event to be
handled

15-26

Create a menu bar with menus and menu items


Handle events

Copyright 2004, Oracle. All rights reserved.

Practice 15-2: Overview

This practice covers adding event handling for:


Order > New menu
Find Customer button
Add Product button

15-27

Copyright 2004, Oracle. All rights reserved.

Using JDBC to Access the Database

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Describe how Java applications connect to the
database
Describe how Java database functionality is
supported by the Oracle database
Load and register a JDBC driver
Connect to an Oracle database
Follow the steps to execute a simple SELECT
statement
Map simple Oracle database types to Java types

16-2

Copyright 2004, Oracle. All rights reserved.

Java, J2EE, and Oracle 10g

Client

Web
server

Application
server

Presentation

Business
logic

Oracle
database

Oracle
Application Server 10g
J2EE Certified Environment

JDBC

16-3

Copyright 2004, Oracle. All rights reserved.

Data

Connecting to a Database with Java

Client applications, JSPs, and servlets use JDBC.

Client application
or applet

16-4

JDBC

Copyright 2004, Oracle. All rights reserved.

Relational DB

What Is JDBC?

JDBC is a standard interface for connecting to


relational databases from Java.
The JDBC API includes Core API Package in
java.sql.
JDBC 2.0 API includes Optional Package API in
javax.sql.
JDBC 3.0 API includes the Core API and Optional
Package API

16-5

Include the Oracle JDBC driver archive file in the


CLASSPATH.
The JDBC class library is part of the Java 2,
Standard Edition (J2SE).
Copyright 2004, Oracle. All rights reserved.

Preparing the Environment

Set the CLASSPATH:


[Oracle Home]\jdbc\lib\classes12.jar

Import JDBC packages:


// Standard packages
import java.sql.*;
import java.math.*; // optional
// Oracle extension to JDBC packages
import oracle.jdbc.*;
import oracle.sql.*;

16-6

Copyright 2004, Oracle. All rights reserved.

Steps for Using JDBC to Execute


SQL Statements
1. Register JDBC driver.

2. Obtain a connection.

3. Create statement object.

4. Execute SQL statement.

4a. Process SELECT


statement.

5. Process query results.

16-7

4b. Process DML


or DDL statement.

6. Close connections.

Copyright 2004, Oracle. All rights reserved.

Step 1: Registering the Driver

Register the driver in the code:


DriverManager.registerDriver (new
oracle.jdbc.OracleDriver());
Class.forName
("oracle.jdbc.OracleDriver");

Register the driver when launching the class:


java D jdbc.drivers =
oracle.jdbc.OracleDriver <ClassName>;

16-8

Copyright 2004, Oracle. All rights reserved.

Connecting to the Database

Using the package oracle.jdbc.driver, Oracle


provides different drivers to establish a connection to
the database.
OracleDriver
JDBC calls

16-9

Thin client
OCI
Server-based

Database
commands

Copyright 2004, Oracle. All rights reserved.

Database

Oracle JDBC Drivers: Thin Client Driver

Is written entirely in Java


Must be used by applets

Applet
JDBC
Thin driver
Client

16-10

Oracle

Server

Copyright 2004, Oracle. All rights reserved.

Oracle JDBC Drivers: OCI Client Drivers

Is written in C and Java


Must be installed on the client
Application
JDBC
OCI driver

ocixxx.dll
Client

16-11

Oracle

Server

Copyright 2004, Oracle. All rights reserved.

Choosing the Right Driver

Type of Program

Driver

Applet

Thin

Client application

Thin
Thin

EJB, servlet
(on the middle tier)
Stored procedure

16-12

OCI

OCI
Server side

Copyright 2004, Oracle. All rights reserved.

Step 2: Getting a Database Connection

In JDBC 1.0, use the DriverManager class, which


provides overloaded getConnection() methods.
All connection methods require a JDBC URL to
specify the connection details.

Example:
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");

16-13

Vendors can provide different types of JDBC


drivers.

Copyright 2004, Oracle. All rights reserved.

About JDBC URLs

JDBC uses a URL-like string. The URL identifies


The JDBC driver to use for the connection
Database connection details, which vary depending
on the driver used
jdbc:<subprotocol>:<subname>

Protocol

Database identification

jdbc:oracle:<driver>:@<database>

Example using Oracle Thin JDBC driver:


jdbc:oracle:thin:@myhost:1521:ORCL

16-14

Copyright 2004, Oracle. All rights reserved.

JDBC URLs with Oracle Drivers

Oracle Thin driver


Syntax: jdbc:oracle:thin:@<host>:<port>:<SID>
Example: "jdbc:oracle:thin:@myhost:1521:orcl"

Oracle OCI driver


Syntax: jdbc:oracle:oci:@<tnsname entry>
Example: "jdbc:oracle:oci:@orcl"

16-15

Copyright 2004, Oracle. All rights reserved.

Step 3: Creating a Statement

JDBC statement objects are created from the


Connection instance:
Use the createStatement() method, which
provides a context for executing an SQL statement.
Example:
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");
Statement stmt = conn.createStatement();

16-16

Copyright 2004, Oracle. All rights reserved.

Using the Statement Interface

The Statement interface provides three methods to


execute SQL statements:
Use executeQuery(String sql)for SELECT
statements.
Returns a ResultSet object for processing rows

Use executeUpdate(String sql) for DML or


DDL.
Returns an int

Use execute(String) for any SQL statement.


Returns a boolean value

16-17

Copyright 2004, Oracle. All rights reserved.

Step 4a: Executing a Query

Provide a SQL query string, without semicolon, as an


argument to the executeQuery() method.
Returns a ResultSet object:
Statement stmt = null;
ResultSet rset = null;
stmt = conn.createStatement();
rset = stmt.executeQuery
("SELECT ename FROM emp");

16-18

Copyright 2004, Oracle. All rights reserved.

The ResultSet Object

The JDBC driver returns the results of a query in a


ResultSet object.
ResultSet:
Maintains a cursor pointing to its current row of
data
Provides methods to retrieve column values

16-19

Copyright 2004, Oracle. All rights reserved.

Step 4b: Submitting DML Statements

1. Create an empty statement object:


Statement stmt = conn.createStatement();

2. Use executeUpdate to execute the statement:


int count = stmt.executeUpdate(SQLDMLstatement);

Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM order_items
WHERE order_id = 2354");

16-20

Copyright 2004, Oracle. All rights reserved.

Step 4b: Submitting DDL Statements

1. Create an empty statement object:


Statement stmt = conn.createStatement();

2. Use executeUpdate to execute the statement:


int count = stmt.executeUpdate(SQLDDLstatement);

Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("CREATE TABLE temp (col1 NUMBER(5,2),
col2 VARCHAR2(30)");

16-21

Copyright 2004, Oracle. All rights reserved.

Step 5: Processing the Query Results

The executeQuery() method returns a ResultSet.


Use the next() method in loop to iterate through
rows.
Use getXXX() methods to obtain column values
by column position in query, or column name.
stmt = conn.createStatement();
rset = stmt.executeQuery(
"SELECT ename FROM emp");
while (rset.next()) {
System.out.println
(rset.getString("ename"));
}

16-22

Copyright 2004, Oracle. All rights reserved.

Step 6: Closing Connections

Explicitly close a Connection, Statement, and


ResultSet object to release resources that are no
longer needed.
Call their respective close() methods:
Connection conn = ...;
Statement stmt = ...;
ResultSet rset = stmt.executeQuery(
"SELECT ename FROM emp");
...
// clean up
rset.close();
stmt.close();
conn.close();
...
16-23

Copyright 2004, Oracle. All rights reserved.

A Basic Query Example


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();
}
}
16-24

Copyright 2004, Oracle. All rights reserved.

Mapping Database Types to Java Types


ResultSet maps database types to Java types:
ResultSet rset = stmt.executeQuery
("SELECT empno, hiredate, job
FROM emp");
while (rset.next()){
int id = rset.getInt(1);
Date hiredate = rset.getDate(2);
String job = rset.getString(3);

16-25

Column Name

Type

Method

empno

NUMBER

getInt()

hiredate

DATE

getDate()

job

VARCHAR2

getString()

Copyright 2004, Oracle. All rights reserved.

Handling an Unknown SQL Statement

1. Create an empty statement object:


Statement stmt = conn.createStatement();

2. Use execute to execute the statement:


boolean isQuery = stmt.execute(SQLstatement);

3. Process the statement accordingly:


if (isQuery) { // was a query - process results
ResultSet r = stmt.getResultSet(); ...
}
else { // was an update or DDL - process result
int count = stmt.getUpdateCount(); ...
}

16-26

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions

SQL statements can throw a


java.sql.SQLException.

Use standard Java error handling methods.


try

{
rset = stmt.executeQuery("SELECT empno,
ename FROM emp");
}
catch (java.sql.SQLException e)
{ ... /* handle SQL errors */ }

...
finally { // clean up
try { if (rset != null) rset.close(); }
catch (Exception e)
{ ... /* handle closing errors */ }
...

16-27

Copyright 2004, Oracle. All rights reserved.

Managing Transactions

By default, connections are in autocommit mode.


Use conn.setAutoCommit(false)to turn
autocommit off.
To control transactions when you are not in
autocommit mode, use:
conn.commit(): Commit a transaction
conn.rollback(): Roll back a transaction

16-28

Closing a connection commits the transaction


even with the autocommit off option.

Copyright 2004, Oracle. All rights reserved.

The PreparedStatement Object

16-29

A PreparedStatement prevents reparsing of SQL


statements.
Use this object for statements that you want to
execute more than once.
A PreparedStatement can contain variables that
you supply each time you execute the statement.

Copyright 2004, Oracle. All rights reserved.

How to Create a PreparedStatement

1. Register the driver and create the database


connection.
2. Create the PreparedStatement, identifying
variables with a question mark (?):
PreparedStatement pstmt =
conn.prepareStatement
("UPDATE emp SET ename = ? WHERE empno = ?");
PreparedStatement pstmt =
conn.prepareStatement
("SELECT ename FROM emp WHERE empno = ?");

16-30

Copyright 2004, Oracle. All rights reserved.

How to Execute a PreparedStatement

1. Supply values for the variables:


pstmt.setXXX(index, value);

2. Execute the statement:


pstmt.executeQuery();
pstmt.executeUpdate();
int empNo = 3521;
PreparedStatement pstmt =
conn.prepareStatement("UPDATE emp
SET ename = ? WHERE empno = ? ");
pstmt.setString(1, "DURAND");
pstmt.setInt(2, empNo);
pstmt.executeUpdate();

16-31

Copyright 2004, Oracle. All rights reserved.

Maximize Database Access

16-32

Use connection pooling to minimize the operation


costs of creating and closing sessions.
Use explicit data source declaration for physical
reference to the database.
Use the getConnection() method to obtain a
logical connection instance.

Copyright 2004, Oracle. All rights reserved.

Connection Pooling
Middle tier

Java servlet
Data source
Middle-tier server code
ConnectionPoolDataSource
JDBC
driver

Database

Database
commands

16-33

Copyright 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:


JDBC provides database connectivity for various
Java constructs, including servlets and client
applications.
JDBC is a standard Java interface and part of the
J2SE.
The steps for using SQL statements in Java are
Register, Connect, Submit, and Close.
SQL statements can throw exceptions.
You can control default transactions behavior.

16-34

Copyright 2004, Oracle. All rights reserved.

Practice 16: Overview

This practice covers:


Setting up the Java environment for JDBC
Adding JDBC components to query the database
Populating the OrderEntryFrame with Customers
from the database

16-35

Copyright 2004, Oracle. All rights reserved.

Deploying Applications by Using


Java Web Start

Copyright 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
Define the architecture of Java Web Start
Describe the benefits of using Java Web Start
Deploy an application by using Web Start

17-2

Copyright 2004, Oracle. All rights reserved.

What Is Java Web Start?

17-3

It is an application deployment technology based


on the Java 2 platform.
It launches full-featured applications via any
browser on any platform, from anywhere on the
Web.

Copyright 2004, Oracle. All rights reserved.

Running a Web Start Application

1. Request the
application.
2. Launch Web Start on
the local machine.
3. Download the
application.
4. Launch the
application (Draw).

17-4

HTTP

Copyright 2004, Oracle. All rights reserved.

3
HTTP
4

Advantages of Web Start

17-5

Renders a very responsive and rich user interface


Launches applications from the Start menu on the
desktop
Does not require browser to be running
Allows applications to work offline
Automatically updates applications when invoked

Copyright 2004, Oracle. All rights reserved.

Examining the JNLP File


The JNLP files defines:
The location of the application resources
Information that appears while the application loads
What the application resources are

17-6

Copyright 2004, Oracle. All rights reserved.

Deploying Applications with JDeveloper

The JDeveloper Deployment Profile Wizard:


Detects interclass dependencies
Creates .ear, .war, .jar, or .zip files

Enables you to have control over other files added


to the deployed archive
Enables you to save deployment profile settings in
project files:
To simplify redeployment when code changes
That can be automatically updated with new classes
as they are added to the project

17-7

Copyright 2004, Oracle. All rights reserved.

Creating the Deployment Profile File

Select File > New

17-8

Copyright 2004, Oracle. All rights reserved.

Saving the Deployment Profile

Select a destination and name for the deployment


profile.

17-9

Copyright 2004, Oracle. All rights reserved.

Selecting Files to Deploy


Select the file types to include. Other settings differ for
other deployment profile types.

17-10

Copyright 2004, Oracle. All rights reserved.

Making an Executable .jar File

Set the Main Class field to the class name containing a


main() method, in JAR Options.

17-11

Copyright 2004, Oracle. All rights reserved.

Creating and Deploying the Archive File

17-12

Right-click the Deployment Profile file.


Select the Deploy to menu option.
The .jar file is created in the directory listed in
the deployment properties.

Copyright 2004, Oracle. All rights reserved.

Using JDeveloper to Deploy an Application


to Java Web Start
Step 1: Generate deployment profiles and archive the
application.
Step 2: Start OC4J and create a connection.
Step 3: Use Web Start Wizard to create JNLP file.
Step 4: Archive and deploy your application to OC4J
server.

17-13

Copyright 2004, Oracle. All rights reserved.

Step 1: Generate Deployment Profiles and


Archive Application
Package all the Java application files into a simple
.jar archive.

17-14

Copyright 2004, Oracle. All rights reserved.

Step 2a: Start OC4J

Use the command line to start the server.

17-15

Copyright 2004, Oracle. All rights reserved.

Step 2b: Creating a Connection

Use the Connection Wizard to create a connection to


the application server. You must specify:
The type of connection (OC4J)
The username and password for authentication
Local URL, target Web site, and local directory for
OC4J

17-16

Copyright 2004, Oracle. All rights reserved.

Step 3: Use Web Start Wizard to Create


a JNLP File

17-17

Specify the Web Start name, application archive


(.jar), and main application class.

Include information to be displayed to the user


while downloading (for example, application title,
vendor, and brief description)

Copyright 2004, Oracle. All rights reserved.

Step 4: Archive and Deploy the Application


to the OC4J Server

17-18

Specify properties of the Web components and


deployment description.

Deploy to the OC4J connection created in step 2.


Run the generated HTML file.
Copyright 2004, Oracle. All rights reserved.

Summary

In this module, you should have learned how to:


Describe how a Java Web Start application runs
Describe the benefits of using Java Web Start
Use JDeveloper to deploy an application by using
Web Start

17-19

Copyright 2004, Oracle. All rights reserved.

Practice 17: Overview

This practice covers the following topics:


Archiving your Java application
Creating a new project to hold the Web Start files
and setting the OC4J server preference
Installing and starting the stand-alone OC4J
application server
Creating an application server connection in
JDeveloper
Archiving and deploying the application files to
OC4J, and testing the application

17-20

Copyright 2004, Oracle. All rights reserved.

Practice Solutions

Copyright 2004, Oracle. All rights reserved.

B
Java Language
Quick-Reference
Guide

Console Output
Java applications and applets can output simple messages to the console as
follows:
System.out.println("This is displayed on the console");
Data Types
boolean

Boolean type, can be true or false

byte

1-byte signed integer

char

Unicode character (i.e. 16 bits)

short

2-byte signed integer

int

4-byte signed integer

long

8-byte signed integer

float

Single-precision fraction, 6 significant figures

double

Double-precision fraction, 15 significant figures

Operators
+ - * / %
++ --

+= -= *= /= %= etc.
&&

||

!
== != > >= < <=
& | ^ ~
<< >> >>>
instanceof

Arithmetic operators (% means remainder)


Increment or decrement by 1
result = ++i; means increment by 1 first
result = i++; means do the assignment first
For example, i += 2 is equivalent to i = i + 2
Logical AND. For example, if (i > 50 && i < 70)
The second test is only carried out if necessary use & if the second test should always be done
Logical OR. For example, if (i < 0 || i > 100)
The second test is only carried out if necessary use | if the second test should always be done
Logical NOT. For example, if (!endOfFile)
Relational operators
Bitwise operators (AND, OR, XOR, NOT)
Bitwise shift operators (shift left, shift right with
sign extension, shift right with 0 fill)
Test whether an object is an instance of a class.
For example,
if (anObj instanceof BankAccount)
System.out.println($$$);

Oracle10g: Java Programming B-2

Control Flow: if else


if statements are formed as follows (the else clause is optional). The braces {}
are necessary if the if-body exceeds one line; even if the if-body is just one line,
the braces {} are worth having to aid readability:
String dayname;

if (dayname.equals("Sat") || dayname.equals("Sun")){
System.out.println("Hooray for the weekend");
}
else if (dayname.equals("Mon")) {
System.out.println("I dont like Mondays");
}
else {
System.out.println("Not long for the weekend!");
}
Control Flow: switch
switch is used to check an integer (or character) against a fixed list of
alternative values:
int daynum;

switch (daynum) {
case 0:
case 6:
System.out.println("Hooray for the weekend");
break;
case 1:
System.out.println("I dont like Mondays");
break;
default:
System.out.println("Not long for the weekend!");
break;
}

Oracle10g: Java Programming B-3

Control Flow: Loops


Java contains three loop mechanisms:
int i = 0;
while (i < 100) {
System.out.println("Next square is: " +
i++;
}

i*i);

for (int i = 0; i < 100; i++) {


System.out.println("Next square is: " +
}

i*i);

int positiveValue;
do {
positiveValue = getNumFromUser();
}
while (positiveValue < 0);

Oracle10g: Java Programming B-4

Defining Classes
When you define a class, you define the data attributes (usually private) and
the methods (usually public) for a new data type. The class definition is placed
in a .java file as follows:
// This file is Student.java. The class is declared
// public, so that it can be used anywhere in the program
public class Student {
private String name;
private int
numCourses = 0;
// Constructor to initialize all the data members
public Student(String n, int c) {
name = n;
numCourses = c;
}
// No-arg constructor, to initialize with defaults
public Student() {
this("Anon", 0);
// Call other constructor
}
// finalize() is called when obj is garbage collected
public void finalize() {
System.out.println("Goodbye to this object");
}
// Other methods
public void attendCourse() {
numCourses++;
}
public void cancelPlaceOnCourse() {
numCourses--;
}
public boolean isEligibleForChampagne() {
return (numCourses >= 3);
}
}

Oracle10g: Java Programming B-5

Using Classes
To create an object and send messages to the object:
public class MyTestClass {
public static void main(String[] args) {
// Step 1 - Declare object references
// These refer to null initially in this example
Student me, you;

// Step 2 - Create new Student objects


me = new Student("Andy", 0);
you = new Student();

// Step 3 - Use the Student objects


me.attendCourse();
you.attendCourse();

if (me.isEligibleForChampagne())
System.out.println("Thanks very much");
}
}

Oracle10g: Java Programming B-6

Arrays
An array behaves like an object. Arrays are created and manipulated as follows:
// Step 1 - Declare a reference to an array
int[] squares;
// Could write int squares[];
// Step 2 - Create the array "object" itself
squares = new int[5]; // Creates array with 5 slots
// Step 3 - Initialize slots in the array
for (int i=0; i < squares.length; i++) {
squares[i] = i * i;
System.out.println(squares[i]);
}
Note that array elements start at [0], and that arrays have a length property that
gives you the size of the array. If you inadvertently exceed an arrays bounds, an
exception is thrown at run time and the program aborts.
Note: Arrays can also be set up by using the following abbreviated syntax:
String[] cities = {
"San Francisco",
"Dallas",
"Minneapolis",
"New York",
"Washington, D.C."
};

Oracle10g: Java Programming B-7

Inheritance and Polymorphism


A class can inherit all of the data and methods from another class. Methods in the
superclass can be overridden by the subclass. Any members of the superclass that
you want to access in the subclass must be declared protected. The
protected access specifier allows subclasses, plus any classes in the same
package, to access that item.
public class Account {
private double balance = 0.0;
public Account(double initBal) {
balance = initBal;
}
public void deposit(double amt) {
balance += amt;
}
public void withdraw(double amt) {
balance -= amt;
}
public void display() {
System.out.println("Balance is: " + balance);
}
}
public class CheckAccount extends Account {
private int maxChecks = 0;
private int numChecksWritten = 0;
public CheckAccount(double initBal, int maxChk) {
super(initBal);
// Call superclass ctor
maxChecks = maxChk;
// Initialize our data
}
public void withdraw(double amt) {
super.withdraw(amt);
// Call superclass
numChecksWritten++;
// Increment chk. num.
}
public void display() {
super.display();
// Call superclass
System.out.println(numChecksWritten);
}
}

Oracle10g: Java Programming B-8

Abstract Classes
An abstract class is one that can never be instantiated; in other words, you cannot
create an object of such a class. Abstract classes are specified as follows:
// Abstract superclass
public abstract class Mammal {

// Concrete subclasses
public class Cat extends Mammal {

}
public class Dog extends Mammal {

}
public class Mouse extends Mammal {

Oracle10g: Java Programming B-9

Abstract Methods
An abstract method is one that does not have a body in the superclass. Each concrete
subclass is obliged to override the abstract method and provide an implementation;
otherwise, the subclass is itself deemed abstract because it does not implement all its
methods.
// Abstract superclass
public abstract class Mammal {
// Declare some
public abstract
public abstract
public abstract

abstract methods
void eat();
void move();
void reproduce();

// Define some data members if you like


private double weight;
private int age;
// Define some concrete methods too if you like
public double getWeight{} {
return weight;
}
public int getAge() {
return age;
}
}

Oracle10g: Java Programming B-10

Interfaces
An interface is similar to an abstract class with 100% abstract methods and no
instance variables. An interface is defined as follows:
public interface Runnable {
public void run();
}
A class can implement an interface as follows. The class is obliged to provide an
implementation for every method specified in the interface; otherwise, the class
must be declared abstract because it does not implement all its methods.
public class MyApp extends Applet implements Runnable {
public void run() {
// This is called when the Applet is kicked off
// in a separate thread

// Plus other applet methods

Oracle10g: Java Programming B-11

Static Variables
A static variable is like a global variable for a class. In other words, you get
only one instance of the variable for the whole class, regardless of how many
objects exist. static variables are declared in the class as follows:
public class Account {
private String accnum;
private double balance = 0.0;

// Instance var
// Instance var

private static double intRate = 5.0;

// Class var

}
Static Methods
A static method in a class is one that can access only static items; it cannot
access any non-static data or methods. static methods are defined in the
class as follows:
public class Account {
public static void setIntRate(double newRate) {
intRate = newRate;
}
public static double getIntRate() {
return intRate;
}

}
To invoke a static method, use the name of the class as follows:
public class MyTestClass {
public static void main(String[] args) {
System.out.println("Interest rate is" +
Account.getIntRate());
}
}

Oracle10g: Java Programming B-12

Packages
Related classes can be placed in a common package as follows:
// Car.java
package mycarpkg;
public class Car {

// Engine.java
package mycarpkg;
public class Engine {

// Transmission.java
package mycarpkg;
public class Transmission {

}
Importing Packages
Anyone needing to use the classes in this package can import all or some of the
classes in the package as follows:
import mycarpkg.*;

// import all classes in package

or
import mycarpkg.Car; // just import individual classes

Oracle10g: Java Programming B-13

The final Keyword


The final keyword can be used in three situations:
final classes (for example, the class cannot be inherited from)
final methods (for example, the method cannot be overridden in a subclass)
final variables (for example, the variable is constant and cannot be changed)
Here are some examples:
// final classes
public final class Color {

// final methods
public class MySecurityClass {
public final void validatePassword(String password) {

}
}

// final variables
public class MyTrigClass {
public static final double PI = 3.1415;

Oracle10g: Java Programming B-14

Exception Handling
Exception handling is achieved through five keywords in Java:
try
The block of code where statements that can cause an exception are
placed
catch The block of code where error processing is placed
finally An optional block of code after a try block, for unconditional
execution
throw The keyword that is used in the low-level code to generate or throw an
exception
throws The keyword that specifies the list of exceptions that a method can
throw
Here are some examples:
public class MyClass {
public void anyMethod() {
try {
func1();
func2();
func3();
}
catch (IOException e) {
System.out.println("IOException:" + e);
}
catch (MalformedURLException e) {
System.out.println("MalformedURLException:" + e);
}
finally {
System.out.println("This is always displayed");
}
}
public void func1() throws IOException {

}
public void func2() throws MalformedURLException {

}
public void func3() throws IOException,
MalformedURLException {

}
}

Oracle10g: Java Programming B-15

Order Entry Solution

Copyright 2004, Oracle. All rights reserved.

S-ar putea să vă placă și