java and oracle combined

385
Java Developer Courses

Upload: rampratapsinghchauha

Post on 27-Apr-2015

85 views

Category:

Documents


0 download

DESCRIPTION

Implementing java with oracle

TRANSCRIPT

Page 1: Java and Oracle Combined

Java Developer Courses

Page 2: Java and Oracle Combined

Introducing the Javaand Oracle Platforms

Page 3: Java and Oracle Combined

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

Page 4: Java and Oracle Combined

Key Benefits of Java

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

Page 5: Java and Oracle Combined

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 projectAnalysis Implementation Integration

and TestingDesign

CLASS MODELS

Page 6: Java and Oracle Combined

Platform Independence

• Java source code is stored as text in a .java file.• The .java file is compiled into .class files.• A .class file contains Java bytecodes

(instructions).• The bytecodes are interpreted at run time.

– The Java .class file is the executable code.

Compile

Movie.java

JVM

Running program

Movie.class

(javac) (java)

Page 7: Java and Oracle Combined

Using Java with EnterpriseInternet Computing

Web serverClient

Application server

Presentation Businesslogic

• Servlets

• JavaServerPages (JSPs)

• EnterpriseJavaBeans (EJB)

• CORBA

Data

Page 8: Java and Oracle Combined

Using the Java Virtual Machine

Operating system

JVM

Application

Operating system

Browser

JVM

Applet

Page 9: Java and Oracle Combined

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

Page 10: Java and Oracle Combined

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

Page 11: Java and Oracle Combined

Implementing Securityin the Java Environment

Interface-specific access

Class loader

Bytecode verifier

Language and compiler

Page 12: Java and Oracle Combined

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.

Page 13: Java and Oracle Combined

OracleDatabase

Using Java with Oracle9i

DataWeb

serverClientApplication

server

Presentation Businesslogic

Oracle9iApplication Server

OC4J

OC4J

Page 14: Java and Oracle Combined

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

Page 15: Java and Oracle Combined

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

Page 16: Java and Oracle Combined

Integrated Development Environment

Development

UML

Multitier

XML

SCM

Debug

Exchange

Database

HTML

Deployment

Synchronized changes

Page 17: Java and Oracle Combined

Exploring the JDeveloper Environment

Command Area

Project NavigatorViewer Property Inspector

Page 18: Java and Oracle Combined

Oracle9i Products

Page 19: Java and Oracle Combined

Oracle9iDS Application Development

Page 20: Java and Oracle Combined

Oracle9iDS Business Intelligence

Page 21: Java and Oracle Combined

Defining Object-Oriented Principles

Page 22: Java and Oracle Combined

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.

Page 23: Java and Oracle Combined

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

Page 24: Java and Oracle Combined

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

Attribute:ink amount

Attribute:cash available

Object:my blue pen

Object:Acme Bank ATM

Page 25: Java and Oracle Combined

Objects Have Behavior

• An object exists to provide behavior (functionality) to the system.

• Each distinct behavior is called an operation.

Object:my blue pen

Operation:write

Object:Acme Bank ATM

Operation:withdraw

Page 26: Java and Oracle Combined

Objects Are Modeled as Abstractions

• A Java object is modeled as an abstract representation of a real-world object.

• Model only those attributes and operations that are relevant to the context of the problem.

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

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

Context: Product catalogReal-world attributes/operations that you may want to model:

• Attributes: Model, manufacturer, price• Operations: Change price

Page 27: Java and Oracle Combined

A bank may be an object.

A bank may have an ATM, which

may be an object.

An ATM may have a keyboard, card

reader, and cash drawer, all of which

may be objects.

Defining Object Composition

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

aggregation.

Page 28: Java and Oracle Combined

The Donut Diagram

getAge()

Client orSender

Person

Messagenameaddressbirthdate

getName

setBirthdate getAge

getAddress setAddress

Page 29: Java and Oracle Combined

Guided Practice:Spot the Operations and Attributes

Page 30: Java and Oracle Combined

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.

Page 31: Java and Oracle Combined

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

Page 32: Java and Oracle Combined

When you create my blue pen, you do not have to specify its operations or attributes. You simply

say what class it belongs to.

What Is a Class?

• A class is a template for objects.• A class definition specifies the operations and

attributes for all instances of that class.• A class is used to manage complexity.

Page 33: Java and Oracle Combined

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, refillattribs: ink amount, color of ink

Your blue pen ops: write, refillattribs: ink amount

Page 34: Java and Oracle Combined

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.

Page 35: Java and Oracle Combined

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.

Page 36: Java and Oracle Combined

What Is Inheritance?

• There may be commonality between different classes.

• Define the common properties in a superclass.

• The subclasses use inheritance to include those properties.

Savings account Checking account

Account

Page 37: Java and Oracle Combined

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

• A subclass object “is-a-kind-of” superclass object.

• A subclass must have all of the attributes and behaviors of the superclass.

Savings account

Account Pen

Pencil

Page 38: Java and Oracle Combined

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

Page 39: Java and Oracle Combined

Order Entry UML Diagram

Page 40: Java and Oracle Combined

Order Entry SystemPartial UML Class Model

Order

id: intorderDate: DateshipDate: DateshipMode: StringorderTotal: double

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

OrderItemlineNo: intquantity: intprice: double

getQuantity()setQuantity()setPrice()getPrice()getItemTotal():

Customername: Stringaddress: Stringphone: doublegetName()setName()setAddress()getAddress():

Companycontact: Stringdiscount: int

getContact()setContact():

Individual

licNumber: String

setLicNumber()getLicNumber():

Productid: intname: Stringdescription: StringretailPrice: double

getPrice():

Page 41: Java and Oracle Combined

Basic Java Syntax and Coding Conventions

Page 42: Java and Oracle Combined

Examining Toolkit Components

The J2SE/J2EE from Sun provides:• Compiler• Appletviewer• Bytecode interpreter• Documentation generator

Page 43: Java and Oracle Combined

Exploring Packages in J2SE/J2EE

The Sun J2SE/J2EE provides standard packages for:• Language• Windowing• Applet control• Input/output• Network communication

Page 44: Java and Oracle Combined

Documenting Using the J2SE

The J2SE/J2EE from Sun provides documentation support for:• Comments

– Implementation– Documentation

• Documentation generator

Page 45: Java and Oracle Combined

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

Page 46: Java and Oracle Combined

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

Page 47: Java and Oracle Combined

More on Naming Conventions

• Variables:– customerName, customerCreditLimit

• Constants:– MIN_WIDTH, MAX_NUMBER_OF_ITEMS

• Uppercase and lowercase characters• Numerics and special characters

Page 48: Java and Oracle Combined

Defining a Class

Class definitions typically include:• Access modifier• Class keyword• Instance fields• Constructors• Instance methods• Class fields• Class methods

Page 49: Java and Oracle Combined

Rental Class Example

public class Rental {

// Instance variables

int rentalId;

String rentalDate;

float rentalAmountDue;

// Instance methods

float getAmountDue (int rentId) {

}

}

Declaration

Instance variable

Instance method

Access modifier

Page 50: Java and Oracle Combined

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

}

}

Page 51: Java and Oracle Combined

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> …}

Page 52: Java and Oracle Combined

Examples of a Method

public float getAmountDue (String cust){

// method variables

int numberOfDays;

float due;

float lateFee = 1.50F;

String customerName;

// method body

numberOfDays = this.getOverDueDays();

due = numberOfDays * lateFee;

customerName = getCustomerName(cust);

return due;

}

Declaration

Methodvariables

Methodstatements

Return

Page 53: Java and Oracle Combined

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.

Page 54: Java and Oracle Combined

Examples of Variablesin the Context of a Method

public float getAmountDue (String cust) {

float due = 0;

int numberOfDays = 0;

float lateFee = 1.50F;

{int tempCount = 1; // new code block

due = numberOfDays * lateFee;

tempCount++;

} // end code block

return due;

}

Method variables

Temporary variables

Page 55: Java and Oracle Combined

Rules for Creating Statements

• Use a semicolon to terminate statements.• Define multiple statements within braces.• Use braces for control statements.

Page 56: Java and Oracle Combined

Compiling and Runninga Java Application

