Академический Документы
Профессиональный Документы
Культура Документы
Java:
• Is a platform and an object-oriented language
• Was originally designed by Sun Microsystems for
consumer electronics
• Contains a class library
• Uses a virtual machine for program execution
Key Benefits of Java
• Object-oriented
• Interpreted and platform-independent
• Dynamic and distributed
• Multithreaded
• Robust and secure
An Object-Oriented Approach
CLASS MODELS
Platform Independence
Compile JVM
(javac) (java)
• Servlets • Enterprise
JavaBeans (EJB)
• JavaServer
Pages (JSPs) • CORBA
Using the Java Virtual Machine
Browser
JVM JVM
Application Applet
How Does the JVM Work?
JIT compilers:
• Improve performance
• Are useful if the same bytecodes are executed
repeatedly
• Translate bytecodes to native instruction
• Optimize repetitive code, such as loops
• Use Java HotSpot VM for better performance and
reliability
Implementing Security
in the Java Environment
Class loader
Bytecode verifier
Interface-specific access
What Are Java Applications?
• Client-side deployment:
– The JVM runs stand-alone applications from the
command line.
– Classes load from a local disk, eliminating the need
to load classes over a network.
• Server-side deployment:
– Serves multiple clients from a single source.
– Is compatible with a multitier model for Internet
computing.
Using Java with Oracle9i
Web Application
Client server server Data
Business
Presentation
logic
OC4J
Oracle
Oracle9i Database
Application Server
OC4J
The Java Software Development Kit
Development Debug
UML Exchange
Multitier Database
SCM Deployment
Exploring the JDeveloper Environment
Command Area
Property
Viewer Project Navigator
Inspector
Oracle9i Products
Oracle9iDS Application Development
Oracle9iDS Business Intelligence
Defining Object-Oriented Principles
What Is Modeling?
• A class:
– Models an abstraction of objects
– Defines the attributes and behaviors of
objects
– Is the blueprint that defines an object
• An object:
– Is stamped out of the class mold
– Is a single instance of a class
– Retains the structure and behavior
of a class
An Object’s Attributes Maintain Its State
INK
Object: Attribute:
my blue pen ink amount
Object: Attribute:
Acme Bank ATM cash available
Objects Have Behavior
Object: Operation:
my blue pen write
Object: Operation:
Acme Bank ATM withdraw
Objects Are Modeled as Abstractions
Person
getName
getAge()
setBirthdate name getAge Message
address
birthdate
Account
Savings account Checking account
• A subclass object
“is-a-kind-of”
superclass
object. Account Pen
• A subclass must
have all of the
attributes and
behaviors of the
superclass.
Load passengers
Order Entry UML Diagram
Order Entry System
Partial UML Class Model
Order
Customer OrderItem
id: int
name: String orderDate: Date lineNo: int
address: String shipDate: Date quantity: int
phone: double shipMode: String price: double
getName() orderTotal: double
setName() getQuantity()
setAddress() addItem() setQuantity()
getAddress() removeItem() setPrice()
: setOrderDate() getPrice()
getOrderDate() getItemTotal()
setShipDate() :
:
Product
Company Individual id: int
name: String
contact: String description: String
discount: int licNumber: String
retailPrice: double
getContact() setLicNumber()
getPrice()
setContact() getLicNumber()
:
: :
Basic Java Syntax and Coding
Conventions
Examining Toolkit Components
• Variables:
– customerName, customerCreditLimit
• Constants:
– MIN_WIDTH, MAX_NUMBER_OF_ITEMS
• Uppercase and lowercase characters
• Numerics and special characters
Defining a Class
Access modifier
Setting CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les05\solution
Exploring Primitive Data Types
and Operators
Reserved Keywords
Floating True
Integer Character
Point False
byte
short float
char boolean
int double
long
Type
Identifier
int myAge; Initial value
boolean isAMovie;
float maxItemCost = 17.98F;
Declaring Variables
class Rental {
private int instVar; // instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3; // local variable
}
}
Defining Variable Names
0 1 42 -23795 (decimal)
02 077 0123 (octal)
Integer literals
0x0 0x2a 0X1FF (hex)
365L 077L 0x1000L (long)
int a, b, c, d;
a = 2 + 2; // addition
b = a * 3; // multiplication
c = b - 2; // subtraction
d = b / 2; // division
e = b % 2; // returns the remainder of division
More on Arithmetic Operators
byte b1 = 1, b2 = 2, b3;
b3 = b1 + b2; // ERROR: result is an int
// b3 is byte
Examining Conversions and Casts
byte
short
int
long
• Java does not automatically “downcast.”
int var1 = 0;
var1 = 2 + 3 * 4; // var1 now equals 14
int var1 = 0;
var1 = 12 - 6 + 3; // var1 now equals 9
Sequential
Selection
Iteration
Transfer
Using Flow Control in Java
if ( boolean_expr )
General : statement1;
[else
statement2];
if (i % 2 == 0)
System.out.println("Even");
Examples: else
System.out.println("Odd");
… if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed greater than or
equal to 25 but less than or equal to 65");
else
System.out.println("Speed under 25");
int x = 3, y = 5; 1
if (x >= 0)
if (y < x)
System.out.println("y is less than x");
else
System.out.println("x is negative");
int x = 7; 2
if (x = 0)
System.out.println("x is zero");
switch ( integer_expr ) {
case constant_expr1:
statement1;
• Useful to
break;
select from
case constant_expr2:
several
statement2;
alternative
break;
integer values
[default: • Integer_expr
statement3;] must be byte,
} int, char, or
short.
More About the switch Statement
switch (choice) {
• Case labels
case 37:
must be
System.out.println("Coffee?");
constants.
break;
• Use break to
jump out of a
case 45:
switch.
System.out.println("Tea?");
• It is break;
recommended
to always default:
provide a System.out.println("???");
default. }
Looping in Java
while ( boolean_expr )
statement;
Example: int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Using the do…while Loop
int i = 0;
Example: do {
System.out.println("i = " + i);
i++;
} while (i < 10);
Using the for Loop
Example:
int x = 10; 1
while (x > 0);
System.out.println(x--);
System.out.println("We have lift off!");
int x = 10; 2
while (x > 0)
System.out.println("x is " + x);
x--;
int sum = 0; 3
for (; i < 10; sum += i++);
System.out.println("Sum is " + sum);
Implementing the break Statement
…
while (age <= 65) {
balance = (balance+payment) * (1 + interest);
if (balance >= 250000)
break;
age++;
}
…
Comparing Labeled break
and continue Statements
outer_loop:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
if (i + j > 7) break outer_loop;
if (i + j == 7) continue outer_loop;
System.out.println(i);
System.out.println(j);
}
}
…
Building Applications with Oracle9i
JDeveloper
What Is Oracle9i JDeveloper?
Command Area
Property
Editor System Navigator Inspector
Examining Workspaces
Navigator
pane
Structure
pane
What Are Projects?
Project
Project
files
Creating JDeveloper Items
• Invoked with
File > New
• Categorized by type
• Create any
JDeveloper element
Creating an Application Project
• Invoked after
project creation
• Specify:
– Name
– Package
– Extends
– Frame
• Invokes frame
details if adding
frame
Looking at the Directory Structure
Setting breakpoints:
• Manage multiple breakpoints
• Conditional breakpoints
• Define columns displayed in window
– Description
– Type
– Status, and so on
• Control scope of action
Global > Workspace > Project
Using the Debugger Windows
Methods Objects
Packages
Contained in a class
Object
Attributes references
Comparing Classes and Objects
• An object is an Movie
instance of a
class. public void displayDetails()
• Objects have their
public void setRating()
own memory.
• Class definitions private String title;
must be loaded to
private String rating;
create instances.
mov1 mov2
title: “Gone with…” title: “Last Action…”
rating: “PG” rating: “PG-13”
Creating Objects
j 3 mov1
title: null
rating: null
Using the null Reference
mov2
Declaring Instance Variables
Class variables:
• Belong to a class and are common to all instances
of that class
• Are declared as static in class definitions
public class Movie {
private static double minPrice; // class var
private String title, rating; // inst vars
title
rating
min title
Price rating
title
rating
Movie class variable Movie objects
Initializing Class Variables
acmevideo
CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les06
Access Modifiers
acmevideo acmetools
public public
protected
private
Object Life Cycle and Inner Classes
Overloading Methods
title : null
void anyMethod() { mov1 rating: “PG”
Movie mov1 = new Movie();
Movie mov2 = new Movie(); title: null
mov1.setRating("PG"); … mov2 rating: null
Initializing Instance Variables
• Queued reference
mov1
• Memory still occupied
title: “Gone...”
• Unreachable object rating: “PG”
• poll() for existence
• clear() for memory
collection
What Are Inner Classes?
Enclosing class
Defining Static Inner Classes
• 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");
Concatenating Strings
• Trim whitespace:
String trim(); String nospaces =
str.trim();
• Use String.valueOf():
String seven = String.valueOf(7);
String onePoint0 = String.valueOf(1.0f);
The SimpleDateFormat:
• Is a concrete class for formatting and parsing
dates in a locale-sensitive manner
• Allows you to start by choosing any user-defined
patterns for date-time formatting
• Uses time-pattern string to display the date:
– y year 1996
– M month in year July or 07
– m minute in hour 30
Using DecimalFormat
The DecimalFormat:
• Is a concrete subclass of NumberFormat for
formatting decimal numbers
• Allows for a variety of parameters and for
localization to Western, Arabic, or Indic numbers
• Uses standard number notation in format
public DecimalFormat(String pattern};
Guided Practice
b.
b.
// s3 begins with 2 spaces and ends with 2 spaces
String s3 = " Monday ";
System.out.println(s3.indexOf("day"));
System.out.println(s3.trim().indexOf("day"));
Using Regular Expressions
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
About System.out.println
Understanding System.out.println()
• System is a class in the java.lang package.
• out is a public final static (class) variable.
– Declared as a PrintStream object reference
• println() is an overloaded method of the
PrintStream class.
– PrintStream is a FilterOutputStream that
subclasses OutputStream
• System.err is also provided as a PrintStream
object reference to write to standard error.
About OutputStream and PrintStream
• Inheritance
• Constructors referenced by subclass
• Polymorphism
• Inheritance as an OO fundamental
Superclass
InventoryItem
Subclasses
Movie Game Vcr
Example of Inheritance
Movie
price
Movie movie1 = new Movie(); condition
2
3
Acme Video and Polymorphism
InventoryItem
calcDeposit(){…}
VCR Movie
calcDeposit(){…} calcDeposit(){…}
ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();
…
}
Using the instanceof Operator
[0] 1
[0] Action
[1] 2
[1] Comedy
[2] 4
[2] Drama
[3] 8
Creating an Array of Primitives
powers null
arrVar
1. Declare the array.
null
ClassName[] arrVar;
… or … arrVar
ClassName arrVar[]; null
null
null
2. Create the array object.
arrVar
Action
// Create array object syntax Comedy
arrVar = new ClassName[size];
Drama
3. Initialize the objects in the array.
Initializing the Objects in the Array
System.out.println
("Length is " + categories[2].length());
• ArrayIndexOutOfBoundsException occurs
when an array index is invalid:
String[] list = new String[4];
//The following throws ArrayIndexOutOfBoundsException
System.out.println(list[4]);
• NullPointerException occurs when you try to
access an element that has not been initialized:
Movie[] movieList = new Movie[3];
// The following will throw NullPointerException
String director = movieList[0].getDirector();
Multidimensional Arrays
[0][0] [0][1]
int[][] mdarr = new int[4][2];
mdarr[0][0] = 1;
mdarr[0][1] = 7; mdarr
1 7
[0]
0 0
[1]
0 0
[2]
[3] 0 0
main()Revisited
Abstract
InventoryItem
superclass
Concrete
Movie VCR
subclasses
Creating Abstract Classes
• An abstract method:
– Is an implementation placeholder
– Is part of an abstract class
– Must be overridden by a concrete subclass
• Each concrete subclass can implement the
method differently.
Defining Abstract Methods
Nonsteerable Steerable
Creating Interfaces
MyApplication
Sort
The movie sortObjects()
returns the asks a movie to
3 2
result of the compare itself with
comparison. another movie.
Movie
The Sortable Interface
Holds sortObjects()
Implements Sortable:
class myApplication {
Movie[] movielist;
… // build the array of Movie
Sort.sortObjects(movielist);
}
Using instanceof with Interfaces
Exception object
Handler
for this
Yes exception? No
Advantages of Java Exceptions:
Separating Error Handling Code
method2 method2
Exception
method3 method3 ex
Error
method4 code method4
If method3 ignores the The exception must be
error, then it will never be caught and handled
handled. somewhere.
Checked Exceptions, Unchecked
Exceptions, and Errors
Error Exception
Unchecked (run-time)
exceptions
What to Do with an Exception
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
Catching Multiple Exceptions
try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}
Cleaning Up with a finally Block
FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}
Catching and Handling Exceptions:
Guided Practice
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}
Catching and Handling Exceptions:
Guided Practice
void myMethod () {
try {
getSomething();
} catch (IndexOutOfBoundsException e1) {
System.out.println("Caught IOBException ");
} catch (Exception e2) {
System.out.println("Caught Exception ");
} finally {
System.out.println("No more exceptions ");
}
System.out.println("Goodbye");
}
Allowing an Exception Pass to the
Calling Method
catch (exception1 e) {
throw new exception2(…);
}
• Buttons
• Check boxes
• Combo boxes
• Text
• Lists
• Labels
Layout Management Overview
Border Layout
• Is based on a grid
• Allows components to span multiple rows and
columns
• Allows rows and columns to differ in size
• Uses the component’s preferred size to control
cell size
GridBag Constraints
External insets
Component
Cell position padding
Cell span
Expansion
weighting Anchoring
Fill rules
Using Layout Managers
Border
null
Vertical-
Flow
GridBag
Grid
Using Frames or Dialogs
Frame
Adding Components
Setting Pluggable Look and Feel
• Text controls
– JTextField
– JPasswordField
– JTextArea
– JEditorPane
– JTextPane
• Graphic controls
– JTree
– JTable
– JToggleButton
Swing Components in JDeveloper
System Context
Navigator menu
Code Editor
How to Add a Component to a Form
Click
menu bar
object in
Structure pane
to display Context menu when
menu bar right-clicking a menu
Sample Order Entry Application
Java Event Handling Model
• How it works:
– Event originates from source and generates an
event object.
– An event listener hears a specific event.
– An event handler determines what to do.
• Setting it up:
– Create an event source object.
– Create an event listener object implementing an
interface with methods to handle the event object.
– Write an event-specific method to handle the event.
– Register the listener object with the event source
for the specified event.
Event Handling Code Basics
Source
Event listener object
OK
Handler method
Source
Event listener object
OK
Notified Handler method
Source
Event listener object
OK Handler method:
save changes and quit
Event handler
methods
How to Define an Event Handler
in JDeveloper
3: Double-click the
right column to create the method.
Default Event Handling Code Style
Generated by JDeveloper
public void jbInit() throws Exception {
… Find
findButton.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
findButton_actionPerformed(e);
}
}); …
void findButton_actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
Completing the Event Handler Method
JavaBeans contain:
• Events that can interact with your Java application
• Properties that can be exposed
• Methods that can be invoked
JavaBeans support:
• Introspection/reflection
• Customization
• Persistence
Engineering for a Black Box Environment
Getter Setter
private
methods T var; methods
(public) T[] arr; (public void)
1 Bean registers
as a listener.
1. Develop a JavaBean
– Modified via code, class, or UI editors
2. Store the bean in an archive file
3. Create a JDeveloper library identifying the archive
4. Install the bean in JDeveloper’s Component
Palette, via its library name
5. Develop an application by using the JavaBean
component
1. Develop a JavaBean
Select the
parent class
Add a Simple Property
Type
Modifier
Add Events to a Bean
Oracle9i Oracle
Application Server Database
J2EE Certified Environment
JDBC
Connecting to a Database with Java
Client application
JDBC Relational DB
or applet
What Is JDBC?
2. Obtain a connection
6. Close connections
Step 1: Registering the Driver
OracleDriver
Database
JDBC calls commands
• Thin client
• OCI Database
• Server Based
•…
Oracle JDBC Drivers: Thin Client Driver
Applet
JDBC
Client Server
Oracle JDBC Drivers: OCI Client Drivers
Application
JDBC
OCI driver
Oracle 9i
ocixxx.dll
Client Server
Choosing the Right Driver
Applet Thin
Thin
EJB, servlet
(on the middle tier)
OCI
jdbc:<subprotocol>:<subname>
Database Identification
Protocol
jdbc:oracle:<driver>:@<database>
• Example using Oracle Thin JDBC driver:
– jdbc:oracle:thin:@myhost:1521:ORCL
JDBC URLs with Oracle Drivers
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");
Statement stmt = conn.createStatement();
Step 4: Executing SQL Statements
2. Obtain a connection
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM order_items
WHERE order_id = 2354");
4b: Submitting DDL Statements
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("CREATE TABLE temp (col1 NUMBER(5,2),
col2 VARCHAR2(30)");
Step 5: Processing the Query Results
import java.sql.*;
class TestJdbc {
public static void main (String args [ ]) throws SQLException {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myHost:1521:ORCL","scott", "tiger");
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery
("SELECT ename FROM emp");
while (rset.next ())
System.out.println (rset.getString ("ename"));
rset.close();
stmt.close();
conn.close();
}
}
Step 6: Closing Connections
PreparedStatement pstmt =
conn.prepareStatement
("UPDATE emp SET ename = ? WHERE empno = ?");
PreparedStatement pstmt =
conn.prepareStatement
("SELECT ename FROM emp WHERE empno = ?");
How to Execute a PreparedStatement
Java servlet
Data source
ConnectionPoolDataSource
JDBC
driver Database
Database
commands
Deploying Applications Using
Java Web Start
What Is Java Web Start?
1. Request application
2. Launch Web Start on local machine
3. Download the application
4. Launch the application (Draw)
1
HTTP
3
HTTP
2 4
Advantages of Web Start