Oracle10g Java Programming - Electronic Presentation PDF
Oracle10g Java Programming - Electronic Presentation PDF
Oracle10g Java Programming - Electronic Presentation PDF
Electronic Presentation
D17249GC11
Edition 1.1
August 2004
D39817
Authors
Jeff Gallus
Glenn Stokol
Technical Contributors
and Reviewers
Kenneth Cooper
Peter Driver
Christian Dugas
Craig Hollister
Chika Izumi
Pete Laseau
Glenn Maslen
Monica Motley
Gayathri Rajagopal
Publisher
Poornima G
Introduction
Objectives
I-2
Course Overview
I-3
Objectives
1-2
What Is Java?
Java:
Is a platform and an object-oriented language
Was originally designed by Sun Microsystems for
consumer electronics
Contains a class library
Uses a virtual machine for program execution
1-3
1-4
Object-oriented
Interpreted and platform-independent
Dynamic and distributed
Multithreaded
Robust and secure
An Object-Oriented Approach
Design
Implementation
CLASS MODELS
1-5
Integration
and testing
Platform Independence
Compile
(javac)
Movie.java
1-6
JVM
(java)
Movie.class
Running program
Web
server
Application
server
Presentation
Business
logic
Servlets
JavaServer
Pages (JSPs)
1-7
Enterprise
JavaBeans (EJB)
CORBA
Data
Operating system
JVM
Application
1-8
1-9
JIT compilers:
Improve performance
Are useful if the same bytecodes are executed
repeatedly
Translate bytecodes to native instruction
Optimize repetitive code, such as loops
Use Java HotSpot VM for better performance and
reliability
1-10
Implementing Security
in the Java Environment
Language and compiler
Class loader
Bytecode verifier
Interface-specific access
1-11
Client-side deployment:
JVM runs stand-alone applications from the
command line.
Classes load from a local disk, eliminating the need
to load classes over a network.
Server-side deployment:
Serves multiple clients from a single source
Is compatible with a multitier model for Internet
computing.
1-12
Client
Web
server
Application
server
Presentation
Business
logic
Oracle
Application Server
1-13
Data
Oracle
database
1-14
Debugger (jdb)
Others
Copyright 2004, Oracle. All rights reserved.
J2SE
1-15
Development
Debug
UML
Exchange
ADF
Database
Synchronized changes
XML
SCM
1-16
HTML
Deployment
Component Palette
System Navigator
1-17
Code Editor
Copyright 2004, Oracle. All rights reserved.
Property Inspector
Oracle10g Products
1-18
Summary
1-19
Objectives
2-2
What Is Modeling?
2-3
A class:
Models an abstraction of objects
Defines the attributes and behaviors of
objects
Is the blueprint that defines an object
An object:
Is stamped out of the class mold
Is a single instance of a class
Retains the structure and behavior
of a class
2-4
2-5
Operation: Write
Operation: Withdraw
2-7
A PC may be
an object.
2-8
A PC may have a
keyboard, mouse, and
network card, all of which
may be objects.
Copyright 2004, Oracle. All rights reserved.
A PC may have a
CD drive, which
may be an object.
getName
setBirthdate
name
address
birthdate
getAddress
getAge
getAge()
Message
setAddress
Person
2-9
Client or
sender
Guided Practice:
Spot the Operations and Attributes
2-10
Collaborating Objects
2-11
2-12
What Is a Class?
2-13
ops:
attribs:
2-14
write, refill
ink amount, color of ink
write, refill
ink amount
2-15
What Is Encapsulation?
2-16
What Is Inheritance?
Savings account
2-17
Account
Checking account
2-18
A subclass object
is-a-kind-of
superclass
object.
A subclass must
have all the
attributes and
behaviors of the
superclass.
Account
Pen
Savings account
Pencil
What Is Polymorphism?
Load passengers
2-19
2-20
2-21
2-22
Summary
2-23
Practice 2: Overview
2-24
id: int
orderDate: Date
shipDate: Date
shipMode: String
orderTotal: double
name: String
address: String
phone: String
getName()
setName()
setAddress()
getAddress()
:
addItem()
removeItem()
setOrderDate()
getOrderDate()
setShipDate()
:
OrderItem
lineNo: int
quantity: int
price: double
getQuantity()
setQuantity()
setPrice()
getPrice()
getItemTotal()
:
Product
Company
Individual
contact: String
discount: int
licNumber: String
getContact()
setContact()
:
setLicNumber()
getLicNumber()
:
2-25
id: int
name: String
description: String
retailPrice: double
getPrice()
:
Objectives
J2SE
3-3
J2SE
3-4
Documentation generator
J2SE
3-5
3-6
File names
Customer.java, RentalItem.java
Method names
getCustomerName(), setRentalItemPrice()
Package names
oracle.xml.xsql, java.awt, java.io
3-7
Variables:
customerName, customerCreditLimit
Constants:
MIN_WIDTH, MAX_NUMBER_OF_ITEMS
3-8
Defining a Class
3-9
// Instance methods
float getAmountDue (int rentId) {
3-10
Declaration
Instance
variable
Instance
method
3-11
Access modifier
Static keyword
Arguments
Return type
3-12
Examples of a Method
public float getAmountDue (String cust){
// method variables
int numberOfDays;
float due;
float lateFee = 1.50F;
String customerName;
// method body
numberOfDays = getOverDueDays();
due = numberOfDays * lateFee;
customerName = getCustomerName(cust);
return due;
}
3-13
Declaration
Method
variables
Method
statements
Return
Declaring Variables
3-14
Examples of Variables
in the Context of a Method
public float getAmountDue (String cust) {
float due = 0;
int numberOfDays = 0;
float lateFee = 1.50F;
{int tempCount = 1; // new code block
due = numberOfDays * lateFee;
tempCount++;
}
// end code block
return due;
}
3-15
Method
variables
Temporary
variables
3-16
3-17
3-18
Getter
methods
(public)
3-19
private
T var;
T[] arr;
getVar()
Setter
methods
(public void)
setVar(T val)
T[] getArr()
setArr(T[] val)
boolean isVar()
setVar(boolean val)
3-20
3-21
3-22
CLASSPATH: Example
Location of .class files in the oe package
Setting CLASSPATH
C:\>set CLASSPATH=D:labs\les03\classes\oe
3-23
Summary
3-24
Practice 3: Overview
3-25
Objectives
Reserved Keywords
boolean
byte
char
double
float
int
long
short
void
true
false
null
4-3
abstract
final
native
private
protected
public
static
synchronized
transient
volatile
strictfp
break
case
catch
continue
default
do
else
finally
for
if
return
switch
throw
try
while
class
extends
implements
interface
throws
import
package
instanceof
new
super
this
Variable Types
User-defined types:
Classes
Interfaces
Arrays
4-4
ab
Floating
Point
Character
True
False
byte
short
int
long
float
double
char
boolean
1, 2, 3, 42
07
0xff
3.0F
.3337F
4.022E23
'a' '\141'
'\u0061'
'\n'
true
false
0.0f
\u0000
false
4-6
Initial value
Declaring Variables
4-7
Local Variables
class Rental {
private int instVar;
// instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3;
// local variable
}
}
4-8
4-9
item_Cost
_itemCost
itemCost2
item#Cost
item*Cost
2itemCost
item-Cost
abstract
4-10
Integer literals
0 1 42 -23795
02 077 0123
0x0 0x2a 0X1FF
365L 077L 0x1000L
Floating-point
literals
(decimal)
(octal)
(hex)
(long)
Boolean literals
Character literals
String literals
4-11
true false
'a'
'\n'
'\t'
'\077' '\u006F'
"Hello, world\n"
4-12
4-13
Categorizing Operators
4-14
4-15
4-16
a, b, c, d, e;
2 + 2;
// addition
a * 3;
// multiplication
b - 2;
// subtraction
b / 2;
// division
b % 2;
// returns the remainder of division
4-17
byte
int
long
4-18
short
char
short
char
int
long
4-19
>
>=
<
<=
==
!=
greater than
greater than or equal to
less than
less than or equal to
equal to
not equal to
4-20
4-21
&
|
4-22
4-23
Operator Precedence
Order
1
2
3
4
5
6
7
8
9
10
11
12
13
4-24
Operators
Comments
++ -- + - ~
! (type)
* / %
+ - +
<< >> >>>
< > <= >=
instanceof
==
!=
&
^
|
&&
||
?:
= op=
Unary operators
L
L
L
L
Equality
Bit/logical AND
Bit/logical exclusive OR
Bit/logical inclusive OR
Logical AND
Logical OR
Conditional operator
Assignment operators
L
L
L
L
L
L
R
R
Assoc.
4-25
Concatenating Strings
4-26
Summary
4-27
Practice 4: Overview
4-28
Objectives
5-2
5-3
Sequential
Iteration
Selection
Transfer
5-4
General:
Examples:
if ( boolean_expr )
statement1;
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
5-5
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed >= 25 but <= 65");
else
System.out.println("Speed under 25");
5-7
int x = 3, y = 5;
if (x >= 0)
if (y < x)
System.out.println("y is less than x");
else
System.out.println("x is negative");
int x = 7;
if (x = 0)
System.out.println("x is zero");
switch ( integer_expr ) {
case constant_expr1:
statement1;
break;
case constant_expr2:
statement2;
break;
[default:
statement3;]
}
5-8
The switch
statement is useful
when selecting an
action from several
alternative integer
values.
Integer_expr must
be byte, int, char,
or short.
switch (choice) {
case labels
case 37:
must be
System.out.println("Coffee?");
constants.
break;
Use break to
jump out of a
case 45:
switch.
System.out.println("Tea?");
It is
break;
recommended
to always
default:
provide a
System.out.println("???");
default.
break;
5-9
Looping in Java
5-10
Initialization
Iteration condition
Body
Termination
Example:
5-11
int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Example:
int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
5-12
Example:
for (i = 0; i < 10; i++)
System.out.println(i);
5-13
5-14
int x = 10;
while (x > 0);
System.out.println(x--);
System.out.println("We have lift off!");
int x = 10;
while (x > 0)
System.out.println("x is " + x);
x--;
int sum = 0;
for (; i < 10; sum += i++);
System.out.println("Sum is " + sum);
5-15
5-16
Summary
5-17
Practice 5: Overview
5-18
Objectives
6-2
6-3
Component Palette
System Navigator
6-4
Code Editor
Copyright 2004, Oracle. All rights reserved.
Property Inspector
Examining Workspaces
Structure
pane
6-5
Contain related
files
Manage project and
environment
Project
settings
Manage compiler
and debug options
Project
files
6-6
6-7
General
Business Tier
Client Tier
Database Tier
Web Tier
In the General
category, select
Application
Workspace to invoke
the Property pane.
6-8
6-9
6-10
6-11
6-12
6-13
6-14
6-15
Customizing JDeveloper
6-16
6-17
6-18
6-19
Setting Breakpoints
Setting breakpoints:
Manage multiple breakpoints
Manage conditional breakpoints
Define columns displayed in window
Description
Type
Status, and so on
6-20
6-21
6-22
6-23
Summary
6-24
Java applications
Java servlets
JSPs
EJBs
Practice 6: Overview
6-25
Objectives
7-2
Methods
Objects
Contained in a class
Attributes
7-3
Packages
Object
references
An object is an
instance of a
class.
Objects have
their own
memory.
Class definitions
must be loaded
to create
instances.
mov1
7-4
mov2
Creating Objects
7-5
mov1
(When instantiated)
7-6
Primitive variables
hold a value.
int i;
Object variables
hold references.
Movie mov1;
mov1
0
null
Movie mov1 = new Movie();
int j = 3;
j
7-7
mov1
title: null
rating: null
if (mov1 == null)
mov1 = new Movie();
mov1 = null;
7-8
Assigning References
mov2
7-9
mov1
title: null
rating: null
mov2
Create movies:
title: null
rating: null
7-11
Defining Methods
};
7-12
Calling a Method
7-13
7-14
7-15
operator:
7-16
var
aMethod
aMethod()
7-17
num
150
anObj.aMethod(num);
System.out.println("num: " + num);
public void aMethod(int arg) {
arg
if (arg < 0 || arg > 100)
150
arg = 0;
System.out.println("arg: " + arg);
}
7-18
mov1
title: Gone with
rating: PG
ref2
public void aMethod(Movie ref2) {
ref2.setRating("R");
}
7-19
Class variables:
Belong to a class and are common to all instances
of that class
Are declared as static in class definitions
public class Movie {
private static double minPrice;
private String title, rating;
title
rating
min
Price
Movie class variable
7-20
// class var
// inst vars
title
rating
Movie objects
title
rating
7-21
7-22
7-23
Examples in Java
main()
Math.sqrt()
System.out.println()
public class MyClass {
public static void main(String[] args) {
double num, root;
root = Math.sqrt(num);
System.out.println("Root is " + root);
}
7-24
7-25
Customer Order
Util
OrderEntry OrderItem
7-26
7-27
Package name
CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06
7-28
Access Modifiers
acmevideo
public
public
protected
private
7-29
acmetools
Summary
7-30
Practice 7: Overview
7-31
Objectives
8-2
Overloading Methods
8-3
void anyMethod() {
Movie mov1 = new Movie();
Movie mov2 = new Movie();
mov1.setRating("PG");
8-4
title : null
rating: PG
mov1
mov2
title: null
rating: null
8-5
8-6
8-7
What happens
here?
}
8-8
8-9
Reclaiming Memory
8-10
8-11
Any problems?
Static
Member
Local
Anonymous
8-12
8-13
8-14
8-15
8-16
Summary
8-17
Practice 8: Overview
8-18
Objectives
9-2
What Is a String?
9-3
String is a class.
A String object holds a sequence of characters.
String objects are read-only (immutable); their
values cannot be changed after creation.
The String class represents all strings in Java.
Creating a String
Use a constructor:
String empName = new String(Bob Smith");
9-4
Concatenating Strings
9-5
9-6
String toUpperCase();
String toLowerCase();
Trim whitespace:
String nospaces =
str.trim();
String trim();
String caps =
str.toUpperCase();
int index =
str.indexOf("me");
9-8
9-9
Use String.valueOf():
String seven = String.valueOf(7);
String onePoint0 = String.valueOf(1.0f);
System.out.println(count);
9-10
And so on
9-11
9-12
9-13
Formatting Classes
9-14
The SimpleDateFormat:
9-15
year
month in year
minute in hour
1996
July or 07
30
The MessageFormat:
9-16
Using DecimalFormat
The DecimalFormat:
Is a concrete subclass of NumberFormat for
formatting decimal numbers
Allows for a variety of parameters and for
localization to Western, Arabic, or Indic numbers
Uses standard number notation in format
public DecimalFormat(String pattern);
9-17
Guided Practice
b.
int num = 1234567;
System.out.println(String.valueOf(num).charAt(3));
9-18
Guided Practice
b.
// s3 begins with 2 spaces and ends with 2 spaces
String s3 = " Monday ";
System.out.println(s3.indexOf("day"));
System.out.println(s3.trim().indexOf("day"));
9-19
9-20
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
9-21
9-22
9-23
import java.io.Serializable;
public class Member implements Serializable {
private int id;
private String name;
private transient String password;
9-24
Summary
9-25
Practice 9: Overview
9-26
Objectives
10-2
Inheritance
Constructors referenced by subclass
Polymorphism
Inheritance as an OO fundamental
Superclass
InventoryItem
Subclasses
Movie
10-3
Game
Vcr
Example of Inheritance
Movie
10-4
}
public class Movie extends InventoryItem {
10-5
Defining Inheritance
by Using Oracle JDeveloper 10g
10-6
10-7
Movie
price
condition
title
length
Default Initialization
10-8
Movie
price
condition
title
length
10-9
}
}
class Movie extends InventoryItem {
Movie(String title) {
Movie(String title, String cond)
{super(cond);
System.out.println("Movie");
}
}
10-10
Base class
constructor
Calls base
class
constructor
10-11
10-12
10-14
10-16
10-17
10-18
Movie
calcDeposit(){}
ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();
10-19
if (i instanceof Vcr)
((Vcr)i).playTestTape();
}
10-20
10-21
10-22
Summary
10-23
10-24
Objectives
11-2
What Is an Array?
[0]
[1]
[2]
[3]
11-3
[0]
Action
[1]
Comedy
[2]
Drama
2
4
8
Null
arrayName
0
arrayName
0
1
2
4
// Example
null
11-5
11-6
0
0
0
0
11-7
1
0
0
0
[0]
3 [1]
5 [2]
7 [3]
2
primes
[0]
[1]
[2]
[3]
null
arrVar
null
null
null
arrVar
Action
Comedy
Drama
11-9
11-10
ArrayIndexOutOfBoundsException occurs
when an array index is invalid:
11-11
Multidimensional Arrays
[0][0]
[0][1]
[1]
[2]
[3]
[0]
11-12
main() Revisited
11-13
11-14
Modifying a Vector
11-15
Accessing a Vector
11-16
11-17
11-18
11-19
Using Iterators
11-20
Summary
11-21
11-22
Objectives
12-2
Abstract
superclass
InventoryItem
Concrete
subclasses
12-3
Movie
VCR
12-4
An abstract method:
Is an implementation placeholder
Is part of an abstract class
Must be overridden by a concrete subclass
12-5
12-6
12-7
Examples of Interfaces
Nonsteerable
12-8
Steerable
Creating Interfaces
12-9
Implementing Interfaces
12-10
12-11
12-12
public abstract
class Sort
public class
MyApplication
sortObjects()
returns the
sorted list.
MyApplication passes
an array of movies to
Sort.sortObjects().
Sort
The movie
returns the
result of the
comparison.
sortObjects()
asks a movie to
2
compare itself with
another movie.
3
Movie
12-13
12-14
Holds sortObjects():
public abstract class Sort {
public static void sortObjects(Sortable[] items) {
// Step through the array comparing and swapping;
// do this length-1 times
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length - 1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempitem = items[j+1];
items[j+1] = items[j];
items[j] = tempitem; } } } } }
12-15
Implements Sortable:
public class Movie extends InventoryItem
implements Sortable {
String title;
public int compare(Object movie2) {
String title1 = this.title;
String title2 = ((Movie)movie2).getTitle();
return(title1.compareTo(title2));
}
}
12-16
12-17
12-18
Summary
12-19
12-20
Objectives
13-2
What Is an Exception?
13-3
Exception object
Yes
13-4
Handler
for this
exception?
No
13-5
Java exceptions
Error
code
method3
Error
code
method4
Error
code
13-6
Method1
//handle ex
method2
method3
Exception
ex
method4
method4 throws an
exception; eventually
method1 catches it.
Java exceptions
method1
//handle error
method1
//handle ex
method2
method2
method3
method3
method4
Error
code
13-7
Exception
ex
method4
The exception must be
caught and handled
somewhere.
Error
Unrecoverable
errors
Exception
Checked
exceptions
RuntimeException
Unchecked (run-time)
exceptions
13-8
13-9
Handle each
exception in a catch
block.
Perform any final
processing in a
finally block.
13-10
try {
// call the method
}
catch (exception1) {
// handle exception1
}
catch (exception2) {
// handle exception2
}
finally {
// any final processing
}
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
13-11
13-12
13-13
13-14
13-15
13-16
Throwing Exceptions
13-17
Creating Exceptions
13-18
13-19
Summary
13-20
13-21
Objectives
14-2
14-3
Swing (javax.swing):
A more powerful graphical user interface library
Built on top of the AWT class hierarchy
14-4
Swing Features
A set of visual components that have been available
since JDK 1.1, but part of core JDK since version 1.2:
Lightweight components compared to AWT
Pluggable look and feel API
InventoryItem
Many more components than AWT
14-5
JButton
JSlider
JComboBox
JTextField
JTree
JProgressBar
Heavyweight components
Strong dependency on
native peer code
Each rendered in its own
opaque window
Early AWT components
were mostly
heavyweight
Include some Swing
top-level components
(JFrame, JApplet,
JDialog)
14-6
Lightweight components
No dependence on native
peer code
Can have transparent
backgrounds
Most Swing components
are lightweight
When displayed, they can
appear nonrectangular
Must be displayed in
heavyweight container
14-7
Top-level containers
Frame
Frame
Dialog
Applet
Intermediate containers
Panel
Scroll Pane
Atomic components
Label
Text items
Buttons
14-8
Panel
Atomic
components
Top-Level Containers
14-9
Intermediate Containers
14-10
Atomic Components
14-11
Buttons
Check boxes
Combo boxes
Text
Lists
Labels
14-12
Border Layout
14-13
GridBag Layout
14-14
Is based on a grid
Allows components to span multiple rows and
columns
Allows rows and columns to differ in size
Uses the components preferred size to control
cell size
GridBag Constraints
External insets
Component
padding
Cell position
Cell span
Expansion
weighting
Anchoring
Fill rules
14-15
14-16
Border
null
VerticalFlow
GridBag
Grid
14-17
14-18
14-19
jPanel1.setBorder(BorderFactory.createBevelBorder(
BevelBorder.LOWERED,Color.lightGray,Color.darkGray));
Border etchedBorder =
BorderFactory.createEtchedBorder();//pre-create border
jPanel2.setBorder(etchedBorder);
// use border`
14-20
14-21
14-22
Adding Components
with Oracle JDeveloper 10g
14-23
Creating a Frame
Frame
14-24
Adding Components
Use the Component Palette to add
Swing items to the Frame
14-25
14-26
Summary
14-27
14-28
Objectives
15-2
Swing Components
Text controls
JTextField
JPasswordField
JTextArea
JEditorPane
JTextPane
Graphic controls
JTree
JTable
JToggleButton
15-3
15-4
Code Editor
System Navigator
Context menu
15-5
15-6
15-8
Creating a Menu
15-9
Context menu
when
right-clicking a
menu item
Click
menu bar
object in
Structure pane
to display
menu bar
15-10
15-11
15-12
How it works:
Event originates from source and generates an
event object.
An event listener hears a specific event.
An event handler determines what to do.
Setting it up:
1. Create an event source object.
2. Create an event listener object implementing an
interface with methods to handle the event object.
3. Write an event-specific method to handle the event.
4. Register the listener object with the event source
for the specified event.
15-13
15-14
Source
OK
15-15
Handler method
15-16
Source
OK
Source
15-17
Controller
modify
modify
View
View
Notify update
Model
Terms explained:
Model represents the data or information.
View provides a visual representation of the data.
Controller handles events modifying the
view/model.
15-19
15-20
void setModel(ListModel)
Sets model representing the data and clears
selection. Uses DefaultListModel class for the
model.
Object getSelectedValue()
Returns the selected object, or null if nothing is
selected
int getSelectedIndex()
Returns the index of the selected item, or 1 if
nothing is selected
15-21
Event handler
methods
15-22
15-23
findButton.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
findButton_actionPerformed(e);
}
});
void findButton_actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
15-24
15-25
Summary
15-26
15-27
Objectives
16-2
Client
Web
server
Application
server
Presentation
Business
logic
Oracle
database
Oracle
Application Server 10g
J2EE Certified Environment
JDBC
16-3
Data
Client application
or applet
16-4
JDBC
Relational DB
What Is JDBC?
16-5
16-6
2. Obtain a connection.
16-7
6. Close connections.
16-8
16-9
Thin client
OCI
Server-based
Database
commands
Database
Applet
JDBC
Thin driver
Client
16-10
Oracle
Server
ocixxx.dll
Client
16-11
Oracle
Server
Type of Program
Driver
Applet
Thin
Client application
Thin
Thin
EJB, servlet
(on the middle tier)
Stored procedure
16-12
OCI
OCI
Server side
Example:
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");
16-13
Protocol
Database identification
jdbc:oracle:<driver>:@<database>
16-14
16-15
16-16
16-17
16-18
16-19
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM order_items
WHERE order_id = 2354");
16-20
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("CREATE TABLE temp (col1 NUMBER(5,2),
col2 VARCHAR2(30)");
16-21
16-22
16-25
Column Name
Type
Method
empno
NUMBER
getInt()
hiredate
DATE
getDate()
job
VARCHAR2
getString()
16-26
Handling Exceptions
{
rset = stmt.executeQuery("SELECT empno,
ename FROM emp");
}
catch (java.sql.SQLException e)
{ ... /* handle SQL errors */ }
...
finally { // clean up
try { if (rset != null) rset.close(); }
catch (Exception e)
{ ... /* handle closing errors */ }
...
16-27
Managing Transactions
16-28
16-29
16-30
16-31
16-32
Connection Pooling
Middle tier
Java servlet
Data source
Middle-tier server code
ConnectionPoolDataSource
JDBC
driver
Database
Database
commands
16-33
Summary
16-34
16-35
Objectives
17-2
17-3
1. Request the
application.
2. Launch Web Start on
the local machine.
3. Download the
application.
4. Launch the
application (Draw).
17-4
HTTP
3
HTTP
4
17-5
17-6
17-7
17-8
17-9
17-10
17-11
17-12
17-13
17-14
17-15
17-16
17-17
17-18
Summary
17-19
17-20
Practice Solutions
B
Java Language
Quick-Reference
Guide
Console Output
Java applications and applets can output simple messages to the console as
follows:
System.out.println("This is displayed on the console");
Data Types
boolean
byte
char
short
int
long
float
double
Operators
+ - * / %
++ --
+= -= *= /= %= etc.
&&
||
!
== != > >= < <=
& | ^ ~
<< >> >>>
instanceof
if (dayname.equals("Sat") || dayname.equals("Sun")){
System.out.println("Hooray for the weekend");
}
else if (dayname.equals("Mon")) {
System.out.println("I dont like Mondays");
}
else {
System.out.println("Not long for the weekend!");
}
Control Flow: switch
switch is used to check an integer (or character) against a fixed list of
alternative values:
int daynum;
switch (daynum) {
case 0:
case 6:
System.out.println("Hooray for the weekend");
break;
case 1:
System.out.println("I dont like Mondays");
break;
default:
System.out.println("Not long for the weekend!");
break;
}
i*i);
i*i);
int positiveValue;
do {
positiveValue = getNumFromUser();
}
while (positiveValue < 0);
Defining Classes
When you define a class, you define the data attributes (usually private) and
the methods (usually public) for a new data type. The class definition is placed
in a .java file as follows:
// This file is Student.java. The class is declared
// public, so that it can be used anywhere in the program
public class Student {
private String name;
private int
numCourses = 0;
// Constructor to initialize all the data members
public Student(String n, int c) {
name = n;
numCourses = c;
}
// No-arg constructor, to initialize with defaults
public Student() {
this("Anon", 0);
// Call other constructor
}
// finalize() is called when obj is garbage collected
public void finalize() {
System.out.println("Goodbye to this object");
}
// Other methods
public void attendCourse() {
numCourses++;
}
public void cancelPlaceOnCourse() {
numCourses--;
}
public boolean isEligibleForChampagne() {
return (numCourses >= 3);
}
}
Using Classes
To create an object and send messages to the object:
public class MyTestClass {
public static void main(String[] args) {
// Step 1 - Declare object references
// These refer to null initially in this example
Student me, you;
if (me.isEligibleForChampagne())
System.out.println("Thanks very much");
}
}
Arrays
An array behaves like an object. Arrays are created and manipulated as follows:
// Step 1 - Declare a reference to an array
int[] squares;
// Could write int squares[];
// Step 2 - Create the array "object" itself
squares = new int[5]; // Creates array with 5 slots
// Step 3 - Initialize slots in the array
for (int i=0; i < squares.length; i++) {
squares[i] = i * i;
System.out.println(squares[i]);
}
Note that array elements start at [0], and that arrays have a length property that
gives you the size of the array. If you inadvertently exceed an arrays bounds, an
exception is thrown at run time and the program aborts.
Note: Arrays can also be set up by using the following abbreviated syntax:
String[] cities = {
"San Francisco",
"Dallas",
"Minneapolis",
"New York",
"Washington, D.C."
};
Abstract Classes
An abstract class is one that can never be instantiated; in other words, you cannot
create an object of such a class. Abstract classes are specified as follows:
// Abstract superclass
public abstract class Mammal {
// Concrete subclasses
public class Cat extends Mammal {
}
public class Dog extends Mammal {
}
public class Mouse extends Mammal {
Abstract Methods
An abstract method is one that does not have a body in the superclass. Each concrete
subclass is obliged to override the abstract method and provide an implementation;
otherwise, the subclass is itself deemed abstract because it does not implement all its
methods.
// Abstract superclass
public abstract class Mammal {
// Declare some
public abstract
public abstract
public abstract
abstract methods
void eat();
void move();
void reproduce();
Interfaces
An interface is similar to an abstract class with 100% abstract methods and no
instance variables. An interface is defined as follows:
public interface Runnable {
public void run();
}
A class can implement an interface as follows. The class is obliged to provide an
implementation for every method specified in the interface; otherwise, the class
must be declared abstract because it does not implement all its methods.
public class MyApp extends Applet implements Runnable {
public void run() {
// This is called when the Applet is kicked off
// in a separate thread
Static Variables
A static variable is like a global variable for a class. In other words, you get
only one instance of the variable for the whole class, regardless of how many
objects exist. static variables are declared in the class as follows:
public class Account {
private String accnum;
private double balance = 0.0;
// Instance var
// Instance var
// Class var
}
Static Methods
A static method in a class is one that can access only static items; it cannot
access any non-static data or methods. static methods are defined in the
class as follows:
public class Account {
public static void setIntRate(double newRate) {
intRate = newRate;
}
public static double getIntRate() {
return intRate;
}
}
To invoke a static method, use the name of the class as follows:
public class MyTestClass {
public static void main(String[] args) {
System.out.println("Interest rate is" +
Account.getIntRate());
}
}
Packages
Related classes can be placed in a common package as follows:
// Car.java
package mycarpkg;
public class Car {
// Engine.java
package mycarpkg;
public class Engine {
// Transmission.java
package mycarpkg;
public class Transmission {
}
Importing Packages
Anyone needing to use the classes in this package can import all or some of the
classes in the package as follows:
import mycarpkg.*;
or
import mycarpkg.Car; // just import individual classes
// final methods
public class MySecurityClass {
public final void validatePassword(String password) {
}
}
// final variables
public class MyTrigClass {
public static final double PI = 3.1415;
Exception Handling
Exception handling is achieved through five keywords in Java:
try
The block of code where statements that can cause an exception are
placed
catch The block of code where error processing is placed
finally An optional block of code after a try block, for unconditional
execution
throw The keyword that is used in the low-level code to generate or throw an
exception
throws The keyword that specifies the list of exceptions that a method can
throw
Here are some examples:
public class MyClass {
public void anyMethod() {
try {
func1();
func2();
func3();
}
catch (IOException e) {
System.out.println("IOException:" + e);
}
catch (MalformedURLException e) {
System.out.println("MalformedURLException:" + e);
}
finally {
System.out.println("This is always displayed");
}
}
public void func1() throws IOException {
}
public void func2() throws MalformedURLException {
}
public void func3() throws IOException,
MalformedURLException {
}
}