• To compile a .java file:

• To execute a .class file:

• Remember that case matters.

prompt> javac SayHello.java

… compiler output …

prompt> java SayHello

Hello world

prompt>

Page 57: Java and Oracle Combined

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

Page 58: Java and Oracle Combined

CLASSPATH Example

C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les05\solution

Setting CLASSPATH

Location of .class files

Page 59: Java and Oracle Combined

Exploring Primitive Data Typesand Operators

Page 60: Java and Oracle Combined

Reserved Keywords

abstractfinalnativeprivateprotectedpublicstaticsynchronizedtransientvolatilestrictfp

breakcasecatchcontinuedefaultdoelsefinallyforifreturnswitchthrowtrywhile

booleanbytechardoublefloatintlongshortvoid

true falsenull

classextendsimplementsinterfacethrows

instanceofnewsuperthis

importpackage

Page 61: Java and Oracle Combined

Variable Types

• Eight primitive data types:– Six numeric types– A char type (for characters)– A Boolean type (for truth values)

• User-defined types:– Classes– Interfaces– Arrays

a b c

Page 62: Java and Oracle Combined

Primitive Data Types

Append uppercase/lowercase L or F to the number to specify a long or a floating number.

Integer FloatingPoint Character True

False

byteshort

intlong

floatdouble char boolean

1, 2, 3, 4207

0xff0

3.0F.3337F

4.022E230.0f

‘a’ - '\141''\u0061'

'\n‘‘\u0000’

trueFalsefalse

Page 63: Java and Oracle Combined

What Are Variables?

• A variable is a basic unit of storage.• Variables must be explicitly declared.• Each variable has a type, an identifier, and a

scope.• There are three types of variables: class, instance,

and method.

int myAge;

boolean isAMovie;

float maxItemCost = 17.98F;

TypeIdentifier

Initial value

title: “Blue Moon”

Page 64: Java and Oracle Combined

Declaring Variables

• Basic form of variable declaration:– type identifier [ = value];

• Variables can be initialized when declared.

public static void main(String[] args) {

int itemsRented = 1;

float itemCost;

int i, j, k;

double interestRate;

}

Page 65: Java and Oracle Combined

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

}

}

Page 66: Java and Oracle Combined

Defining Variable Names

• Variable names must start with a letter of the alphabet, an underscore, or a $ symbol.

• Other characters may include digits.

• Use meaningful names for variables, such ascustomerFirstName, ageNextBirthday.

a item_Cost

itemCost _itemCost

item$Cost itemCost2

item#Cost item-Cost

item*Cost abstract

2itemCost

Page 67: Java and Oracle Combined

What Are Numeric Literals?

0 1 42 -23795 (decimal)

02 077 0123 (octal)

0x0 0x2a 0X1FF (hex)

365L 077L 0x1000L (long)

1.0 4.2 .471.22e19 4.61E-9

6.2f 6.21F

Integer literals

Floating-point literals

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

Page 68: Java and Oracle Combined

What Are the Nonnumeric Literals?

true/false //result not string

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

"Hello, world\n"

Boolean literals

String literals

Character literals

Page 69: Java and Oracle Combined

Guided Practice: Declaring Variables

Find the mistakes in this code and fix them.byte sizeof = 200;

short mom = 43;

short hello mom;

int big = sizeof * sizeof * sizeof;

long bigger = big + big + big // ouch

double old = 78.0;

double new = 0.1;

boolean consequence = true;

boolean max = big > bigger;

char maine = "New England state";

char ming = 'd';

1

2

3

4

5

6

7

8

9

10

11

Page 70: Java and Oracle Combined

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.

Page 71: Java and Oracle Combined

Categorizing Operators

There are five types of operators:• Assignment• Arithmetic• Integer bitwise• Relational• Boolean

Page 72: Java and Oracle Combined

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:

• The expression on the right is always evaluated before the assignment.

• Assignments can be strung together:

int var1 = 0, var2 = 0;

var1 = 50; // var1 now equals 50

var2 = var1 + 10; // var2 now equals 60

var1 = var2 = var3 = 50;

Page 73: Java and Oracle Combined

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

Page 74: Java and Oracle Combined

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 typelong.

• 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

Page 75: Java and Oracle Combined

Examining Conversions and Casts

• Java automatically converts a value of one numeric type to a larger type.

• Java does not automatically “downcast.”

byte shortint

long

byte longintshort

Page 76: Java and Oracle Combined

Incrementing and Decrementing Values

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

• The ++/-- operators can be used in two ways:

int var1 = 3;

var1++; // var1 now equals 4

int var1 = 3, var2 = 0;

var2 = ++var1; // Prefix: Increment var1 first,

// then assign to var2.

var2 = var1++; // Postfix: Assign to var2 first,

// then increment var1.

Page 77: Java and Oracle Combined

greater thangreater than or equal toless thanless than or equal toequal tonot equal to

>>=<<===!=

Relational and Equality Operators

int var1 = 7, var2 = 13;

boolean res = true;

res = (var1 == var2); // res now equals false

res = (var2 > var1); // res now equals true

Page 78: Java and Oracle Combined

Using the Conditional Operator (?:)

• Useful alternative to if…else:

• If boolean_expr is true, the result is expr1, otherwise the result is expr2:

boolean_expr ? expr1 : expr2

int val1 = 120, val2 = 0;

int highest;

highest = (val1 > val2) ? 100 : 200;

System.out.println("Highest value is " + highest);

Page 79: Java and Oracle Combined

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 ornot

&& &|| |^!

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

boolean res = true;

res = (var2 > var1) & (var0 == 3); // now false

res = !res; // now true

Page 80: Java and Oracle Combined

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

Page 81: Java and Oracle Combined

Operator Precedence

Operators

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

Comments

Unary operators

Multiply, divide, remainderAdd, subtract, add stringShift (>>> is zero-fill shift)Relational, type compare

EqualityBit/logical ANDBit/logical exclusive ORBit/logical inclusive ORLogical ANDLogical ORConditional operatorAssignment operators

Order

1

2345

67 8910111213

Assoc.

R

LLLL

LLLLLLRR

Page 82: Java and Oracle Combined

More on Operator Precedence

• Operator precedence determines the order in which operators are executed:

• Operators with the same precedence are executed from left to right (see note in text below):

• Use parentheses to override the default order.

int var1 = 0;

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

int var1 = 0;

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

Page 83: Java and Oracle Combined

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;

Page 84: Java and Oracle Combined

Controlling Program Flow

Page 85: Java and Oracle Combined

Categorizing Basic Flow Control Types

Flow control can be categorized into four types:

Sequential

Transfer

Selection

Iteration

Page 86: Java and Oracle Combined

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++;

}

Page 87: Java and Oracle Combined

Using the if Statement

if ( boolean_expr )

statement1;

[else

statement2];

if (i % 2 == 0)

System.out.println("Even");

else

System.out.println("Odd");

… if (i % 2 == 0) {

System.out.print(i);

System.out.println(" is even");

}

General :

Examples:

Page 88: Java and Oracle Combined

