Вы находитесь на странице: 1из 385

Java Developer Courses

Introducing the Java


and Oracle Platforms
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
Key Benefits of Java

• Object-oriented
• Interpreted and platform-independent
• Dynamic and distributed
• Multithreaded
• Robust and secure
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 throughout the project
Integration
Analysis Design Implementation
and Testing

CLASS MODELS
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 JVM
(javac) (java)

Movie.java Movie.class Running


program
Using Java with Enterprise
Internet Computing
Web Application
Client server server Data
Business
Presentation
logic

• Servlets • Enterprise
JavaBeans (EJB)
• JavaServer
Pages (JSPs) • CORBA
Using the Java Virtual Machine

Operating system Operating system

Browser

JVM JVM

Application Applet
How Does the JVM Work?

• The class loader loads all required classes.


– Uses a CLASSPATH setting to locate class files
• The JVM Verifier checks for illegal bytecodes.
• The JVM Verifier executes bytecodes.
– May invoke a Just-In-Time (JIT) compiler
• The Memory Manager releases memory used by
the de-referenced object back to the OS.
– Garbage collection
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
Implementing Security
in the Java Environment

Language and compiler

Class loader

Bytecode verifier

Interface-specific access
What Are Java Applications?

• Client-side deployment:
– The 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.
Using Java with Oracle9i
Web Application
Client server server Data
Business
Presentation
logic

OC4J
Oracle
Oracle9i Database
Application Server

OC4J
The Java Software Development Kit

The Sun Java J2SE (known as JDK and Java SDK)


provides:
• Compiler (javac)
• Core class library
– classes.zip
– rt.jar
• Debugger (jdb)
• Bytecode interpreter: The JVM (java)
• Documentation generator (javadoc)
• Java Archive utility (jar)
• Others
Using the Appropriate Development Kit

Java2 comes in three sizes:


• J2ME (Micro Edition): Version specifically targeted
to 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
Integrated Development Environment

Development Debug

UML Exchange

Multitier Database

XML Synchronized changes HTML

SCM Deployment
Exploring the JDeveloper Environment

Command Area

Property
Viewer Project Navigator
Inspector
Oracle9i Products
Oracle9iDS Application Development
Oracle9iDS Business Intelligence
Defining Object-Oriented Principles
What Is Modeling?

• Models perform the following functions:


– Describe exactly what the business needs
– Facilitate discussion
– Prevent mistakes
• Modeling and implementation are treated
separately.
• Before coding can begin, the model must be
correct.
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
An Object’s 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.

INK

Object: Attribute:
my blue pen ink amount

Object: Attribute:
Acme Bank ATM cash available
Objects Have Behavior

• An object exists to provide behavior (functionality)


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

Object: Operation:
my blue pen write

Object: Operation:
Acme Bank ATM withdraw
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
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.

An ATM may have a


keyboard, card
reader, and cash A bank may have
A bank may be drawer, all of which an ATM, which
an object. may be objects. may be an object.
The Donut Diagram

Person

getName

getAge()
setBirthdate name getAge Message
address
birthdate

getAddress setAddress Client or


Sender
Guided Practice:
Spot the Operations and Attributes
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.
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.
• 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
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.
How Do You Identify a Class?

• Identify the common behavior and structure for a


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

My blue pen ops: write, refill


attribs: ink amount, color of ink

Your blue pen ops: write, refill


attribs: ink amount
Comparing Classes and Objects

• Classes are static definitions that we can use to


understand all the objects of that class.
• Objects are the dynamic entities that exist in the
real world and our 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.
What Is Encapsulation?

Encapsulation hides the internal structure and


operations of an object behind an interface.
• A bank ATM is an object that gives its users cash.
– The ATM hides (encapsulates) the actual operation
of withdrawal from the user.
– The interface (way to operate the ATM) is provided
by the keyboard functions, screen, cash dispenser,
and so on.
– Bypassing the encapsulation is bank robbery.
• Bypassing encapsulation in object-oriented
programming is impossible.
What Is Inheritance?

• There may be commonality between different


classes.
• Define the common properties in a superclass.

Account
Savings account Checking account

• The subclasses use inheritance to include those


properties.
Using the “Is-a-Kind-of” Relationship

• A subclass object
“is-a-kind-of”
superclass
object. Account Pen
• A subclass must
have all of the
attributes and
behaviors of the
superclass.

Savings account Pencil


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, but each object
implements the operation in a unique way
• Principles of inheritance and object substitution

Load passengers
Order Entry UML Diagram
Order Entry System
Partial UML Class Model
Order
Customer OrderItem
id: int
name: String orderDate: Date lineNo: int
address: String shipDate: Date quantity: int
phone: double shipMode: String price: double
getName() orderTotal: double
setName() getQuantity()
setAddress() addItem() setQuantity()
getAddress() removeItem() setPrice()
: setOrderDate() getPrice()
getOrderDate() getItemTotal()
setShipDate() :
:

Product
Company Individual id: int
name: String
contact: String description: String
discount: int licNumber: String
retailPrice: double
getContact() setLicNumber()
getPrice()
setContact() getLicNumber()
:
: :
Basic Java Syntax and Coding
Conventions
Examining Toolkit Components

The J2SE/J2EE from Sun provides:


• Compiler
• Appletviewer
• Bytecode interpreter
• Documentation generator
Exploring Packages in J2SE/J2EE

The Sun J2SE/J2EE provides standard packages for:


• Language
• Windowing
• Applet control
• Input/output
• Network communication
Documenting Using the J2SE

The J2SE/J2EE from Sun provides documentation


support for:
• Comments
– Implementation
– Documentation
• Documentation generator
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
• Filename must have the same name as the public
class or public interface
Establishing Naming Conventions

Naming conventions include:


• Filenames
– Customer.java, RentalItem.java
• Class names
– Customer, RentalItem, InventoryItem
• Method names
– getCustomerName(), setRentalItemPrice()
• Package names
– oracle.xml.xsql, java.awt, java.io
More on Naming Conventions

• Variables:
– customerName, customerCreditLimit
• Constants:
– MIN_WIDTH, MAX_NUMBER_OF_ITEMS
• Uppercase and lowercase characters
• Numerics and special characters
Defining a Class

Class definitions typically include:


• Access modifier
• Class keyword
• Instance fields
• Constructors
• Instance methods
• Class fields
• Class methods
Rental Class Example