Nesting if Statementsif (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");

Page 89: Java and Oracle Combined

Guided Practice: Spot the Mistakes

int x = 3, y = 5;

if (x >= 0)

if (y < x)

System.out.println("y is less than x");

else

System.out.println("x is negative");

int x = 7;

if (x = 0)

System.out.println("x is zero");

int x = 14, y = 24;

if ( x % 2 == 0 && y % 2 == 0 );

System.out.println("x and y are even");

1

2

3

Page 90: Java and Oracle Combined

Defining the switch Statement

• Useful to select from several alternative integer values

• Integer_exprmust be byte, int, char, or short.

switch ( integer_expr ) {

case constant_expr1:

statement1;

break;

case constant_expr2:

statement2;

break;

[default:

statement3;]

}

Page 91: Java and Oracle Combined

More About the switch Statement

• Case labels must be constants.

• Use break to jump out of a switch.

• It is recommended to always provide a default.

switch (choice) {

case 37:

System.out.println("Coffee?");

break;

case 45:

System.out.println("Tea?");

break;

default:

System.out.println("???");

}

Page 92: Java and Oracle Combined

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

Page 93: Java and Oracle Combined

Using the while Loop

while is the simplest loop statement and contains the following general form:

Example:

while ( boolean_expr )

statement;

int i = 0;

while (i < 10) {

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

i++;

}

Page 94: Java and Oracle Combined

Using the do…while Loop

do…while loops place the test at the end:

Example:

do

statement;

while ( termination );

int i = 0;

do {

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

i++;

} while (i < 10);

Page 95: Java and Oracle Combined

Using the for Loop

for loops are the most common loops:

Example:

How would this for loop look using a while loop?

for (i = 0; i < 10; i++)

System.out.println(i);

for ( initialization; termination; iteration )

statement;

Page 96: Java and Oracle Combined

More About the for Loop

• Variables can be declared in the initialization part of a for loop:

• Initialization and iteration can consist of a list of comma-separated expressions:

for (int i = 0; i < 10; i++)

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

for (int i = 0, j = 10; i < j; i++, j--) {

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

System.out.println("j = " + j);

}

Page 97: Java and Oracle Combined

Guided Practice: Spot the Mistakes

int x = 10;

while (x > 0);

System.out.println(x--);

System.out.println("We have lift off!");

int x = 10;

while (x > 0)

System.out.println("x is " + x);

x--;

int sum = 0;

for (; i < 10; sum += i++);

System.out.println("Sum is " + sum);

1

2

3

Page 98: Java and Oracle Combined

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++;

}…

Page 99: Java and Oracle Combined

Comparing Labeled breakand 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);

}

}

Page 100: Java and Oracle Combined

Building Applications with Oracle9iJDeveloper

Page 101: Java and Oracle Combined

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.

Page 102: Java and Oracle Combined

Exploring the JDeveloper Environment

System NavigatorEditorProperty Inspector

Command Area

Page 103: Java and Oracle Combined

Examining Workspaces

• Contain multiple projects• View into currently used

objectsWorkspace

Navigator pane

Structure pane

Page 104: Java and Oracle Combined

What Are Projects?

• Contain related files• Manage project and

environment settings • Manage compiler and

debug options

Project

Projectfiles

Page 105: Java and Oracle Combined

Creating JDeveloper Items

• Invoked withFile > New

• Categorized by type• Create any

JDeveloper element

Page 106: Java and Oracle Combined

Creating an Application Project

In the Projects category, select Project Containing a New Application

Page 107: Java and Oracle Combined

Specifying Project Details

Page 108: Java and Oracle Combined

Selecting Additional Libraries

Page 109: Java and Oracle Combined

Creating an Application

• Invoked after project creation

• Specify:– Name– Package– Extends– Frame

• Invokes frame details if adding frame

Page 110: Java and Oracle Combined

Looking at the Directory Structure

JDeveloper creates and stores .java and .class files using the following convention.• <ORACLE_HOME>\jdev\mywork

• Followed by the workspacename

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

Page 111: Java and Oracle Combined

Exploring the Skeleton Java Application

Contains application and frame classes

Page 112: Java and Oracle Combined

Finding Methods and Fields

Find methods and fields using the Structure pane.

Page 113: Java and Oracle Combined

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

Page 114: Java and Oracle Combined

Using the Help System

Page 115: Java and Oracle Combined

Obtaining Help on a Topic

Use [F1] to invoke context-specific Help.

Page 116: Java and Oracle Combined

Oracle9i JDeveloper Debugger

• Helps find and fix program errors:– Run-time errors– Logic errors

• Allows control of execution• Allows examination of variables

Page 117: Java and Oracle Combined

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

Page 118: Java and Oracle Combined

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

Page 119: Java and Oracle Combined

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

Page 120: Java and Oracle Combined

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.

Page 121: Java and Oracle Combined

Adding a New J2SE

New J2SE definitions include:• Java executable• A classpath• A source path • A doc path

Page 122: Java and Oracle Combined

Creating Classes and Objects

Page 123: Java and Oracle Combined

Using Java Classes

Packages

Methods Objects

ObjectreferencesAttributes

Contained in a class

Page 124: Java and Oracle Combined

title: “Gone with…”rating: “PG”

title: “Last Action…”rating: “PG-13”

Comparing Classes and Objects

public void displayDetails()

private String title;

private String rating;

public void setRating()

Movie• An object is an instance of a class.

• Objects have their own memory.

• Class definitions must be loaded to create instances.

mov1 mov2

Page 125: Java and Oracle Combined

Creating Objects

• Objects are typically created by using the new operator:

• For example, to create two Movie objects:

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

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

ClassName objectRef = new ClassName();

title: “Gone with…”rating: “PG”

title: “Last Action…”rating: “PG-13”

Page 126: Java and Oracle Combined

title: “Gone with…”rating: “PG”

Using the new Operator

The new operator performs the following actions:• Allocates and initializes memory for the new

object• Calls a special initialization method in the class,

called a constructor• Returns a reference to the new object

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

mov1(when instantiated)

Page 127: Java and Oracle Combined

Comparing Primitives and Objects

Primitive variables hold a value.

int i;

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

Object variableshold references.

title: nullrating: null

mov1

Movie mov1;

mov10

3

i

j

null

Page 128: Java and Oracle Combined

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

Page 129: Java and Oracle Combined

Assigning References

Assigning one reference to another results in two references to the same object:

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

mov1

Movie mov2 = mov1;

mov2

title: “Gone with…”rating: “PG”

Page 130: Java and Oracle Combined

title: nullrating: null

title: nullrating: null

Declaring Instance Variables

Instance variables are declared within the class but outside the methods or instance or static intializers.public class Movie {

public String title;

public String rating;

public float getPrice(){

return price;

}

}

Movie mov1 = new Movie();

Movie mov2 = new Movie();

mov2

mov1

Create movies:

Page 131: Java and Oracle Combined

Accessing public Instance Variables

public instance variables can be accessed by usingthe 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";

Page 132: Java and Oracle Combined

Guided Practice:Creating and Using Objects

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

}

}

public class Movie {

public String title;

}

Page 133: Java and Oracle Combined

Defining Methods

A method in Java is equivalent to a function or subroutine in other languages.

modifier returnType methodName (argumentList) {

// method body

};

Page 134: Java and Oracle Combined

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

Page 135: Java and Oracle Combined

Specifying Method Arguments: Examples

• Specify the number and type of arguments in the method definition:

• If the method takes no arguments, then leave the parentheses empty:

public void displayDetails() {

System.out.println("Title is " + title);

System.out.println("Rating is " + rating);

}

public void setRating(String newRating) {

rating = newRating;

}

Page 136: Java and Oracle Combined

Returning a Value from a Method

• Use a return statement to exit a method and to return a value from a method:

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

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

public class Movie {

private String rating;

public String getRating () {

return rating;

}

}

Page 137: Java and Oracle Combined

Calling Instance Methods

public class Movie {

private String title, rating;

public String getRating(){

return rating;

}

public void setRating(String newRating){

rating = newRating;

}

}Movie mov1 = new Movie();

String r = mov1.getRating();

if (r.equals("G")) … Use the dotoperator:

Page 138: Java and Oracle Combined

Applying Encapsulation in Java

• Instance variables should be declared as private.

• Only instance methods can access private instance variables.

• private decouples the interface of the class from its internal operation.

Movie mov1 = new Movie();

String rating = mov1.getRating();

String r = mov1.rating; // error: private

...

if (rating.equals("G"))

var

aMethod

aMethod()

Page 139: Java and Oracle Combined

Passing Primitives into Methods

When a primitive or object reference value is passed into a method, a copy of the value is generated:

public void aMethod(int arg) {

if (arg < 0 || arg > 100)

arg = 0;

System.out.println("arg: " + arg);

}

int num = 150;

anObj.aMethod(num);

System.out.println("num: " + num);

num150

arg150

Page 140: Java and Oracle Combined

title: “Gone with…”rating: “PG”

Passing Object References into Methods

When an object reference is passed into a method, the object is not copied but the pointer to the object is copied:

public void aMethod(Movie ref2) {

ref2.setRating("R");

}

mov1

ref2

Movie mov1 =

new Movie("Gone…");

mov1.setRating("PG");

anObj.aMethod(mov1);

Page 141: Java and Oracle Combined

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 definitionspublic class Movie {

private static double minPrice; // class var

private String title, rating; // inst vars

Movie class variable Movie objects

titlerating

titlerating title

ratingmin

Price

Page 142: Java and Oracle Combined

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;

Page 143: Java and Oracle Combined

What Are Class Methods?

Class methods are:• Shared by all instances • Useful for manipulating class variables• Declared as static

A class method is called by using the name of the class or an object reference.

public static void increaseMinPrice(double inc) {

minPrice += inc;

}

Movie.increaseMinPrice(.50);

mov1.increaseMinPrice(.50);

Page 144: Java and Oracle Combined

Guided Practice: Class Methodsor 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();float b = mov1.getPrice();Legal or not?

Page 145: Java and Oracle Combined

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

} …

Page 146: Java and Oracle Combined

Creating Classes Using the Class Editor

Page 147: Java and Oracle Combined

What Are Java Packages?

acmevideo

Copy Title Rental

Game Member Movie

Page 148: Java and Oracle Combined

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

Page 149: Java and Oracle Combined

Setting the CLASSPATH with Packages

The CLASSPATH includes the directory containing the top level of the package tree:

Package name .class location

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

CLASSPATH

Page 150: Java and Oracle Combined

Access Modifiers

private

protected

acmevideo acmetools

public public

Page 151: Java and Oracle Combined

Object Life Cycle and Inner Classes

Page 152: Java and Oracle Combined

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

Page 153: Java and Oracle Combined

Using the this Reference

Instance methods receive an argument called this, which refers to the current object.

public class Movie {

public void setRating(String newRating) {

this.rating = newRating;

}

void anyMethod() {

Movie mov1 = new Movie();

Movie mov2 = new Movie();

mov1.setRating("PG"); … title: null

rating: nullmov2

mov1title : null

rating: “PG”

this

Page 154: Java and Oracle Combined

Initializing Instance Variables

• Instance variables can be explicitly initialized at declaration.

• Initialization happens at object creation.

• All instance variables are initialized implicitly to default values depending on data type.

• More complex initialization should be placed in a constructor.

public class Movie {

private String title;

private String rating = "G";

private int numOfOscars = 0;

Page 155: Java and Oracle Combined

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.

Page 156: Java and Oracle Combined

Defining and Overloading Constructors

public class Movie {

private String title;

private String rating = "PG";

public Movie() {

title = "Last Action …";

}

public Movie(String newTitle) {

title = newTitle;

}

}Movie mov1 = new Movie();

Movie mov2 = new Movie("Gone …");

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

The Movie classnow provides two

constructors.

Page 157: Java and Oracle Combined

Sharing Code Between Constructors

public class Movie {

private String title;

private String rating;

public Movie() {

this("G");

}

public Movie(String newRating) {

rating = newRating;

}

}

A constructor can call another constructor by using this().

Movie mov2 = new Movie();

What happens here?

Page 158: Java and Oracle Combined

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

}

Page 159: Java and Oracle Combined

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();.

Page 160: Java and Oracle Combined

Using the finalize() Method

• If an object holds a resource such as a file, then the object should be able to clean it up.

• You can provide a finalize() method in that class.• The finalize() method is called just before garbage

collection.

public class Movie {

public void finalize() {

System.out.println("Goodbye");

}

}

Any problems?

Page 161: Java and Oracle Combined

Controlling Garbage Collection

Object reference types:• Strong reference• Soft reference• Weak reference• Phantom reference

Weaker gradation

order

mov1 title: “Gone...”rating: “PG”

Page 162: Java and Oracle Combined

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

?

Page 163: Java and Oracle Combined

mov1

mov1

title: “Gone...”rating: “PG”

Delaying Memory Collection

Phantom references are used for delaying the reuse of memory:• Finalized object• Queued reference• Memory still occupied• Unreachable object• poll() for existence• clear() for memory

collection

Page 164: Java and Oracle Combined

What Are Inner Classes?

• Classes that are defined within a class• Enforce a relationship between two

classes• Are of four types:

– Static– Member– Local– Anonymous

public class Outer { …

class Inner { …

}

}

Enclosing class

Page 165: Java and Oracle Combined

public class Outer {

private static float varFloat = 3.50f;private String varString;… static class InnerStatic {…

}…}

Defining Static Inner Classes

• Defined at class level• Access only static members of the outer class

Page 166: Java and Oracle Combined

public class Outer {

private static float varFloat = 3.50f;private String varString;...class InnerMember {

...outer.this

...}...}

Defining Member Inner Classes

• Defined at class level• Instance of the outer class is needed• Keyword this is used to access the outer

instance

Page 167: Java and Oracle Combined

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

}}

Page 168: Java and Oracle Combined

Defining Anonymous Inner Classes

• Defined at method level• Declared within a code block• Lack the class, extends, and implements

keywords• Cannot have a constructorpublic class Outer {...public void outerMethod(){

SomeClass sc = new SomeClass();...

myObject.myAnonymous(new SomeClass(){...

} )}

}

Page 169: Java and Oracle Combined

Using Strings, String Buffer, Wrapper,and Text-Formatting Classes

Page 170: Java and Oracle Combined

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.

Page 171: Java and Oracle Combined

Creating a String

• Assign a double-quoted constant to a Stringvariable:

• Concatenate other strings:

• Use a constructor:

String category = "Action";

String empName = firstName + " " + lastName;