Access modifier

public class Rental { Declaration


// Instance variables
int rentalId;
String rentalDate; Instance
float rentalAmountDue; variable

// Instance methods
float getAmountDue (int rentId) { 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");
}
}
Defining Java Methods

• Always within a class


• Specify:
– Access modifier
– Static keyword
– Arguments
– Return type

[access-modifiers] [static] <return-type>


<method-name> ([arguments]) {
return <java code block> …}
Examples of a Method

public float getAmountDue (String cust){ Declaration


// method variables
int numberOfDays;
Method
float due;
variables
float lateFee = 1.50F;
String customerName;
// method body
numberOfDays = this.getOverDueDays(); Method
statements
due = numberOfDays * lateFee;
customerName = getCustomerName(cust);
return due; Return
}
Styles for Declaring Variables

• You can declare variables anywhere in a class


block, and outside any method.
• You must declare variables before they are used
inside a method.
• It is typical to declare variables at the beginning of
a class block.
• The scope or visibility of variables is determined
in the code block.
• You must initialize method variables before using
them.
• Class and instance variables are automatically
initialized.
Examples of Variables
in the Context of a Method

public float getAmountDue (String cust) {


float due = 0; Method
variables
int numberOfDays = 0;
float lateFee = 1.50F;
{int tempCount = 1; // new code block
due = numberOfDays * lateFee;
tempCount++; Temporary
… variables
} // end code block
return due;
}
Rules for Creating Statements

• Use a semicolon to terminate statements.


• Define multiple statements within braces.
• Use braces for control statements.
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>

• Remember that case matters.


Examining the CLASSPATH variable

• Defined in the O/S


• Directs the JVM and Java applications where to
find .class files
• References built-in libraries or user-defined
libraries
• Interpreter searches paths and loads built-in
classes before user-defined classes
• Can be used with “javac” and “java” commands
CLASSPATH Example

Location of .class files

Setting CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les05\solution
Exploring Primitive Data Types
and Operators
Reserved Keywords

boolean abstract break class


byte final case extends
char native catch implements
double private continue interface
float protected default throws
int public do
long static else import
short synchronized finally package
void transient for
volatile if
instanceof
true strictfp return
new
false switch
super
null throw
this
try
while
Variable Types

• Eight primitive data types:


– Six numeric types
– A char type (for characters)
– A Boolean type (for truth values)
• User-defined types:
– Classes ab
– Interfaces c
– Arrays
Primitive Data Types

Floating True
Integer Character
Point False

byte
short float
char boolean
int double
long

1, 2, 3, 42 3.0F ‘a’ - '\141' true


07 .3337F '\u0061' False
0xff 4.022E23 '\n‘ false
0 0.0f ‘\u0000’

Append uppercase/lowercase L or F to the number to


specify a long or a floating number.
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; Initial value
boolean isAMovie;
float maxItemCost = 17.98F;
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;
}

• Variables can be initialized when declared.


Local Variables

• Method or 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
}
}
Defining Variable Names

• Variable names must start with a letter of the


alphabet, an underscore, or a $ symbol.
• Other characters may include digits.

a item_Cost item#Cost item-Cost


itemCost _itemCost item*Cost abstract
item$Cost itemCost2 2itemCost

• Use meaningful names for variables, such as


customerFirstName, ageNextBirthday.
What Are Numeric Literals?

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

0 1 42 -23795 (decimal)
02 077 0123 (octal)
Integer literals
0x0 0x2a 0X1FF (hex)
365L 077L 0x1000L (long)

1.0 4.2 .47


Floating-point
1.22e19 4.61E-9
literals
6.2f 6.21F
What Are the Nonnumeric Literals?

Boolean literals true/false //result not string

Character literals 'a' '\n' '\t' '\077‘ '\u006F'

String literals "Hello, world\n"


Guided Practice: Declaring Variables

Find the mistakes in this code and fix them.


1 byte sizeof = 200;
2 short mom = 43;
3 short hello mom;
4 int big = sizeof * sizeof * sizeof;
5 long bigger = big + big + big // ouch
6 double old = 78.0;
7 double new = 0.1;
8 boolean consequence = true;
9 boolean max = big > bigger;
10 char maine = "New England state";
11 char ming = 'd';
What Are Operators?

• Operators manipulate data and objects.


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

There are five types of operators:


• Assignment
• Arithmetic
• Integer bitwise
• Relational
• Boolean
Using the Assignment Operator

An assignment operator is an expression and can be


used whenever an expression is permitted.
• The expression on the right is assigned to the
variable 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;


Working with Arithmetic Operators

• Perform basic arithmetic operations


• Work on numeric variables and literals

int a, b, c, d;
a = 2 + 2; // addition
b = a * 3; // multiplication
c = b - 2; // subtraction
d = b / 2; // division
e = b % 2; // returns the remainder of division
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 type long, then the other is
also promoted to a long, and the result is of type
long.
• floats are promoted to doubles for floating point
calculations.

byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2; // ERROR: result is an int
// b3 is byte
Examining Conversions and Casts

• Java automatically converts a value of one


numeric type to a larger type.

byte
short
int
long
• Java does not automatically “downcast.”

byte short int long


Incrementing and Decrementing Values

• The ++/-- operators increment/decrement by 1:


int var1 = 3;
var1++; // var1 now equals 4

• The ++/-- 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.
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 now equals false
res = (var2 > var1); // res now equals true
Using the Conditional Operator (?:)

• Useful alternative to if…else:


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) ? 100 : 200;
System.out.println("Highest value is " + highest);
Using Logical Operators

Results of Boolean expressions can be combined by


using logical operators:

&& & and (with/without short-circuit evaluation)


|| | or (with/without short-circuit evaluation)
^ exclusive or
! not

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


boolean res = true;
res = (var2 > var1) & (var0 == 3); // now false
res = !res; // now true
Compound Assignments 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
Operator Precedence
Order Operators Comments Assoc.
1 ++ -- + - ~ Unary operators R
!(type)
2 * / % Multiply, divide, remainder L
3 + - + Add, subtract, add string L
4 << >> >>> Shift (>>> is zero-fill shift) L
5 < > <= >= Relational, type compare L
instanceof
6 == != Equality L
7 & Bit/logical AND L
8 ^ Bit/logical exclusive OR L
9 | Bit/logical inclusive OR L
10 && Logical AND L
11 || Logical OR L
12 ?: Conditional operator R
13 = op= Assignment operators R
More on Operator Precedence