String empName = new String(“Bob Smith");

Page 172: Java and Oracle Combined

Concatenating Strings

• Use the + operator to concatenate strings.

• You can concatenate primitives and strings.

• The String class has a concat() instance method that can be used to concatenate strings.

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

int age = getAge();

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

Page 173: Java and Oracle Combined

Performing Operations on Strings

• Find the length of a string:

• Find the character at a specific index:

• Return a substring of a string:

int length(); String str = "Comedy";

int len = str.length();

char charAt(int index); String str = "Comedy";

char c = str.charAt(1);

String substring

(int beginIndex,

int endIndex);

String str = "Comedy";

String sub =

str.substring(2,4);

Page 174: Java and Oracle Combined

Performing More Operations on Strings

• Convert to uppercase or lowercase:

• Trim whitespace:

• Find the index of a substring:

String toUpperCase();

String toLowerCase();

String caps =

str.toUpperCase();

String trim(); String nospaces =

str.trim();

int indexOf (String str);

int lastIndexOf

(String str);

int index =

str.indexOf("me");

Page 175: Java and Oracle Combined

Comparing String Objects

• Use equals()if you want case to count:

• Use equalsIgnoreCase()if you want to ignore case:

• Do not use ==.

String passwd = connection.getPassword();

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

String cat = getCategory();

if (cat.equalsIgnoreCase("Drama"))…

// We just want the word to match

Page 176: Java and Oracle Combined

Producing Strings from Other Objects

• Use the Object.toString() method.• Your class can override toString().

• System.out.println() automatically calls an object’s toString() method if a reference is passed to it.

public Class Movie {…

public String toString () {

return name + " (" + Year + ")";

}…

Movie mov = new Movie(…);

System.out.println(mov);

Page 177: Java and Oracle Combined

Producing Strings from Primitives

• Use String.valueOf():

• There is a version of System.out.println()for each primitive type:

String seven = String.valueOf(7);

String onePoint0 = String.valueOf(1.0f);

int count;

System.out.println(count);

Page 178: Java and Oracle Combined

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.

Page 179: Java and Oracle Combined

Wrapper Class Conversion Methods

Example: Use the methods to process data fromfields as their declared.

String qtyVal = "17";

String priceVal = "425.00";

int qty = Integer.parseInt(qtyVal);

float price = Float.parseFloat(priceVal);

float itemTotal = qty * price;

Page 180: Java and Oracle Combined

Changing the Contents of a String

• Use the StringBuffer class for modifiable strings of characters:

• Use StringBuffer if you need to keep adding characters to a string.

Note: StringBuffer has a reverse() method.

public String reverseIt(String s) {

StringBuffer sb = new StringBuffer();

for (int i = s.length() - 1; i >= 0; i--)

sb.append(s.charAt(i));

return sb.toString();

}

Page 181: Java and Oracle Combined

Formatting Classes

The java.text package contains:• An abstract class called Format with the format

() method shown in the following example

• Classes that format locale-sensitive information such as dates, numbers, and messages– DateFormat, NumberFormat, and MessageFormat

public abstract class Format … {public final String format(Object obj){//Formats an object and produces a string. }…

}

Page 182: Java and Oracle Combined

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

Page 183: Java and Oracle Combined

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

Page 184: Java and Oracle Combined

Guided Practice

1. What is the output of each code fragment?a.

b.

String s = new String("Friday");

if(s == "Friday")

System.out.println("Equal A");

if(s.equals("Friday"))

System.out.println("Equal B");

int num = 1234567;

System.out.println(String.valueOf(num).charAt(3));

Page 185: Java and Oracle Combined

Guided Practice

2. What is the output of each code fragment?a.

b.

String s1 = "Monday";

String s2 = "Tuesday";

System.out.println(s1.concat(s2).substring(4,8));

// s3 begins with 2 spaces and ends with 2 spaces

String s3 = " Monday ";

System.out.println(s3.indexOf("day"));

System.out.println(s3.trim().indexOf("day"));

Page 186: Java and Oracle Combined

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

Page 187: Java and Oracle Combined

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.

Page 188: Java and Oracle Combined

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

Page 189: Java and Oracle Combined

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

Page 190: Java and Oracle Combined

Serialization Streams, Interfaces,and Modifiers

• Example of implementing java.io.Serializable– Mark fields with the transient modifier to prevent

them from being saved; that is, to protect the information.

• Write object with java.io.ObjectOutputStream• Read object with java.io.ObjectInputStream

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

}

Page 191: Java and Oracle Combined

Reusing Code with Inheritanceand Polymorphism

Page 192: Java and Oracle Combined

Key Object-Oriented Components

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

InventoryItem

Movie Game Vcr

Superclass

Subclasses

Page 193: Java and Oracle Combined

Example of Inheritance

• The InventoryItem class defines methods and variables.

• Movie extends InventoryItem and can:– Add new variables – Add new methods– Override methods in InventoryItem class

InventoryItem

Movie

Page 194: Java and Oracle Combined

Specifying Inheritance in Java

• Inheritance is achieved by specifying which superclass the subclass extends.

• Movie inherits all the variables and methods of InventoryItem.

• If the extends keyword is missing, then the java.lang.Object is the implicit superclass.

public class InventoryItem {

}public class Movie extends InventoryItem {

}

Page 195: Java and Oracle Combined

Defining Inheritanceby Using Oracle9i JDeveloper

• When specifying a class, JDeveloper asks for its superclass:

• JDeveloper generates the code automatically.

Page 196: Java and Oracle Combined

What Does a Subclass ObjectLook Like?

A subclass inherits all the instance variables of itssuperclass.

Movie

titlelength

pricecondition

public class

Movie extends InventoryItem {

private String title;

private int length; …

}

public class InventoryItem {

private float price;

private String condition; …

}

Page 197: Java and Oracle Combined

Default Initialization

• What happens when a subclass object is created?

• If no constructors are defined:– First, the default no-arg

constructor is called in the superclass.

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

Movie movie1 = new Movie();

movie1

titlelength

pricecondition

Page 198: Java and Oracle Combined

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

Page 199: Java and Oracle Combined

The super Reference Example

public class InventoryItem {

InventoryItem(String cond) {

System.out.println("InventoryItem");

}

}

class Movie extends InventoryItem {

Movie(String title) {

super(title);

System.out.println("Movie");

}

}

Base class constructor

Calls baseclass

constructor

Page 200: Java and Oracle Combined

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;

} …

Page 201: Java and Oracle Combined

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()…

Page 202: Java and Oracle Combined

Overriding Superclass Methods

• A subclass inherits all the methods of its superclass.

• The subclass can override a method with its own specialized version.– The subclass method must have the same signature

and semantics as the superclass method.

public class InventoryItem {

public float calcDeposit(int custId) {

if …

return itemDeposit;

}

public class Vcr extends InventoryItem {

public float calcDeposit(int custId) {

if …

return itemDeposit;

}

Page 203: Java and Oracle Combined

Invoking Superclass Methods

• If a subclass overrides a method, then it can still call the original superclass method.

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

public class InventoryItem {

public float calcDeposit(int custId) {

if …

return 33.00;

}

public class Vcr extends InventoryItem {

public float calcDeposit(int custId) {

itemDeposit = super.calcDeposit(custId);

return (itemDeposit + vcrDeposit);

}

Page 204: Java and Oracle Combined

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

Page 205: Java and Oracle Combined

Treating a Subclass as Its Superclass

A Java object instance of a subclass is assignable to its superclass definition.• You can assign a subclass object to a reference

that is declared with the superclass.

• The compiler treats the object via its reference (that is, in terms of its superclass definition).

• The JVM run-time environment creates a subclass object, executing subclass methods, if overridden.

public static void main(String[] args) {

InventoryItem item = new Vcr();

double deposit = item.calcDeposit();

}

Page 206: Java and Oracle Combined

Browsing Superclass Referencesby Using Oracle9i JDeveloper

Oracle9i JDeveloper makes it easy to browse the contents of your superclass.

1

23

Page 207: Java and Oracle Combined

Acme Video and Polymorphism

• Acme Video started renting only videos.• Acme Video added games and VCRs.• What is next?• Polymorphism solves the problem.

Page 208: Java and Oracle Combined

ShoppingBasket

Using Polymorphism for Acme Video

void addItem(InventoryItem item) {

// this method is called each time

// the clerk scans in a new item

float deposit = item.calcDeposit();

}

InventoryItem

VCR Movie

calcDeposit(){…}

calcDeposit(){…}calcDeposit(){…}

Page 209: Java and Oracle Combined

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

}

Page 210: Java and Oracle Combined

Limiting Methods and Classes with final

• You can mark a method as final to prevent it from being overridden.

• You can mark a whole class as final to prevent it from being extended.

public final class Color {

}

public final boolean checkPassword(String p) {

}

Page 211: Java and Oracle Combined

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.

Page 212: Java and Oracle Combined

Using Arrays and Collections

Page 213: Java and Oracle Combined

What Is an Array?

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

1

2

4

8

[0]

[1]

[2]

[3]

Action

Comedy

Drama

[0]

[1]

[2]

Page 214: Java and Oracle Combined

Creating an Array of Primitives

1. Declare the array.

type is a primitive, like int and so on.2. Create the array object.

3. Initialize the array elements(optional).

NullarrayName

arrayName1

2

4

0

0

0

arrayName

type[] arrayName;

… or …

type arrayName[];

// Create array object syntax

arrayName = new type[size];

Page 215: Java and Oracle Combined

Declaring an Array of Primitives

• Create a variable to reference the array object.

• When an array variable is declared:– Its instance variable is initialized to null until the

array object has been created.

– Its method variable is unknown until the object is created.

int[] powers; // Example

nullpowers

Page 216: Java and Oracle Combined

Creating an Array Object foran Array of Primitives

• Create an array of the required length and assign it to the array variable:

– The array object is created by using the newoperator.

• The contents of an array of primitives are initialized automatically.

int[] powers; // Declare array variable

powers = new int[4]; //Create array object

[0]

[1]

[2]

[3]

powers 000

0

Page 217: Java and Oracle Combined

Initializing Array Elements

• Assign values to individual elements.

• Create and initialize arrays atthe same time.

int[] primes = {2, 3, 5, 7};

type[] arrayName = {valueList};

primes[0][1][2]

2357 [3]

arrayName[index] = value;

powers[0] = 1;powers

[0][1][2]

1000 [3]

Page 218: Java and Oracle Combined

Creating an Array of Object References

1. Declare the array.

2. Create the array object.

3. Initialize the objects in the array.

nullarrVar

null

null

null

arrVar

Action

Comedy

Drama

arrVar

ClassName[] arrVar;

… or …

ClassName arrVar[];

// Create array object syntax

arrVar = new ClassName[size];

Page 219: Java and Oracle Combined

Initializing the Objects in the Array

• Assign a value to each array element:

• Create and initialize the array at the same time:

String[] categories =

{"Action", "Comedy", "Drama"};

// Create an array of four empty Strings

String[] arr = new String[4];

for (int i = 0; i < arr.length; i++) {

arr[i] = new String();

}

Page 220: Java and Oracle Combined

Using an Array of Object References

• Any element can be assigned to an object of the correct type:

• Each element can be treated as an individual object:

• An array element can be passed to any method; array elements are passed by reference.

System.out.println

("Length is " + categories[2].length());

String category = categories[0];

Page 221: Java and Oracle Combined

Arrays and Exceptions

• ArrayIndexOutOfBoundsException occurs when an array index is invalid:

• NullPointerException occurs when you try to access an element that has not been initialized:

Movie[] movieList = new Movie[3];

// The following will throw NullPointerException

String director = movieList[0].getDirector();

String[] list = new String[4];

//The following throws ArrayIndexOutOfBoundsException

System.out.println(list[4]);

Page 222: Java and Oracle Combined

Multidimensional Arrays

Java supports arrays of arrays:

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

int[][] mdarr = new int[4][2];

mdarr[0][0] = 1;

mdarr[0][1] = 7;

[0]

[1]

[2]

[3]

1 7

0 0

0 0

0 0

mdarr

[0][0] [0][1]

Page 223: Java and Oracle Combined

main()Revisited

• main() has a single parameter, args.• args is an array of Strings that holds command-

line parameters:

public class SayHello {

public static void main(String[] args) {

if (args.length != 2)

System.out.println("Specify 2 arguments");

else

System.out.println(args[0]+" "+args[1]);

} …

C:\> java SayHello Hello World

Page 224: Java and Oracle Combined

Working with Variable-Length Structures

The Vector class implements a “resizable” array of any type of object:• Creating an empty vector:

• Creating a vector with an initial size:

Vector members = new Vector();

// Create a vector with 10 elements. The vector //

can be expanded later.

Vector members = new Vector(10);

Page 225: Java and Oracle Combined

Modifying a Vector

• Add an element to the end of the vector:

• Add an element at a specific position:

• Remove the element at a specific index:

String name = MyMovie.getNextName();

members.addElement(name);

// Remove the first element

members.removeElementAt(0);

// Insert a string at the beginning

members.insertElementAt(name, 0);

Page 226: Java and Oracle Combined

Accessing a Vector

• Get the first element:

• Get an element at a specific position:

• Find an object in a vector:

• Get the size of a vector:

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

int size = members.size();

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

int position = members.indexOf(name);

Page 227: Java and Oracle Combined

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

Page 228: Java and Oracle Combined

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.

Page 229: Java and Oracle Combined

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

Page 230: Java and Oracle Combined

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

Page 231: Java and Oracle Combined

Structuring Code by UsingAbstract Classes and Interfaces

Page 232: Java and Oracle Combined

Defining Abstract Classes

• An abstract class cannot be instantiated.• Abstract methods must be implemented by

subclasses.• Interfaces support multiple inheritance.

Abstract superclass

Concrete subclasses

InventoryItem

Movie VCR

Page 233: Java and Oracle Combined

Creating Abstract Classes

Use the abstract keyword to declare a class as abstract.

public abstract class InventoryItem {

private float price;

public boolean isRentable()…

}

public class Movie

extends InventoryItem {

private String title;

public int getLength()…

public class Vcr

extends InventoryItem {

private int serialNbr;

public void setTimer()…

Page 234: Java and Oracle Combined

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.

Page 235: Java and Oracle Combined

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

Page 236: Java and Oracle Combined

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.

Page 237: Java and Oracle Combined

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.

SteerableNonsteerable

Page 238: Java and Oracle Combined

Creating Interfaces

• Use the interface keyword:

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

public interface Steerable {

int MAXTURN = 45;

void turnLeft(int deg);

void turnRight(int deg);

}

Page 239: Java and Oracle Combined

Implementing Interfaces

Use the implements keyword.

public class Yacht extends Boat

implements Steerable

public void turnLeft(int deg) {…}

public void turnRight(int deg) {…}

}

Page 240: Java and Oracle Combined

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

Page 241: Java and Oracle Combined

Overview of the Classes

• Created by the sort expert:

• Created by the movie expert:

public classMyApplication

public class Movieimplements Sortable

public interface Sortable

public abstract class Sort

Page 242: Java and Oracle Combined

How the Sort Works

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

1

23

sortObjects()asks a movie to

compare itself with another movie.

The movie returns the result of the comparison.

4sortObjects()

returns the sorted list.

Sort

Movie

MyApplication

Page 243: Java and Oracle Combined

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

}

Page 244: Java and Oracle Combined

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

Page 245: Java and Oracle Combined

The Movie Class

public class Movie extends InventoryItemimplements Sortable {

String title; public int compare(Object movie2) {String title1 = this.title;String title2 = ((Movie)movie2).getTitle();return(title1.compareTo(title2));

}}

Implements Sortable:

Page 246: Java and Oracle Combined

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

}

Page 247: Java and Oracle Combined

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

}

Page 248: Java and Oracle Combined

Throwing and Catching Exceptions

Page 249: Java and Oracle Combined

What Is an Exception?

An exception is an unexpected event.

Page 250: Java and Oracle Combined

How Does Java Handle Exceptions?

• A method throws an exception.• A handler catches the exception.

Yes No

Handlerfor this

exception?

Exception object

Page 251: Java and Oracle Combined

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.

Page 252: Java and Oracle Combined

Advantages of Java Exceptions:Passing Errors Up the Call Stack

method4

method3

method2

method1 //handle error

Error code

Error code

Error code

method4

method3

method2

Method1//handle ex

Exceptionex

Each method checks for errors and returns an error code to its calling method.

method4 throws an exception; method1catches it.

Traditional error handling

Java exceptions

Page 253: Java and Oracle Combined

Advantages of Java Exceptions: Exceptions Cannot Be Ignored

If method3 ignores the error, then it will never be handled.

method4

method3

method2

method1 //handle error

Error code method4

method3

method2

Method1//handle ex

Exceptionex

The exception must be caught and handled somewhere.

Traditional error handling

Java exceptions

Page 254: Java and Oracle Combined

Checked Exceptions, Unchecked Exceptions, and Errors

All errors and exceptions extend the Throwable class.

Throwable

Error Exception

Unrecoverable errors

Checkedexceptions

Unchecked (run-time) exceptions

RuntimeException

Page 255: Java and Oracle Combined

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.

Page 256: Java and Oracle Combined

Catching and Handling Exceptions

• Enclose the method call in a try block.

• Handle each exception in a catchblock.

• Perform any final processing in a finally block.

try {

// call the method

}

catch (exception1) {

// handle exception1

}

catch (exception2) {

// handle exception2

}…

finally {

// any final processing

}

Page 257: Java and Oracle Combined

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

Page 258: Java and Oracle Combined

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

}

Page 259: Java and Oracle Combined

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

}

Page 260: Java and Oracle Combined

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

}

Page 261: Java and Oracle Combined

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

}

Page 262: Java and Oracle Combined

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

}

Page 263: Java and Oracle Combined

Throwing Exceptions

• Throw exceptions by using the throw keyword.• Use throws in the method declaration.

public String getValue(int index) throws

IndexOutOfBoundsException {

if (index < 0 || index >= values.length) {

throw new IndexOutOfBoundsException();

}

}

throw new Exception1();

Page 264: Java and Oracle Combined

Creating Exceptions

Extend the Exception class.

public class UserFileException extends Exception {

public UserFileException (String message) {

super(message);

}

}

public class MyException extends Exception { … }

Page 265: Java and Oracle Combined

Catching an Exception and Throwing aDifferent 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());

}

}

Page 266: Java and Oracle Combined

User Interface Design: Swing BasicsPlanning the Application Layout

Page 267: Java and Oracle Combined

Running Java UI Applications

Page 268: Java and Oracle Combined

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)

Page 269: Java and Oracle Combined

JButton JSlider JTree

JComboBox JTextField JProgressBar

InventoryItem

Swing Features

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

Page 270: Java and Oracle Combined

Lightweight or Heavyweight Components?

Lightweight components• No dependence on native

peer code• Can have transparent

backgrounds• Most Swing components

are lightweight• When displayed, they can