• Operator precedence determines the order in


which operators are executed:

int var1 = 0;
var1 = 2 + 3 * 4; // var1 now equals 14

• Operators with the same precedence are executed


from left to right (see note in text below):

int var1 = 0;
var1 = 12 - 6 + 3; // var1 now equals 9

• Use parentheses to override the default order.


Concatenating Strings

The + operator creates and concatenates strings:

String name = "Jane ";


String lastName = "Hathaway";
String fullName;
name = name + lastName; // name is now
//"Jane Hathaway"
// OR
name += lastName ; // same result
fullName = name;
Controlling Program Flow
Categorizing Basic Flow Control Types

Flow control can be categorized into four types:

Sequential

Selection

Iteration

Transfer
Using Flow Control in Java

• Each simple statement terminates with a


semicolon (;).
• Group statements by using the braces { }.
• Each block executes as a single statement within
the flow of control structure.
{
boolean finished = true;
System.out.println("i = " + i);
i++;
}
Using the if Statement

if ( boolean_expr )
General : statement1;
[else
statement2];

if (i % 2 == 0)
System.out.println("Even");
Examples: else
System.out.println("Odd");
… if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed greater than or
equal to 25 but less than or equal to 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");
Guided Practice: Spot the Mistakes

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

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

int x = 14, y = 24; 3


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

switch ( integer_expr ) {

case constant_expr1:
statement1;
• Useful to
break;
select from
case constant_expr2:
several
statement2;
alternative
break;
integer values
[default: • Integer_expr
statement3;] must be byte,
} int, char, or
short.
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. }
Looping in Java

• There are three types of loops in Java:


– while
– do…while
– for
• All loops have four parts:
– Iteration condition
– Body
– Initialization
– Termination
Using the while Loop

while is the simplest loop statement and contains the


following general form:

while ( boolean_expr )
statement;

Example: int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Using the do…while Loop

do…while loops place the test at the end:


do
statement;
while ( termination );

int i = 0;
Example: do {
System.out.println("i = " + i);
i++;
} while (i < 10);
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?


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);
}
Guided Practice: Spot the Mistakes

int x = 10; 1
while (x > 0);
System.out.println(x--);
System.out.println("We have lift off!");

int x = 10; 2
while (x > 0)
System.out.println("x is " + x);
x--;

int sum = 0; 3
for (; i < 10; sum += i++);
System.out.println("Sum is " + sum);
Implementing 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 should be used sparingly


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

Comparing Labeled break
and continue Statements

Can be used to break out of nested loops or continue a


loop outside the current loop:

outer_loop:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
if (i + j > 7) break outer_loop;
if (i + j == 7) continue outer_loop;
System.out.println(i);
System.out.println(j);
}
}

Building Applications with Oracle9i
JDeveloper
What Is Oracle9i JDeveloper?

• Oracle9i JDeveloper provides an integrated


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

Command Area

Property
Editor System Navigator Inspector
Examining Workspaces

• Contain multiple projects


• View into currently used
objects
Workspace

Navigator
pane

Structure
pane
What Are Projects?

• Contain related files


• Manage project and
environment settings
• Manage compiler and
debug options

Project

Project
files
Creating JDeveloper Items

• Invoked with
File > New
• Categorized by type
• Create any
JDeveloper element
Creating an Application Project

In the Projects category, select Project Containing a


New Application
Specifying Project Details
Selecting Additional Libraries
Creating an Application

• Invoked after
project creation
• Specify:
– Name
– Package
– Extends
– Frame
• Invokes frame
details if adding
frame
Looking at the Directory Structure

JDeveloper creates and stores .java and .class files


using the following convention.
• <ORACLE_HOME>\jdev\mywork
• Followed by the workspace
name
• Followed by the project name
– \classes\<package name>\
– \src\<package_name>\
Exploring the Skeleton Java Application
Contains application and frame classes
Finding Methods and Fields

Find methods and fields using the Structure pane.


Supporting Code Development
with the 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
Using the Help System
Obtaining Help on a Topic

Use [F1] to invoke


context-specific Help.
Oracle9i JDeveloper Debugger

• Helps find and fix program errors:


– Run-time errors
– Logic errors
• Allows control of execution
• Allows examination of variables
Setting Breakpoints

Setting breakpoints:
• Manage multiple breakpoints
• Conditional breakpoints
• Define columns displayed in window
– Description
– Type
– Status, and so on
• Control scope of action
Global > Workspace > Project
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
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 a method call
• Step to the end of the method
• Pause execution
• Stop the debugger
Watching Data and Variables

• The Smart Data tab displays analyzed variables


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

New J2SE definitions include:


• Java executable
• A classpath
• A source path
• A doc path
Creating Classes and Objects
Using Java Classes

Methods Objects

Packages
Contained in a class

Object
Attributes references
Comparing Classes and Objects

• An object is an Movie
instance of a
class. public void displayDetails()
• Objects have their
public void setRating()
own memory.
• Class definitions private String title;
must be loaded to
private String rating;
create instances.

mov1 mov2
title: “Gone with…” title: “Last Action…”
rating: “PG” rating: “PG-13”
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…” title: “Last Action…”


rating: “PG” rating: “PG-13”
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 title: “Gone with…”


(when instantiated) rating: “PG”
Comparing Primitives and Objects

Primitive variables Object variables


hold a value. hold references.

int i; Movie mov1;


mov1
i 0
null

int j = 3; Movie mov1 = new Movie();

j 3 mov1
title: null
rating: null
Using the null Reference

• A special null value may be assigned to an object


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

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

mov1 = null; //Forget the Movie object
Assigning References

Assigning one reference to another results in two


references to the same object:

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


mov1

title: “Gone with…”


Movie mov2 = mov1; rating: “PG”

mov2
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();
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";
Guided Practice:
Creating and Using Objects
public class Movie {
public String title;
public class MovieTest { }
public static void main(String[] args) {
Movie mov1, mov2;

mov1.title = "Gone with the Wind";


mov2 = mov1;
mov2.title = "Last Action Hero";
System.out.println("Movie 1 is " + );
System.out.println("Movie 2 is " + );
}
}
Defining Methods