appear nonrectangular• Must be displayed in

heavyweight container

Heavyweight components• Strong dependency on

native peer code• Each rendered in its own

opaque window• Early AWT components

were mostly heavyweight

• Include some Swingtop-level components (JFrame, JApplet, JDialog)

Page 271: Java and Oracle Combined

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

Page 272: Java and Oracle Combined

The Containment Hierarchy

• Top-level containers– Frame– Dialog– Applet

• Intermediate containers– Panel– Scroll Pane

• Atomic components– Label– Text items– Buttons– And so on …

Frame

PanelAtomic

components

Page 273: Java and Oracle Combined

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.

Page 274: Java and Oracle Combined

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

Page 275: Java and Oracle Combined

Atomic Components

• Buttons• Check boxes• Combo boxes• Text• Lists• Labels

Page 276: Java and Oracle Combined

Layout Management Overview

Page 277: Java and Oracle Combined

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

Page 278: Java and Oracle Combined

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

Page 279: Java and Oracle Combined

GridBag Constraints

Cell position

Cell span

Expansionweighting

Fill rules

Anchoring

Componentpadding

External insets

Page 280: Java and Oracle Combined

Using Layout Managers

Using a layout manager with containers requires:• Creating a container and a layout manager object

• Setting the layout property of the container

• Adding items (components or other containers) into the regions that are defined by the layout manager

JFrame myFrame = new JFrame();

BorderLayout layoutMgr = new BorderLayout();

myFrame.add(new JButton(), BorderLayout.NORTH);

myFrame.add(new JTextField(), BorderLayout.SOUTH);

myFrame.add(new JPanel(), BorderLayout.CENTER);

myFrame.setLayout(layoutMgr);

Page 281: Java and Oracle Combined

Combining Layout Managers

Vertical-Flow

Grid

GridBag

null

Border

Page 282: Java and Oracle Combined

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.

Page 283: Java and Oracle Combined

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