A method in Java is equivalent to a function or


subroutine in other languages.

modifier returnType methodName (argumentList) {


// method body

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

• 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.
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();
Use the dot if (r.equals("G")) …
operator:
Applying Encapsulation in Java

• Instance variables should be var


declared as private.
aMethod
• Only instance methods can access
private instance variables.
• private decouples the interface
aMethod()
of the class from its internal operation.

Movie mov1 = new Movie();


String rating = mov1.getRating();
String r = mov1.rating; // error: private
...
if (rating.equals("G"))
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);
}
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 = mov1


title: “Gone with…”
new Movie("Gone…"); rating: “PG”
mov1.setRating("PG");
anObj.aMethod(mov1);
ref2

public void aMethod(Movie ref2) {


ref2.setRating("R");
}
What Are Class Variables?

Class variables:
• Belong to a class and are common to all instances
of that class
• Are declared as static in class definitions
public class Movie {
private static double minPrice; // class var
private String title, rating; // inst vars

title
rating
min title
Price rating
title
rating
Movie class variable Movie objects
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;
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);
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 float getPrice() {
return price; Movie.setPrice(3.98f);
} Movie mov1 = new Movie(…);
} mov1.setPrice(3.98f);
float a = Movie.getPrice();
Legal or not? float b = mov1.getPrice();
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);
} …
Creating Classes Using the Class Editor
What Are Java Packages?

acmevideo

Copy Title Rental

Game Member Movie


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 contain the directory having
the root name of the package tree
– That the class name must be qualified by its
package name
Setting the CLASSPATH with Packages

The CLASSPATH includes the directory containing the


top level of the package tree:
Package name .class location

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

acmevideo acmetools

public public

protected

private
Object Life Cycle and Inner Classes
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);
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
}

title : null
void anyMethod() { mov1 rating: “PG”
Movie mov1 = new Movie();
Movie mov2 = new Movie(); title: null
mov1.setRating("PG"); … mov2 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;

• All instance variables are initialized implicitly to


default values depending on data type.
• More complex initialization should be placed in a
constructor.
What Are Constructors?

• For proper initialization, a class should provide a


constructor.
• A constructor is called automatically when an
object is created:
– Usually declared public
– Has the same name as the class
– No specified 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.
Defining and Overloading Constructors

public class Movie {


private String title;
private String rating = "PG";

public Movie() { The Movie class


title = "Last Action …"; now provides two
constructors.
}
public Movie(String newTitle) {
title = newTitle;
} Movie mov1 = new Movie();
} Movie mov2 = new Movie("Gone …");
Movie mov3 = new Movie("The Good …");
Sharing Code Between Constructors

Movie mov2 = new Movie();

public class Movie {


A constructor
private String title;
can call another
constructor by private String rating;
using this().
public Movie() {
this("G");
}
public Movie(String newRating) {
What happens rating = newRating;
here? }
}
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);

}
Reclaiming Memory

• When all references to an object are lost, the


object is marked for garbage collection.
• Garbage collection reclaims memory that is used
by the object.
• Garbage collection is automatic.
• There is no need for the programmer to do
anything, but the programmer can give a hint to
System.gc();.
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() { Any problems?
System.out.println("Goodbye");
}
}
Controlling Garbage Collection

Object reference types:


• Strong reference
• Soft reference Weaker
• Weak reference gradation
order
• Phantom reference
title: “Gone...”
mov1
rating: “PG”
Defining Removable Objects

Setting potentially removable


objects:
• Create a strong reference to an
object.
• Create a weaker reference to the
created object:
– SoftReference: For memory- ?
sensitive cache
– WeakReference: For objects
that you do not directly own
Delaying Memory Collection

Phantom references are used for delaying the reuse of


memory:
• Finalized object mov1

• Queued reference
mov1
• Memory still occupied
title: “Gone...”
• Unreachable object rating: “PG”
• poll() for existence
• clear() for memory
collection
What Are Inner Classes?

• Classes that are defined within a class


• Enforce a relationship between two
classes
• Are of four types:
– Static
– Member public class Outer { …
– Local class Inner { …
– Anonymous }
}

Enclosing class
Defining Static Inner Classes

• Defined at class level


• Access only static members of the outer class

public class Outer {

private static float varFloat = 3.50f;


private String varString;

static class InnerStatic {

}

}
Defining Member Inner Classes

• Defined at class level


• Instance of the outer class is needed
• Keyword this is used to access the outer
instance
public class Outer {

private static float varFloat = 3.50f;


private String varString;
...
class InnerMember {
...
outer.this
...
}
...
}
Defining Local Inner Classes

• Are defined at the method level


• Are declared within a code block
• Have access only to final variables
• Cannot have a constructor
public class Outer {
...
public void outerMethod(final int var1){
final int var2=5; ...
class InnerLocal {
private int localVar = var1 + var2; ...
}
}
}
Defining Anonymous Inner Classes

• Defined at method level


• Declared within a code block
• Lack the class, extends, and implements
keywords
• Cannot have a constructor
public class Outer {
...
public void outerMethod(){
SomeClass sc = new SomeClass();
...
myObject.myAnonymous(new SomeClass(){
...
} )
}
}
Using Strings, String Buffer, Wrapper,
and Text-Formatting Classes
What Is a String?

• String is a class.
• A String object holds a sequence of characters.
• String objects are read-only (immutable); their
values cannot be changed after creation.
• The String class represents all strings in Java.
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");
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);

• The String class has a concat() instance


method that can be used to concatenate strings.
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); String str = "Comedy";
char c = str.charAt(1);
• Return a substring of a string:
String substring String str = "Comedy";
(int beginIndex, String sub =
int endIndex); str.substring(2,4);
Performing More Operations on Strings

• Convert to uppercase or lowercase:


String toUpperCase(); String caps =
String toLowerCase(); str.toUpperCase();

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

• Find the index of a substring:


int indexOf (String str); int index =
int lastIndexOf str.indexOf("me");
(String str);
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

• Do not use ==.


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


object’s toString() method if a reference is
passed to it.
Movie mov = new Movie(…);
System.out.println(mov);
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);
Producing Primitives from Strings

• Use the primitive wrapper classes.


• There is one wrapper class for each primitive type:
– Integer wraps the int type
– Float wraps the float type
– Character wraps the char type
– Boolean wraps the boolean type
– And so on…
• Wrapper classes provide methods to convert a
String to a primitive, and primitives to a String.
Wrapper Class Conversion Methods

Example: Use the methods to process data from


fields as their declared.

String qtyVal = "17";


String priceVal = "425.00";
int qty = Integer.parseInt(qtyVal);
float price = Float.parseFloat(priceVal);
float itemTotal = qty * price;
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.
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
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 date-time formatting
• Uses time-pattern string to display the date:
– y year 1996
– M month in year July or 07
– m minute in hour 30
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};
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));
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"));
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();
About System.out.println

Understanding System.out.println()
• System is a class in the java.lang package.
• out is a public final static (class) variable.
– Declared as a PrintStream object reference
• println() is an overloaded method of the
PrintStream class.
– PrintStream is a FilterOutputStream that
subclasses OutputStream
• System.err is also provided as a PrintStream
object reference to write to standard error.
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
– Converts Unicode to environment byte encoding
– Terminates lines in platform independent way
– Flushes the output stream
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 all its fields are serializable, including
other objects referenced, or
– Using the transient modifier to prevent fields
from being saved and restored
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;

}

• Write object with java.io.ObjectOutputStream


• Read object with java.io.ObjectInputStream
Reusing Code with Inheritance
and Polymorphism
Key Object-Oriented Components

• Inheritance
• Constructors referenced by subclass
• Polymorphism
• Inheritance as an OO fundamental

Superclass
InventoryItem

Subclasses
Movie Game 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
Specifying Inheritance in Java

• Inheritance is achieved by specifying which


superclass the subclass extends.

public class InventoryItem {



}
public class Movie extends InventoryItem {

}

• Movie inherits all the variables and methods of


InventoryItem.
• If the extends keyword is missing, then the
java.lang.Object is the implicit superclass.
Defining Inheritance
by Using Oracle9i JDeveloper

• When specifying a class, JDeveloper asks for its


superclass:

• JDeveloper generates the code automatically.


What Does a Subclass Object
Look Like?

A subclass inherits all the instance variables of its


superclass.

public class InventoryItem {


Movie
private float price;
private String condition; …
price
}
condition
public class
Movie extends InventoryItem { title
private String title; length
private int length; …
}
Default Initialization

• What happens when a subclass


movie1
object is created?

price
Movie movie1 = new Movie(); condition

• If no constructors are defined: title


– First, the default no-arg length
constructor is called in the
superclass.
– Then, the default no-arg
constructor is called in the
subclass.
The super Reference

• Refers to the base, top-level class


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

public class InventoryItem {


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

}
}
class Movie extends InventoryItem {
Movie(String title) { Calls base
super(title); class
constructor

System.out.println("Movie");
}
}
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;
} …
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()…
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;
}
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);
}
Example of Polymorphism in Java

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


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

• 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.
Browsing Superclass References
by Using Oracle9i JDeveloper

Oracle9i JDeveloper makes it easy to browse the


contents of your superclass.

2
3
Acme Video and Polymorphism

• Acme Video started renting only videos.


• Acme Video added games and VCRs.
• What is next?
• Polymorphism solves the problem.
Using Polymorphism for Acme Video

InventoryItem
calcDeposit(){…}

VCR Movie
calcDeposit(){…} calcDeposit(){…}

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

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

}
Ensuring Genuine Inheritance

• Inheritance should 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 should make sense in
the subclass.
• Inheritance for short-term convenience leads to
problems in the future.
Using Arrays and Collections
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
[0] Action
[1] 2
[1] Comedy
[2] 4
[2] Drama
[3] 8
Creating an Array of Primitives

1. Declare the array. Null


arrayName
type[] arrayName;
… or …
type arrayName[]; 0
arrayName
0
type is a primitive, like int and so on.
0
2. Create the array object.
// Create array object syntax 1
arrayName = new type[size]; arrayName
2
3. Initialize the array elements
(optional). 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.
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.
• The contents of an array of primitives are [0]
initialized automatically. powers 0
[1]
0
[2]
0
0 [3]
Initializing Array Elements

• Assign values to individual elements.


arrayName[index] = value; 1 [0]
powers 0 [1]
powers[0] = 1;
0 [2]
• Create and initialize arrays at 0 [3]
the same time.
type[] arrayName = {valueList};
2 [0]
primes
int[] primes = {2, 3, 5, 7}; 3 [1]
5 [2]
7 [3]
Creating an Array of Object References

arrVar
1. Declare the array.
null
ClassName[] arrVar;
… or … arrVar
ClassName arrVar[]; null
null
null
2. Create the array object.
arrVar
Action
// Create array object syntax Comedy
arrVar = new ClassName[size];
Drama
3. Initialize the objects in the array.
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"};
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());

• An array element can be passed to any method;


array elements are passed by reference.
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();
Multidimensional Arrays

Java supports arrays of arrays:

type[][] arrayname = new type[n1][n2];

[0][0] [0][1]
int[][] mdarr = new int[4][2];
mdarr[0][0] = 1;
mdarr[0][1] = 7; mdarr
1 7
[0]
0 0
[1]
0 0
[2]
[3] 0 0
main()Revisited

• main() has a single parameter, args.


• args is an array of Strings that holds command-
line 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]);
} …
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);
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);
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();
Java Collections Framework

The Java Collections Framework is an API architecture


for managing a group of objects that can be
manipulated independently of their internal
implementation.
• 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
Collections Framework Components

The 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.
Using ArrayList and Hashtable

The ArrayList class:


• Is a resizable implementation of the List interface
• Allows manipulation of the array size
• Capacity grows as elements added to list
The Hashtable class:
• Is a legacy class similar to Map implementations,
but does not implement the Map interface
• 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
Using Enumerators to Implement Arrays

Enumerators are interfaces similar to arrays that group


like-typed data (for example:
java.util.Enumeration).
Enumerators:
• Implement more of an object-oriented approach
• Deal with their own memory allocation
• Adjust for changes in size
• Contain methods for iteration and traversal
Structuring Code by Using
Abstract Classes and Interfaces
Defining Abstract Classes

• An abstract class cannot be instantiated.


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

Abstract
InventoryItem
superclass

Concrete
Movie VCR
subclasses
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 public class Vcr