Page 284: Java and Oracle Combined

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 touse 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`

Page 285: Java and Oracle Combined

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

Page 286: Java and Oracle Combined

Swing Text Controls

Page 287: Java and Oracle Combined

Adding Componentswith Oracle9i JDeveloper

• Use the wizard to create a JFrame.• Select a layout manager.• Add components from the Swing toolbar.• Fine-tune component properties.

Page 288: Java and Oracle Combined

Creating a Frame

Frame

Page 289: Java and Oracle Combined

Adding Components

Page 290: Java and Oracle Combined

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.

Page 291: Java and Oracle Combined

Adding User Interface Componentsand Event Handling

Page 292: Java and Oracle Combined

Swing Components

• Text controls– JTextField– JPasswordField– JTextArea– JEditorPane– JTextPane

• Graphic controls– JTree– JTable– JToggleButton

Page 293: Java and Oracle Combined

Swing Components in JDeveloper

Use the Swing pull-down menu to add components.

Page 294: Java and Oracle Combined

System Navigator

Invoking the UI Editor

Code Editor

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

Context menu

Page 295: Java and Oracle Combined

1: From the icon bar, select the appropriate component.

2: Drop the component onto the form. The class updates automatically.

How to Add a Component to a Form

Page 296: Java and Oracle Combined

Change property values in the Inspector.

Edit the Propertiesof a Component

Page 297: Java and Oracle Combined

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

}

Page 298: Java and Oracle Combined

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.

Page 299: Java and Oracle Combined

Using JDeveloper Menu Editor

• In the JDeveloper Menu Editor, use the Structure pane:– Expand the Menu node.– Click the menu bar object for a visual

representation.– Right-click menu or menu items to alter

structure from context menu options.

Clickmenu barobject in

Structure paneto displaymenu bar

Context menu whenright-clicking a menu

Context menu whenright-clicking a menu item

Page 300: Java and Oracle Combined

Sample Order Entry Application

Page 301: Java and Oracle Combined

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.

Page 302: Java and Oracle Combined

Event Handling Code Basics

• Create the event source.

• Create the event listener implementing the required event interface.

• Register the listener with the event source.

Jbutton findBtn = new Jbutton("Find");

class MyListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

// handler logic

}

}

findBtn.addActionListener(new MyListener());

Page 303: Java and Oracle Combined

OK

SourceEvent listener object

Handler method

Event Handling Process:Registration

MyListener actionListenerObj = new MyListener();

public void jbInit() {

button1.addActionListener(actionListenerObj);

}

Page 304: Java and Oracle Combined

Event Handling Process:The Event Occurs

NotifiedOK

SourceEvent listener object

Handler method

public interface ActionListener {

void actionPerformed(ActionEvent e);

}

Page 305: Java and Oracle Combined

Event Handling Process:Running the Event Handler

public class MyListener

implements ActionListener {

public void actionPerformed(ActionEvent e) {

// Your code to handle the ActionEvent …

}

OK

SourceEvent listener object

Handler method:save changes and quit

Page 306: Java and Oracle Combined

public void jbInit() {

button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

// Your code to handle the ActionEvent

}

}); … }

Implementing an Event Listeneras an Inner Class

• You can implement and register the listener object in one step.

• Implement the listener as an anonymous inner class.

Page 307: Java and Oracle Combined

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

}

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.

Page 308: Java and Oracle Combined

Swing Model View Controller Architecture

• Model, View, Controller principles

• 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.

Model

Controller ViewViewEventmodify

modify Notify update

Get changed data

Page 309: Java and Oracle Combined

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.

Page 310: Java and Oracle Combined

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

Page 311: Java and Oracle Combined

Events that a component can

generate

Event handler methods

What Events Cana Component Generate?

Page 312: Java and Oracle Combined

1: Select the event that you want to handle.

2: Click the right column to fill in a method name.

3: Double-click theright column to create the method.

How to Define an Event Handlerin JDeveloper

Page 313: Java and Oracle Combined

public void jbInit() throws Exception {

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

}

Find

Default Event Handling Code Style Generated by JDeveloper

Page 314: Java and Oracle Combined

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

}

}

Completing the Event Handler Method

Page 315: Java and Oracle Combined

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.

Page 316: Java and Oracle Combined

Building Components with JavaBeans

Page 317: Java and Oracle Combined

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

Page 318: Java and Oracle Combined

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

Page 319: Java and Oracle Combined

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

Page 320: Java and Oracle Combined

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.

Page 321: Java and Oracle Combined

Exposing Properties and Methods

Gettermethods(public)

Settermethods

(public void)

T getVar()

T[] getArr()

boolean isVar()

setVar(T val)

setArr(T[] val)

setVar(boolean val)

privateT var;T[] arr;

Page 322: Java and Oracle Combined

Event Handling with JavaBeans

A bean can fire events or listen for events from other beans.

Bean registers as a listener.

Event is fired.

Event handler code is invoked.

1

2

3handleEvt()

fireEvt()

Page 323: Java and Oracle Combined

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

Page 324: Java and Oracle Combined

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

Page 325: Java and Oracle Combined

JavaBeans at Run Time

• Always runs in a single JVM• Supports multithreaded access• Detects presence or absence of GUI environment• Locale-dependent controls

Page 326: Java and Oracle Combined

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.

Page 327: Java and Oracle Combined

Building and Using a JavaBeanin JDeveloper: Overview

1. Develop a JavaBean– Modified via code, class, or UI editors

2. Store the bean in an archive file3. Create a JDeveloper library identifying the archive4. Install the bean in JDeveloper’s Component

Palette, via its library name5. Develop an application by using the JavaBean

component

Page 328: Java and Oracle Combined

1. Develop a JavaBean

1. Select File > New.2. Expand the Client Tier - JavaBeans node.3. Double-click the Bean icon.

Page 329: Java and Oracle Combined

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

Page 330: Java and Oracle Combined

Add a Simple Property

1. In the Class Editor, select the Fields tab2. Click the Add Field button Variable name

Modifier

Type

Page 331: Java and Oracle Combined

Add Events to a Bean

1. Select bean source file.2. Select Class Editor > Events tab.

Listen for events

Fire events

Page 332: Java and Oracle Combined

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.

Page 333: Java and Oracle Combined

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.

Page 334: Java and Oracle Combined

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.

Page 335: Java and Oracle Combined

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.

Page 336: Java and Oracle Combined

Using JDBC to Access the Database

Page 337: Java and Oracle Combined

OracleDatabase

DataWeb

serverClientApplication

server

Presentation Businesslogic

Oracle9iApplication Server

J2EE Certified Environment

Java, J2EE, and Oracle9i

JDBC

Page 338: Java and Oracle Combined

Client application or applet

Connecting to a Database with Java

Client applications, JSPs, and servlets use JDBC

JDBC Relational DB

Page 339: Java and Oracle Combined

• 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).

What Is JDBC?

Page 340: Java and Oracle Combined

// Standard packagesimport java.sql.*;

import java.math.*; // optional

// Oracle extension to JDBC packagesimport oracle.jdbc.*;

import oracle.sql.*;

Preparing the Environment

• Setting the PATH

• Setting the CLASSPATH

• Importing JDBC packages

[Oracle Home]\lib

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

Page 341: Java and Oracle Combined

6. Close connections

Steps for Using JDBC to ExecuteSQL Statements

1. Register JDBC driver

4. Execute SQL statement

4a. Process SELECTstatement

4b. Process DML/ DDLstatement

2. Obtain a connection

5. Process query results

3. Create statement object

Page 342: Java and Oracle Combined

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

Page 343: Java and Oracle Combined

Using the package oracle.jdbc.driver, Oracle provides different drivers to establish a connection to the database.

JDBC callsDatabase

commands

Database

Connecting to the Database

OracleDriver

• Thin client • OCI• Server Based• …

Page 344: Java and Oracle Combined

Applet

JDBC

Client Server

Thin driver

Oracle JDBC Drivers: Thin Client Driver

• Written entirely in Java• Must be used by applets

Oracle 9i

Page 345: Java and Oracle Combined

Client Server

Application

JDBC

OCI driver

ocixxx.dll

Oracle JDBC Drivers: OCI Client Drivers

• Written in C and Java• Must be installed on the client

Oracle 9i

Page 346: Java and Oracle Combined

Choosing the Right Driver

Applet

Client application

EJB, servlet(on the middle tier)

Stored procedure

OCIThin

Driver

Thin

Server side

OCI

Thin

Type of Program

Page 347: Java and Oracle Combined

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:

• Vendors can provide different types of JDBC drivers.

Connection conn = DriverManager.getConnection(

"jdbc:oracle:thin:@myhost:1521:ORCL","scott","tiger");

Page 348: Java and Oracle Combined

• 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.

• Example using Oracle Thin JDBC driver:– jdbc:oracle:thin:@myhost:1521:ORCL

jdbc:<subprotocol>:<subname>

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

About JDBC URLs

Protocol Database Identification

Page 349: Java and Oracle Combined

• Oracle Thin driver

• Oracle OCI driver

JDBC URLs with Oracle Drivers

Syntax: jdbc:oracle:thin:@<host>:<port>:<SID>

Example: "jdbc:oracle:thin:@myhost:1521:orcl"

Syntax: jdbc:oracle:oci:@<tnsname entry>

Example: "jdbc:oracle:oci:@ORCL"

Page 350: Java and Oracle Combined

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

Page 351: Java and Oracle Combined

6. Close unneeded objects

Step 4: Executing SQL Statements

1. Register JDBC driver

4. Execute SQL statement

4a. Execute SELECTstatement

4b. Submit DML/ DDLstatement

2. Obtain a connection

5. Process query results

3. Create statement object

Page 352: Java and Oracle Combined

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

Page 353: Java and Oracle Combined

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

Page 354: Java and Oracle Combined

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

Page 355: Java and Oracle Combined

4b: Submitting DML Statements

1. Create an empty statement object.

2. Use executeUpdate to execute the statement.

Example:

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(SQLDMLstatement);

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("DELETE FROM order_items

WHERE order_id = 2354");

Page 356: Java and Oracle Combined

1. Create an empty statement object.

2. Use executeUpdate to execute the statement.

Example:

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("CREATE TABLE temp (col1 NUMBER(5,2),

col2 VARCHAR2(30)");

4b: Submitting DDL Statements

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(SQLDDLstatement);

Page 357: Java and Oracle Combined

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

Page 358: Java and Oracle Combined

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

}

Page 359: Java and Oracle Combined

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 uprset.close(); stmt.close(); conn.close();...

Page 360: Java and Oracle Combined

ResultSet rset = stmt.executeQuery("SELECT empno, hiredate, jobFROM emp");

while (rset.next()){int id = rset.getInt(1);Date hiredate = rset.getDate(2); String job = rset.getString(3);

Column Name

empno

hiredate

job

Type

NUMBER

DATE

VARCHAR2

Mapping Database Types to Java Types

ResultSet maps database types to Java types.

Method

getInt()

getDate()

getString()

Page 361: Java and Oracle Combined

1. Create an empty statement object.

2. Use execute to execute the statement.

3. Process the statement accordingly.

boolean result = stmt.execute(SQLstatement);

if (result) { // was a query - process resultsResultSet r = stmt.getResultSet(); ...

}else { // was an update or DDL - process resultint count = stmt.getUpdateCount(); ...}

Handling an Unknown SQL Statement

Statement stmt = conn.createStatement();

Page 362: Java and Oracle Combined

• SQL statements can throw a java.sql.SQLException.

• Use standard Java error handling methods.

Handling Exceptions

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

...finally { // clean uptry { if (rset != null) rset.close(); }

catch (Exception e) { ... /* handle closing errors */ }

...

Page 363: Java and Oracle Combined

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

Page 364: Java and Oracle Combined

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.

Page 365: Java and Oracle Combined

PreparedStatement pstmt =conn.prepareStatement

("UPDATE emp SET ename = ? WHERE empno = ?");

PreparedStatement pstmt =conn.prepareStatement

("SELECT ename FROM emp WHERE empno = ?");

How to Create a PreparedStatement

1. Register the driver and create the database connection.

2. Create the PreparedStatement, identifying variables with a question mark (?).

Page 366: Java and Oracle Combined

1. Supply values for the variables.

2. Execute the statement.pstmt.setXXX(index, value);

pstmt.executeQuery();

pstmt.executeUpdate();

int empNo = 3521;PreparedStatement pstmt =conn.prepareStatement("UPDATE empSET ename = ? WHERE empno = ? ");

pstmt.setString(1, "DURAND");pstmt.setInt(2, empNo);pstmt.executeUpdate();

How to Execute a PreparedStatement

Page 367: Java and Oracle Combined

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.

Page 368: Java and Oracle Combined

Database

Database commands

Data source

ConnectionPoolDataSource

Java servlet

Middle-tier server code

Middle tier

Connection Pooling

JDBCdriver

Page 369: Java and Oracle Combined

Deploying Applications UsingJava Web Start

Page 370: Java and Oracle Combined

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.

Page 371: Java and Oracle Combined

Running a Web Start Application

1. Request application2. Launch Web Start on local machine3. Download the application4. Launch the application (Draw)

HTTP

HTTP

1

2

3

4

Page 372: Java and Oracle Combined

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

Page 373: Java and Oracle Combined

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

Page 374: Java and Oracle Combined

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

Page 375: Java and Oracle Combined

Creating the Deployment Profile File

Select the File > New

Page 376: Java and Oracle Combined

Saving the Deployment Profile

Select a destination and name for the deployment profile.

Page 377: Java and Oracle Combined

Selecting Files to Deploy

• Always select the file types to include. Other settings differ for other deployment profile types.

Page 378: Java and Oracle Combined

Making an Executable .jar File

Set the Main Class field to the class name containing a main() method, in JAR Options.

Page 379: Java and Oracle Combined

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.

Page 380: Java and Oracle Combined

Using JDeveloper to Deploy an Applicationto Java Web Start

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

Page 381: Java and Oracle Combined

Step 1: Generate Deployment Profiles and Archive Application

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

Page 382: Java and Oracle Combined

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.

Page 383: Java and Oracle Combined

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

Page 384: Java and Oracle Combined

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)

Page 385: Java and Oracle Combined

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.