extends InventoryItem { extends InventoryItem {
private String title; private int serialNbr;
public int getLength()… public void setTimer()…
What Are Abstract Methods?

• An abstract method:
– Is an implementation placeholder
– Is part of an abstract class
– Must be overridden by a concrete subclass
• Each concrete subclass can implement the
method differently.
Defining Abstract Methods

• Use the abstract keyword to declare a method as


abstract:
– Provide the method signature only.
– The class must also be abstract.
• Why is this useful?
– Declare the structure of a given class without
providing complete implementation of every
method.
public abstract class InventoryItem {
public abstract boolean isRentable();

Defining and Using Interfaces

• An interface is like a fully abstract class:


– All of its methods are abstract.
– All variables are public static final.
• An interface lists a set of method signatures
without any code details.
• A class that implements the interface must
provide code details for all the methods of the
interface.
• A class can implement many interfaces but can
extend only one class.
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 Steerable
Creating Interfaces

• Use the interface keyword:


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

• All methods are public abstract.


• All variables are public static final.
Implementing Interfaces

Use the implements keyword.

public class Yacht extends Boat


implements Steerable
public void turnLeft(int deg) {…}
public void turnRight(int deg) {…}
}
Sort: A Real-World Example

• Is used by several unrelated classes


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

• Created by the sort expert:

public interface public abstract


Sortable class Sort

• Created by the movie expert:

public class Movie public class


implements Sortable MyApplication
How the Sort Works

MyApplication

sortObjects() MyApplication passes


returns the 4 1 an array of movies to
sorted list. Sort.sortObjects().

Sort
The movie sortObjects()
returns the asks a movie to
3 2
result of the compare itself with
comparison. another movie.
Movie
The Sortable Interface

Specifies the compare() method:

public interface Sortable {


// compare(): Compare this object to another object
// Returns:
// 0 if this object is equal to obj2
// a value < 0 if this object < obj2
// a value > 0 if this object > obj2
int compare(Object obj2);
}
The Sort Class

Holds sortObjects()

public abstract class Sort {


public static void sortObjects(Sortable[] items) {
// Step through the array comparing and swapping;
// do this length-1 times
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length - 1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempitem = items[j+1];
items[j+1] = items[j];
items[j] = tempitem; } } } } }
The 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));
}
}
Using the Sort

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


of Movie as the argument.

class myApplication {
Movie[] movielist;
… // build the array of Movie
Sort.sortObjects(movielist);
}
Using 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);
}
Throwing and Catching Exceptions
What Is an Exception?

An exception is an unexpected event.


How Does Java Handle Exceptions?

• A method throws an exception.


• A handler catches the exception.

Exception object

Handler
for this
Yes exception? No
Advantages of Java Exceptions:
Separating Error Handling Code

• In traditional programming, error handling often


makes code more confusing to read.
• Java separates the details of handling unexpected
errors from the main work of the program.
• The resulting code is clearer to read and,
therefore, less prone to bugs.
Advantages of Java Exceptions:
Passing Errors Up the Call Stack

Traditional error Java exceptions


handling
method1 Method1
//handle error Error //handle ex
code
method2 method2
Error
code Exception
method3 method3 ex
Error
method4 code method4

Each method checks for method4 throws an


errors and returns an error exception; method1
code to its calling method. catches it.
Advantages of Java Exceptions:
Exceptions Cannot Be Ignored

Traditional error Java exceptions


handling
method1 Method1
//handle error //handle ex

method2 method2
Exception
method3 method3 ex
Error
method4 code method4
If method3 ignores the The exception must be
error, then it will never be caught and handled
handled. somewhere.
Checked Exceptions, Unchecked
Exceptions, and Errors

All errors and exceptions extend the Throwable


class.
Throwable

Error Exception

Unrecoverable Checked RuntimeException


errors exceptions

Unchecked (run-time)
exceptions
What to Do with an Exception

• Catch the exception and handle it.


• Let the exception pass to the calling method.
• Catch the exception and throw a different
exception.
Catching and Handling Exceptions

• Enclose the method try {


call in a try block. // call the method
• Handle each }
exception in a catch catch (exception1) {
block. // handle exception1
• Perform any final }
processing in a catch (exception2) {
finally block. // handle exception2
}…
finally {
// any final processing
}
Catching a Single Exception

int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
Catching 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);
}
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();
}
Catching and Handling Exceptions:
Guided Practice
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}
Catching and Handling Exceptions:
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");
}
Allowing an Exception 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");
}
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();
}

}
Creating Exceptions

Extend the Exception class.

public class MyException extends Exception { … }

public class UserFileException extends Exception {


public UserFileException (String message) {
super(message);
}
}
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());
}
}
User Interface Design: Swing Basics
Planning the Application Layout
Running Java UI Applications
AWT, Swing, and JFC

• AWT, or Abstract Windowing 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)
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

JButton JSlider JTree

JComboBox JTextField JProgressBar


Lightweight or Heavyweight Components?

Heavyweight components Lightweight components


• Strong dependency on • No dependence on native
native peer code peer code
• Each rendered in its own • Can have transparent
opaque window backgrounds
• Early AWT components • Most Swing components
were mostly are lightweight
heavyweight • When displayed, they can
• Include some Swing appear nonrectangular
top-level components • Must be displayed in
(JFrame, JApplet, heavyweight container
JDialog)
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
The Containment Hierarchy

• Top-level containers Frame


– Frame
– Dialog
– Applet
• Intermediate containers
– Panel
– Scroll Pane
• Atomic components
– Label
Panel
– Text items Atomic
– Buttons components
– And so on …
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.
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
Atomic Components

• Buttons
• Check boxes
• Combo boxes
• Text
• Lists
• Labels
Layout Management Overview
Border Layout

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


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

• Is based on a grid
• Allows components to span multiple rows and
columns
• Allows rows and columns to differ in size
• Uses the component’s preferred size to control
cell size
GridBag Constraints

External insets

Component
Cell position padding

Cell span

Expansion
weighting Anchoring

Fill rules
Using Layout Managers

Using a layout manager with containers requires:


• Creating a container and a layout manager object
JFrame myFrame = new JFrame();
BorderLayout layoutMgr = new BorderLayout();

• Setting the layout property of the container


myFrame.setLayout(layoutMgr);

• Adding items (components or other containers)


into the regions that are defined by the layout
manager
myFrame.add(new JButton(), BorderLayout.NORTH);
myFrame.add(new JTextField(), BorderLayout.SOUTH);
myFrame.add(new JPanel(), BorderLayout.CENTER);
Combining Layout Managers

Border

null

Vertical-
Flow

GridBag

Grid
Using Frames or Dialogs

A Java frame is equivalent to an application window.


• Use the JFrame for a main window:
– Has properties for icons, title, window decorations
for minimize, maximize, and close buttons
– Uses BorderLayout by default
– Provides a default content pane that occupies the
center region of the layout
– Set frame size with the setSize() method, and
make it visible by using the setVisible() method.
• Use JDialog for a modal window:
– You must dismiss a modal window before the
application that invokes it can become active.
Using 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);
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 them with many components.
jPanel1.setBorder(BorderFactory.createBevelBorder(
BevelBorder.LOWERED,Color.lightGray,Color.darkGray));
Border etchedBorder =
BorderFactory.createEtchedBorder(); //pre-create a border
jPanel2.setBorder(etchedBorder); // use pre-created border`
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
Swing Text Controls
Adding Components
with Oracle9i JDeveloper

• Use the wizard to create a JFrame.


• Select a layout manager.
• Add components from the Swing toolbar.
• Fine-tune component properties.
Creating a Frame

Frame
Adding Components
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.
• 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.
Adding User Interface Components
and Event Handling
Swing Components

• Text controls
– JTextField
– JPasswordField
– JTextArea
– JEditorPane
– JTextPane
• Graphic controls
– JTree
– JTable
– JToggleButton
Swing Components in JDeveloper

Use the Swing pull-down menu to add components.


Invoking the UI Editor

Right-click and select UI Editor from the context menu.

System Context
Navigator menu

Code Editor
How to Add a Component to a Form

1: From the icon bar, select


the appropriate component.

2: Drop the component onto the form.


The class updates automatically.
Edit the Properties
of a Component

Change property values


in the Inspector.
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));
}
Creating a Menu

• Check “Create Menu Bar” during application


creation.
• Add a JMenuBar from the Component Palette.
• JDeveloper creates:
– JMenuBar for visual container for menus
– JMenu represents a menu of items, added to a menu
bar
– JMenuItems are placed in a JMenu
• 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.
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 Context menu when
structure from context menu options. right-clicking a menu item

Click
menu bar
object in
Structure pane
to display Context menu when
menu bar right-clicking a menu
Sample Order Entry Application
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:
– Create an event source object.
– Create an event listener object implementing an
interface with methods to handle the event object.
– Write an event-specific method to handle the event.
– Register the listener object with the event source
for the specified event.
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());
Event Handling Process:
Registration

Source
Event listener object

OK
Handler method

MyListener actionListenerObj = new MyListener();


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

}
Event Handling Process:
The Event Occurs

Source
Event listener object

OK
Notified Handler method

public interface ActionListener {


void actionPerformed(ActionEvent e);
}
Event Handling Process:
Running the Event Handler

Source
Event listener object

OK Handler method:
save changes and quit

public class MyListener


implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent …
}
Implementing an Event Listener
as an Inner Class

• You can implement and register the listener object


in one step.
• Implement the listener as an anonymous inner
class.
public void jbInit() {
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
}); … }
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
}
Swing Model View Controller Architecture

• Model, View, Controller principles


modify View
Event Controller View

modify 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.
• Always update Swing components on the event
thread queue, or use SwingUtilities methods.
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 component’s capabilities.
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. Use 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
What Events Can
a Component Generate?
Events that a
component can
generate

Event handler
methods
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.
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
}
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);
}
}
Example Menu and Code

Example menu visual representation:


• See code example in notes for the menu that is
displayed.

• Event handling for menu items is the same as that


for button objects. Use an ActionListener.
Building Components with JavaBeans
What Defines JavaBeans?
JavaBeans 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
Architecture Rules for Reuse

JavaBeans contain:
• Events that can interact with your Java application
• Properties that can be exposed
• Methods that can be invoked
JavaBeans support:
• Introspection/reflection
• Customization
• Persistence
Engineering for a Black Box Environment

Following the black box analogy, a JavaBean


approach 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
Managing Bean Properties

• Properties are the bean class member variables.


(Variables can be primitive types or objects.)
• A property can be:
– Unbound: A simple property
– Bound: Triggers an event when the field is altered
– Constrained: Changes are accepted or vetoed by
interested listener objects.
Exposing Properties and Methods

Getter Setter
private
methods T var; methods
(public) T[] arr; (public void)

T getVar() setVar(T val)

T[] getArr() setArr(T[] val)

boolean isVar() setVar(boolean val)


Event Handling with JavaBeans

A bean can fire events or listen for events from other


beans.

1 Bean registers
as a listener.

fireEvt() 2 Event is fired.

handleEvt() 3 Event handler


code is invoked.
JavaBeans 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
Introspection with JavaBeans

• Introspection is a mechanism that is used by a


visual tool to determine the properties, methods,
and events that a bean supports.
• The tool examines a bean to discover its
properties and events.
• Information is displayed in the Property Inspector
window.
JDeveloper
JavaBeans at Run Time

• Always runs in a single JVM


• Supports multithreaded access
• Detects presence or absence of GUI environment
• Locale-dependent controls
Differentiating JavaBeans, Java Classes,
and Widgets

• JavaBeans is packaged with design-time


information which enables design tools to expose
properties, methods, and events.
• JavaBeans are not restricted to any native
platform controls like widgets.
• JavaBeans are Java classes that can be
manipulated in a visual builder tool and included
in applications using introspection.
Building and Using a JavaBean
in JDeveloper: Overview

1. Develop a JavaBean
– Modified via code, class, or UI editors
2. Store the bean in an archive file
3. Create a JDeveloper library identifying the archive
4. Install the bean in JDeveloper’s Component
Palette, via its library name
5. Develop an application by using the JavaBean
component
1. Develop a JavaBean

1. Select File > New.


2. Expand the Client Tier - JavaBeans node.
3. Double-click the Bean icon.
Define the JavaBean

1. Specify the package name.


2. Enter the name of class: SearchPanel.
3. Select the parent class: FindPanel.

Select the
parent class
Add a Simple Property

1. In the Class Editor, select the Fields tab


2. Click the Add Field button Variable name

Type

Modifier
Add Events to a Bean

1. Select bean source file.


2. Select Class Editor > Events tab.

Fire Listen for


events events
2. Store the JavaBean in an Archive File

1. Create a deployment profile.


2. Include the JavaBean file in the deployment
profile.
3. Deploy the archive to a .jar file.
3. Create a JDeveloper Library Identifying
the Archive

1. Create a library to hold the


archived JavaBean.
2. Include the new library
containing the JavaBean in
the JDeveloper project.
4. Install the JavaBean in JDeveloper’s
Component Palette, via Its Library Name

1. Create a new page in the Component Palette for the


JavaBean.
2. Install the JavaBean on the page.
3. Confirm that your page and JavaBean are added to
the Component Palette.
5. Develop an Application Using the
JavaBean

1. In the UI Editor, add the JavaBean to the application.


2. Modify the properties to suit the needs of the
application.
3. Attach the JavaBean to an event.
Using JDBC to Access the Database
Java, J2EE, and Oracle9i
Web Application
Client server server Data
Business
Presentation
logic

Oracle9i Oracle
Application Server Database
J2EE Certified Environment

JDBC
Connecting to a Database with Java

Client applications, JSPs, and servlets use JDBC

Client application
JDBC Relational DB
or applet
What Is JDBC?

• JDBC is a standard interface for connecting to


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

• Include the Oracle JDBC driver archive file in the


CLASSPATH.
• The JDBC class library is part of the Java 2,
Standard Edition (J2SE).
Preparing the Environment

• Setting the PATH


[Oracle Home]\lib

• Setting the CLASSPATH


[Oracle Home]\jdbc\lib\classes12.jar
• Importing JDBC packages
// Standard packages
import java.sql.*;
import java.math.*; // optional
// Oracle extension to JDBC packages
import oracle.jdbc.*;
import oracle.sql.*;
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


5. Process query results
statement

4b. Process DML/ DDL


statement

6. Close connections
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>;
Connecting to the Database

Using the package oracle.jdbc.driver, Oracle


provides different drivers to establish a connection to
the database.

OracleDriver
Database
JDBC calls commands
• Thin client
• OCI Database
• Server Based
•…
Oracle JDBC Drivers: Thin Client Driver

• Written entirely in Java


• Must be used by applets

Applet

JDBC

Thin driver Oracle 9i

Client Server
Oracle JDBC Drivers: OCI Client Drivers

• Written in C and Java


• Must be installed on the client

Application

JDBC

OCI driver

Oracle 9i
ocixxx.dll

Client Server
Choosing the Right Driver

Type of Program Driver

Applet Thin

Client application Thin OCI

Thin
EJB, servlet
(on the middle tier)
OCI

Stored procedure Server side


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

• Vendors can provide different types of JDBC


drivers.
About JDBC URLs

• JDBC uses a URL like string. The URL identifies


– The JDBC driver to use for the connection
– Database connection details, which varies
depending on the driver used.

jdbc:<subprotocol>:<subname>
Database Identification
Protocol

jdbc:oracle:<driver>:@<database>
• Example using Oracle Thin JDBC driver:
– jdbc:oracle:thin:@myhost:1521:ORCL
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"
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();
Step 4: Executing SQL Statements

1. Register JDBC driver

2. Obtain a connection

3. Create statement object

4. Execute SQL statement

4a. Execute SELECT


5. Process query results
statement

4b. Submit DML/ DDL


statement
6. Close unneeded objects
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/DDL.
– Returns an int
• Use execute(String) for any SQL statement.
– Returns a boolean value
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");
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
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");
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)");
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"));
}
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();
}
}
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();
...
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);

Column Name Type Method

empno NUMBER getInt()

hiredate DATE getDate()

job VARCHAR2 getString()


Handling an Unknown SQL Statement

1. Create an empty statement object.


Statement stmt = conn.createStatement();

2. Use execute to execute the statement.


boolean result = stmt.execute(SQLstatement);
3. Process the statement accordingly.
if (result) { // was a query - process results
ResultSet r = stmt.getResultSet(); ...
}
else { // was an update or DDL - process result
int count = stmt.getUpdateCount(); ...
}
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 */ }
...
Managing Transactions

• By default connections are in auto commit 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(): Rollback a transaction
• Closing a connection commits the transaction
even with the autocommit off option
The PreparedStatement Object

• 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.
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 = ?");
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();
Maximize Database Access

• 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.
Connection Pooling
Middle tier

Java servlet

Data source

Middle-tier server code

ConnectionPoolDataSource
JDBC
driver Database

Database
commands
Deploying Applications Using
Java Web Start
What Is Java Web Start?

• Application deployment technology based on the


Java 2 platform.
• Launches full-featured applications via any
browser on any platform, from anywhere on the
Web.
Running a Web Start Application

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

HTTP
3
HTTP

2 4
Advantages of Web Start

• Renders a very responsive and rich UI


• Launches applications from the Start menu on the
desktop
• Doesn’t require browser to be running
• Applications work offline
• Automatically updates applications when invoked
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
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
Creating the Deployment Profile File

Select the File > New


Saving the Deployment Profile

Select a destination and name for the deployment profile.


Selecting Files to Deploy

• Always select the file types to include. Other


settings differ for other deployment profile types.
Making an Executable .jar File

Set the Main Class field to the class name containing a


main() method, in JAR Options.
Creating and Deploying the Archive File

Right-click the Deployment Profile file.


• Select the Deploy to menu option.
• Specify the directory location for the jar file.
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
Step 1: Generate Deployment Profiles and
Archive Application

Package all the Java


application files into a
simple .jar archive.
Step 2a: Start OC4J and Create a
Connection

• Use the command line to start the server.

• Use JDeveloper to create a connection. Define a


connection type, transport URL, target Web site
and home OC4J directory.
Step 2b: Creating a Connection

Use the Connection Wizard to create a connection to


the application server. You need to specify:
• The type of connection (OC4J)
• The username/password for
authentication
• Local URL, target Web site
and local directory for OC4J
Step 3: Use Web Start Wizard to Create
a JNLP File

• Specify the Web Start name, application archive


(.jar), main application class

• Include information to be displayed to the user


while downloading (for example, application title,
vendor and brief description)
Step 4: Archive and Deploy the Application
to the OC4J Server

• Specify properties of the Web components and


deployment description.

• Deploy to the OC4J connection created in step 2.


• Run the generated HTML file.

Вам также может понравиться