comp 531 advanced programming - kuraztech
TRANSCRIPT
Comp 531
Advanced Programming
Computer Science Program
October, 2015
2
Chapter One
Introduction
Types of Computer Language
Programming languages may be divided into three general
types:
Machine languages
Assembly languages
High-level languages
Any computer can directly understand only its own
machine language, which is machine dependent
Assembly language forms English-like abbreviations to
represent elementary operations.
High-level languages allow programmers to write
instructions that look almost like everyday English and
contain commonly used mathematical notations.
The translators include assembler, compiler and
Interpreter 3
Overview of Java Programming
Java is a high level language.
1991 – Sun Microsystems initiates project “Green” with the
intent to develop a programming language for digitally
controlled consumer devices and computers.
The language OAK was developed by James Gosling with
the goal of using C++’s popularity.
OAK was later renamed to JAVA and released in 1995.
Can be used to create two types of programs: applications
and applets.
Robust: no pointers in java and no manual memory
handling.
4
Overview (cnt’d)
Powerful: massive libraries.
Java programs are portable.
Java promise: “Write once, run everywhere”.
Java differs from other programming languages in that it is
both compiled and interpreted language.
Java compilers produce the Java bytecode.
Java bytecodes are a set of instructions written for a
hypothetical computer, known as the Java virtual machine.
Bytecodes are platform-independent.
The JVM is an interpreter for bytecode.
5
Overview (cnt’d)
An interpreter reads the byte code and translates into a
sequence of commands that can be directly executed by
the computer.
Because the execution of every Java program is under the
control of the JVM, the JVM can contain the program and
prevent it from generating side effects outside of the
system.
6
Overview (cnt’d)
7
8
Object Oriented Programming
In the older styles of programming, a programmer who is
faced with some problem must identify a computing task
that needs to be performed in order to solve the problem.
Programming then consists of finding a sequence of
instructions that will accomplish that task.
But at the heart of object-oriented programming, instead
of tasks we find objects– entities that have behaviors,
that hold information, and that can interact with one
another.
Programming consists of designing a set of objects that
model the problem at hand.
9
Object Oriented (cnt’d)
For example, suppose you want to write a program that
automates the video rental process for a local video store.
The two main objects in this problem are the video and the
customer.
Then, specify for each object the relevant data and possible
operations to be performed on that data.
For a video object, the data might include: movie name, starring
actors, producer, production company, number of copies in stock
Some of the operations on a video object might include:
checking the name of the movie
reducing the number of copies in stock by one after a copy is rented
incrementing the number of copies in stock by one after a customer
returns a copy
10
Object Oriented (cnt’d)
In OO, data is critical – data is not allowed to move freely
around a system, but it is tied closely to the functions that
operate on it.
Data is protected because the data belonging to an object
can only be accessed and modified by the methods of that
object.
Different objects can 'talk' to each other through their
methods. In this way, Object A cannot directly modify data
belonging to Object B – but it can call a method of Object
B that in turn modifies the data.
11
Object Oriented (cnt’d)
To summarize the OO approach:
Emphasis on data, not procedure
Programs are made up of objects
Data is hidden from external functions
Objects can communicate with each other through methods
The basic concepts of OO are:
Objects and classes
Data abstraction and encapsulation
Inheritance
Polymorphism
12
Object Oriented (cnt’d)
Objects and Classes
Object:
Represent ‘things/objects’ from the real world, or from someproblem domain (example: “the red car down there in the carpark”)
A set of data items (fields) with operations (methods - thatimplement class behaviors) to manipulate them
object - usually a person, place or thing (a noun)
method - an action performed by an object (a verb)
Has characteristic behavior.
Combines data and operations in one place
An object is also known as an instance. E.g Ibsa is an instance of aStudent
13
Object Oriented (cnt’d)
Class:
Defines a type of object - a category of similar objects
(example: “automobiles”)
Specifies methods and data that type of object has
Map of a building(class) vs. building (object)
14
Object Oriented (cnt’d)
15
Object Oriented (cnt’d)
Class Declaration
The syntax for a simple class declaration is
modifiers class class-name
{
body
}
Where the optional modifiers may be one or more of the three
keywords {public, abstract, final},
Class-name is any valid identifier, and
Body is a sequence of declarations of variables, constructors,
and methods
16
17
Object Oriented (cnt’d)
Abstraction
Ignore details when appropriate
Think about what a method/object/class does, not how itdoes it
One of the fundamental ways in which we handle complexity
18
Object Oriented (cnt’d)
Encapsulation
Is the mechanism that binds together code and the data object
manipulates
Put related things in the same place
I.e. group related data and operations in an object
Each object has its own data and knows how to use it
Hide internal representation/implementation
Deny external access to internal fields/methods
Also called information hiding
19
Object Oriented (cnt’d)
Access an object through its interface:
Set of externally accessible fields and methods
Should not change even if internal implementation does
An analogy:
When you drive a car, you don’t have know the details of how many
cylinders the engine has or how the gasoline and air are mixed and
ignited.
Only have to know how to use the controls.
20
Object Oriented (cnt’d)
Inheritance
Inheritance is the process by which one object acquires the
properties of another object.
Allows reuse of implementation
Classical Inheritance: “is-a” relationship
Example: fruits and types of fruit (an apple is a type of fruit)
Goal of inheritance: code reuse
21
22
Object Oriented (cnt’d)
Polymorphism
The ability to take more than one form
In terms of the OOP, this means that a particular operation
may behave differently for different sub-classes of the same
class.
Informally: same instruction means different things to different
agents
E.g. “write a note” is similar but different on:
Computer
Paper
Technically: many objects can implement same interface in
their own way (writing to screen vs. file)
23
Object Oriented (cnt’d)
Object-oriented programming methods aim to achieve the
following:
To simplify the design and implementation of complexprograms.
To make it easier for teams of designers andprogrammers to work on a single software project.
To enable a high degree of reusability of designs and ofsoftware codes.
To decrease the cost of software maintenance.
Simplify communication of object
Security through data hiding
24
Variables
Variables are locations in memory in which values can be
stored. They have a name, a type, and a value.
A variable has a type and holds a single value while the
object may contain many variables
Every variable has a unique name which is designated
when the variable is declared.
A variable is created when it is declared, and it remains
alive until the method in which it is declared terminates.
The syntax for declaring a variable of any type is:
type-name variable-name
25
Variables (cnt’d)
Besides reference types, there are eight other types in
Java. These are called primitive types, to distinguish them
from reference types - to store the locations of objects in
the computer’s memory.
Their names and values are:
26
API, JDK, and IDE
Computer languages have strict rules of usage.
If you do not follow the rules when writing a program, the
computer will be unable to understand it.
The Java language specification and Java API define the
Java standard.
The Java language specification is a technical definition of
the language that includes the syntax and semantics of the
Java programming language.
The application program interface (API) contains
predefined classes and interfaces for developing Java
programs.
The Java language specification is stable, but the API is
still expanding.27
API…
Java comes in three editions:
Java Standard Edition (Java SE) - to develop client-side standalone
applications or applets.
Java Enterprise Edition (Java EE) - to develop server-side
applications, such as Java servlets and JavaServer Pages.
Java Micro Edition (Java ME) - to develop applications for mobile
devices
There are many versions of Java SE. The latest is Java SE
8.
JDK consists of a set of separate programs, each invoked
from a command line, for developing and testing Java
programs.
Besides JDK, you can use a Java development tool (e.g., Net-
Beans, Eclipse, etc) – provides IDE
28
Assignments
Read about:
Constructors
Method Override vs. overload
Abstract class vs. interface
29
Review Exercise
1. Implement quadratic equation of the form ax2+bx +c =0
by considering a,b,c as random numbers. Handle all
special cases
2. Write and run a Java program that generates four
random integers, determines their minimum, and prints
it.
3. Write and run a Java program that generates a random
double, determines which quintile of the unit interval it is
in, and reports it. A quintile is one of the five equal sized
pieces of the whole. The quintiles of the unit interval are
0 to 1/5, 1/5 to 2/5, 2/5 to 3/5, 3/5 to 4/5, and 4/5 to 1.
30
Review Exercise
4. Write and run a Java program that generates a random
integer and reports whether it is divisible by 2, by 3, or by
5. Hint: n is divisible by d if the remainder from dividing n
by d is 0.
5. Write and run a Java program that generates a random
year between 1800 and 2000 and then reports whether it
is a leap year. A leap year is an integer greater than
1584 that is either divisible by 400 or is divisible by 4
but not by 100. To generate an integer in the range 1800
to 2000, use int year = Math.round(200*x + 1800);
where x is a random float. The round( ) method of the
Math class returns the integer nearest the float passed to
it. The transformation y = 200x + 1800 converts a
number in the range 0 .5< x < 1 into a number in the
range 1800 <= y < 2000.31
Advanced Programming
Computer Science Program
33
Chapter Two
AWT and Swing
Objective
Within this chapter you will be introduced to many of
the Java components for constructing graphical user
interfaces (GUIs).
With the information in this chapter you will be able to
develop your own GUIs.
34
Introduction
A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
A GUI gives an application a distinctive “look” and “feel”.
There are two main sets of visual components and
containers for user interface design in JAVA:
AWT (Abstract Window Toolkit) - in package java.awt and
Swing - in package javax.swing
When Java was introduced, the GUI classes were bundled
in a library known as the Abstract Windows Toolkit (AWT).
35
AWT vs. Swing
AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs.
The AWT user-interface components were replaced by a more
robust, versatile, and flexible library known as Swing
components.
Swing components depend less on the target platform and use
less of the native GUI resource.
Swing components are painted directly on canvases using Java
code.
For this reason, Swing components that don’t rely on native GUI
are referred to as lightweight components, and AWT components
are referred to as heavyweight components.
36
AWT vs. Swing (cont’d)
AWT features include:
A rich set of user interface components.
A robust event-handling model.
Graphics and imaging tools, including shape, color, and font classes.
Swing features include:
All the features of AWT.
100% Pure Java certified versions of the existing AWT
component set (Button, Scrollbar, Label, etc.).
A rich set of higher-level components (such as tree view, list
box, and tabbed panes).
Pure Java design, no reliance on peers.
Pluggable Look and Feel.
37
Java GUI API
The GUI API contains classes that can be classified into
three groups:
component classes,
container classes, and
helper classes.
The component classes, such as JButton, JLabel, and
JTextField, are for creating the user interface.
The container classes, such as JFrame, JPanel, and
JApplet, are used to contain other components.
The helper classes, such as Graphics, Color, Font,
FontMetrics, and Dimension, are used to support GUI
components.
38
Java GUI API (cont’d)
39
Java GUI API (cont’d)
Class Object is the super class of the Java class hierarchy.
Component is the root class of all the user-interface
classes including container classes.
JComponent is the root class of all the lightweight Swing
components.
An instance of Container can hold instances of
Component.
Window, Panel, Applet, Frame, and Dialog are the
container classes for AWT components.
To work with Swing components, use Container, JFrame,
JDialog, JApplet, and Jpanel.
40
Java GUI API (cnt’d)
41
Common super classes of many of the Swing components
Frames
To create a user interface, you need to create either a
frame or an applet to hold the user-interface
components.
A top-level window (that is, a window that is not
contained inside another window) is called a frame in
Java.
A Frame has:
a title bar (containing an icon, a title, and the
minimize/maximize(restore-down)/close buttons),
an optional menu bar and
the content display area.
To create a frame, use the JFrame class
42
Frame
Example 1
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("MyFrame");
frame.setSize(400, 300); // Set the frame size
// Center a frame
frame.setLocationRelativeTo(null); //or .setLocation(300,200)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
}
}
43
Frame (cont’d)
44
JFrame is a top-level container to hold GUI components
Frame (cont’d)
Adding Components to a Frame
import javax.swing.JFrame;
import javax.swing.JButton;
public class FrameWithButton {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a button into the frame
JButton jbtOK = new JButton("OK");
frame.add(jbtOK);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}45
Frame (cont’d)
Adding Lablel
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FrameWithLabel {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a lable into the frame
JLabel jLblName = new JLabel(“First Name");
frame.add(jLblName);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}46
Layout Managers
Java’s layout managers provide a level of abstraction that
automatically maps your user interface on all window
systems.
The Java GUI components are placed in containers, where
they are arranged by the container’s layout manager.
Layout managers are set in containers using the
setLayout(aLayoutManager) method.
This section introduces three basic layout managers:
FlowLayout, GridLayout, and BorderLayout.
47
FlowLayout
Flowlayout
Is the simplest layout manager.
The components are arranged in the container from left to right in the
order in which they were added. When one row is filled, a new row is
started.
You can specify the way the components are aligned by using one of
three constants:
FlowLayout RIGHT,
FlowLayout.CENTER, or
FlowLayout.LEFT.
You can also specify the gap between components in pixels.
48
FlowLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout extends JFrame{
public ShowFlowLayout() {// Set FlowLayout, aligned left with horizontal gap 10
// and vertical gap 20 between components
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20) );
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
49
FlowLayout (cont’d)
/** Main method */public static void main(String[] args) {
ShowFlowLayout frame = newShowFlowLayout();
frame.setTitle("ShowFlowLayout");frame.setSize(200, 200);frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
}
50
Output
GridLayout
Arranges components in a grid (matrix) formation.
The components are placed in the grid from left to
right, starting with the first row, then the second, and
so on, in the order in which they are added.
51
GridLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {public ShowGridLayout() {
// Set GridLayout, 3 rows, 2 columns, and gaps 5 between
// components horizontally and vertically
setLayout(new GridLayout(3, 2, 5, 5));
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
52
GridLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the
frame
frame.setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE);
frame.setVisible(true);}
}
53
Output
BorderLayout
Divides a container into five areas: East, South, West,
North, and Center.
Components are added to a BorderLayout by using
add(Component, index), where index is a constant
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER.
54
BorderLayout
EXAMPLEimport javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame
{
public ShowBorderLayout() {
// Set BorderLayout with horizontal gap 5 and vertical gap 10
setLayout( new BorderLayout(5, 10));
// Add buttons to the frame
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
55
BorderLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowBorderLayout frame = new
ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the
frame
frame.setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE);
frame.setVisible(true);}
}
56
Output
Panels
With Java GUI programming, you can divide a window
into panels.
Panels act as subcontainers to group user-interface
components.
You add the buttons in one panel, then add the panel
into the frame.
You can use new JPanel() to create a panel with a
default FlowLayout manager or new
Panel(LayoutManager) to create a panel with the
specified layout manager.
57
Panels (cont’d)
Example 1import java.awt.GridLayout;
import javax.swing.*;
import java.awt.BorderLayout;
public class SimplePanel1 extends JFrame {
public SimplePanel1() {
// Create panel p1 for the buttons and set GridLayout
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 2));
//Add label and text field to the panel
p1.add(new JLabel("First Name"));
p1.add(new JTextField(8));
// Create panel p2 to hold a p1
JPanel p2 = new JPanel(new BorderLayout());
p2.add(p1, BorderLayout.NORTH);
p2.add (new JButton("Button in Panel 2"));
// add contents into the frame
add(p2);
}58
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
SimplePanel1 frame = new SimplePanel1();
frame.setTitle("Panel With Components");
frame.setSize(300, 100);
frame.setLocationRelativeTo(null); // Center the
frame
frame.setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE);
frame.setVisible(true);}
}
59
Panels (cont’d)
Example 2import java.awt.GridLayout;
import javax.swing.*;
import java.awt.BorderLayout;
public class TestPanels extends JFrame {public TestPanels() {
// Create panel p1 for the buttons and set GridLayout
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
//Add buttons to the panel
for (int i = 1; i <= 9; i++) {
p1.add(new JButton("" + i));
}
60
Panels (cont’d)
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
// Create panel p2 to hold a text field and p1
JPanel p2 = new JPanel(new BorderLayout());
p2.add (new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
p2.add(p1, BorderLayout.CENTER);
// add contents into the frame
add(p2, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
}
61
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
62
Output
The Font Class
You can create a font using the java.awt.Font class and set
fonts for the components using the setFont method in the
Component class.
The constructor for Font is:
Font(String name, int style, int size);
You can choose a font name from SansSerif, Serif,
Monospaced, Dialog, or DialogInput,
Choose a style from Font.PLAIN (0), Font.BOLD (1),
Font.ITALIC (2), and Font.BOLD Font.ITALIC (3), and
specify a font size of any positive integer.
63
Font (cont’d)
Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);
64
The Color Class
You can set colors for GUI components by using the
java.awt.Color class.
Colors are made of red, green, and blue components, each
represented by an int value that describes its intensity,
ranging from 0 (darkest shade) to 255 (lightest shade).
You can create a color using the following constructor:
public Color(int r, int g, int b);
Example:
Color color = new Color(128, 100, 100);
You can use the setBackground(Color c) and
setForeground(Color c) methods to set a component’s
background and foreground colors.
65
The Color Class (cont’d)
Example
JButton jbtOK = new JButton("OK");
jbtOK.setBackground(color);
jbtOK.setForeground(new Color(100, 1, 1));
Alternatively, you can use one of the 13 standard colors
(BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED,
WHITE, and YELLOW) defined as constants in
java.awt.Color.
The following code, for instance, sets the foreground color
of a button to red:
jbtOK.setForeground(Color.RED);
66
The Color Class (cont’d)
Exampleimport java.awt.GridLayout;
import java.awt.Color;
import javax.swing.*;
public class ColorExample extends JFrame{
public ColorExample(){
JFrame jf = new JFrame("Color Frame");
setLayout(new GridLayout(1,2));
Color color = new Color(128, 100, 100);
JButton bc1 = new JButton("Left Button");
JButton bc2 = new JButton("Right Button");
bc1.setBackground(color);
bc2.setForeground(new Color(250,0, 0));
//bc2.setForeground(Color.BLUE);
add(bc1);
add(bc2);}
67
The Color Class (cont’d)
public static void main(String[] args){
ColorExample ce = new ColorExample();
ce.setSize(300,150);
ce.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
ce.setLocationRelativeTo(null);
ce.setVisible(true);}
}
68
Image Icons
import javax.swing.*;
import java.awt.*;
public class ImageExample extends JFrame {
public ImageExample() {
ImageIcon homeIcon = new ImageIcon("src/home.gif");
ImageIcon birdIcon = new ImageIcon("src/bird.gif");
ImageIcon mailIcon = new ImageIcon("src/mail.gif");
setLayout(new GridLayout(1, 3, 5, 5));
add(new JLabel(homeIcon));
add(new JButton(birdIcon));
add(new JLabel(mailIcon));
}
69
Image Icons (cont’d)
/** Main method */
public static void main(String[] args) {
ImageExample frame = new ImageExample();
frame.setTitle("TestImageIcon");
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
70
Event Handling
Event and Event Source
When you run a Java GUI program, the program interacts with
the user, and the events drive its execution.
An event can be defined as a signal to the program that
something has happened.
Events are triggered either by external user actions, such as
mouse movements, button clicks, and keystrokes, or by
internal program activities, such as a timer.
The program can choose to respond to or ignore an event.
The component that creates an event and fires it is called the
source object or source component.
For example, a button is the source object for a button-clicking
action event.
An event is an instance of an event class.
71
Event Handling
Java has a number of events and event handlers.
Java.awt.event –is the main package
It is up to the programmer to decide what to be
executed, how to handle the generated event, etc
There are more than 16 event types in java.
Eventhandler and ActionListener are the two
important aspects in event manipulation
Adding Listener helps to organize the action(event) to
be done after the button or the GUI control is selected
ActionListner is the main Interface in event handling
72
Event Handling (cont’d)
73
An event is an object of the EventObject class.
Event Handling (cont’d)
Listeners, Registrations, and Handling Events
Java uses a delegation-based model for event handling:
a source object fires an event, and an object
interested in the event handles it. The latterobject is called a listener.
For an object to be a listener for an event on a source object,
two things are needed:
The listener object must be an instance of the
corresponding event-listener interface to
ensure that the listener has the correct methodfor processing the event. The following table lists
event types, the corresponding listener interfaces,
and the methods defined in the listener interfaces.
The listener object must be registered by the
source object. Registration methods depend on74
Event Handling (cont’d)
Example 1import javax.swing.*;
import java.awt.event.*;
public class HandleEvent extends JFrame{
public HandleEvent() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);
add(panel); // Add panel to the frame 75
Event Handling (cont’d)
// Register listeners
OKListenerClass listener1 = new
OKListenerClass();
CancelListenerClass listener2 = new
CancelListenerClass();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2);}
public static void main(String[] args) {
JFrame frame = new HandleEvent();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE);
76
Event Handling (cont’d)
class OKListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}
class CancelListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Cancel button clicked");
}
}
77
Event Handling (cont’d)
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyGUI extends Jframe
implements ActionListener {
private JButton clickme = new JButton("ClickMe");
private JButton tests = new JButton("Test");
public MyGUI() {
// Add clickme to the GUI and assign it a listener
setLayout(new GridLayout(2, 0, 5, 5));
add(clickme);
add(tests);clickme.addActionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;setSize(200,200);setVisible(true);
78
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clickme) {
tests.setText("Clickme button clicked");
}
} // actionPerformed()
public static void main(String args[]) {
MyGUI gui = new MyGUI();
}
} // MyGUI class
79
Example 3
import javax.swing.*; // Packages used
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener{
private JLabel prompt = new JLabel("Distance in miles: ");
private JTextField input = new JTextField(6);
private JTextArea display = new JTextArea(10,20);
private JButton convert = new JButton("Convert!");
public Converter() {
setLayout(new FlowLayout());
add(prompt);
add(input);
add(convert);
add(display);
display.setLineWrap(true);
display.setEditable(false);
convert.addActionListener(this);
} // Converter()
80
public void actionPerformed( ActionEvent e ) {
//CHECK TO ACCEPT ONLY NUMBERS
double miles;
try{
miles = Double.valueOf(input.getText()).doubleValue();
}
catch ( NumberFormatException ex )
{
JOptionPane.showMessageDialog(null, "Please Enter Only Number" );
return;
} // end catch
display.setText("");
double km = miles/0.62;
display.append(miles + " miles equals " + km + " kilometers\n");
} // actionPerformed()
81
public static void main(String args[]) {
Converter f = new Converter();
f.setSize(400, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); // Quit the application
}
});
} // main()
} // Converter class
82
More Examples
Checkbox- CheckBoxTest.java
Text Area – TextArea.java
Combobox – ComboBoxDemo.java – uses
DescriptionPanel.java class
Lists – ListTest.java
Tree – SimpleTree.java
Menu – SimpleTextEditor.java
Progress Indicators – ProgressBarDemo.java
83
Overview of Java Applets
Applet is a browser dependent program of java
In applet, methods like init(),paint() etc are included
There is no main() method in applet
Package:- import java.applet.*;
Java application uses JFrame but java applet uses
JApplet
Java application saved by filename.java and run by
javac filename
But, java applets needs another html file and save
by filename.html and run by appletviewer
filename.html84
Cont..
Basic drawing Tools:
Some of the known functions for drawing are:
drawLine()-x,y coordinates and length and height
drawRect();
fillRect();
drawPolygon()
drawOval();
drawstring();-gin-bcoordinates, end-coordinates
85
Cont..
for irregular shapes-we use drawPolygon()
eg:
int x[]={10,20,30,40,50,60};
int y[]={60,50,40,30,20,10};
int p=6;
drawPolygon(x,y,p);//hexagon
86
Examples
Eg1: public class eg1 extends Japplet{
Public void init()
{setBackground(Color.red);
}
Public void paint(Graphics g)
{ g.setColor(Color.blue);
g.fillRect(0,0,100,100);
}
}
87
Examples
import java.awt.*;
import java.applet.*;
public class Applet1 extends JApplet {
public void paint(Graphics g)
{
g.fillRect(30, 20, 200, 200);
g.clearRect(50, 30,70,50);
g.drawRect(60,50,40,20);
g.drawLine(10,50,250,55);
}}88
Examples(applet)
Eg html file for a java class name Eg;
<html>
<head>the result</head>
<body>
<applet code=”Eg.class” width=250 height=250>
</applet></body></html>
89
Advanced Programming
Computer Science Program
91
Chapter Three
Streams and File I/O
Introduction
Data stored in variables, arrays, and objects are
temporary.
To permanently store the data created in a program,
you need to save them in a file on a disk or a CD.
Computers use files for long-term retention of large
amounts of data.
We refer to data maintained in files as persistent
data.
In this chapter, we discuss Java’s powerful file-
processing and stream input/output features.
92
Data Hierarchy
Bit - smallest data item in a computer
character set is the set of all the characters used to write
programs and represent data items.
Characters in Java are Unicode characters composed of
two bytes.
Java contains a data type, byte, that can be used to
represent byte data.
Fields are composed of characters or bytes(E.g. Name)
Record is a group of related fields (E.g Id, name, sex, etc
for employee record)
A file is a group of related records. E.g all employee
records of an organization.
Database – group of related files.
93
Files and Streams
Java views each file as a sequential stream of bytes.
The term “stream” refers to ordered data that is read from
or written to a file.
File streams can be used to input and output data as either
characters or bytes.
Streams that input and output bytes to files are known as
byte-based streams.
Streams that input and output characters to files are known
as character-based streams.
Files that are created using byte-based streams are
referred to as binary files.
Files created using character-based streams are referred
to as text files.
94
Files and Streams (cont’d)
95
Java’s view of a file of n bytes.
Files and Streams (cont’d)
Computers do not differentiate binary files and text
files.
All files are stored in binary format, and thus all files
are essentially binary files.
Encoding and decoding are automatically performed
for text I/O.
96
Files and Streams (cont’d)
The program receives data through an input object
and sends data through an output object.
97
Files and Streams (cont’d)
98
Text I/O requires encoding and decoding,
whereas binary I/O does not.
Files and Streams (cont’d)
Binary I/O is more efficient than text I/O, because
binary I/O does not require encoding and decoding.
Binary files are independent of the encoding scheme
on the host machine and thus are portable.
Java programs on any machine can read a binary file
created by a Java program.
This is why Java class files are binary files. Java class
files can run on a JVM on any machine.
99
Class FIle
Useful for retrieving information about files or directories
from disk.
Objects of class File do not open files or provide any file-
processing capabilities.
However, File objects are used frequently with objects of
other java.io classes to specify files or directories to
manipulate.
Creating File Objects
public File( String name )
specifies the name of a file or directory toassociate with the File object.
100
Class File (cont’d)
Example
import java.io.File;
public class TestFileClass {
public static void main(String[] args) {File file = new
File("C:/Users/Abdi/Desktop/realitypod.com_files/welcome.java");
System.out.println("Does it exist? "+ file.exists() );
System.out.println("The file has " + file.length() + " bytes");
System.out.println("Can it be read? " + file.canRead());
System.out.println("Can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it hidden? " + file.isHidden());
System.out.println("Name of the file? " + file.getName());
System.out.println("Parent Directory? " + file.getParent());
System.out.println("Absolute path is " +
file.getAbsolutePath());
System.out.println("Last modified on " +
new java.util.Date(file.lastModified()));
}
}101
File Input and Output
A File object encapsulates the properties of a file or a path but
does not contain the methods for creating a file or for
reading/writing data from/to a file.
In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
The objects contain the methods for reading/writing data from/to
a file.
Writing Data Using PrintWriter
The java.io.PrintWriter class can be used to create a file and write
data to a text file.
First, you have to create a PrintWriter object for a text file as follows:
PrintWriter output = new PrintWriter(filename); Then, you can invoke the print, println, and printf methods on the
PrintWriter object to write data to a file.
102
File Input and Output (cont’d)
Example 1
import java.io.*;
public class WriteData {
public static void main(String[] args) throws Exception {
File file = new File("score.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
PrintWriter output = new PrintWriter(file);
//Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
103
File Input and Output (cont’d)
Example 2
import java.io.File;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws Exception {
File file = new File("scores.txt");
if (file.exists()) {
// Create a Scanner for the file
Scanner input = new Scanner(file);
while (input.hasNext()) {
String firstName = input.next();
String mi = input.next();
String lastName = input.next();
int score = input.nextInt();
System.out.println(firstName + " " + mi + " " + lastName + " " +
score);
}
104
File Input and Output (cont’d)
//close the file
input.close();
}
else{
System.out.println("File does not exist");
}
}
}
105
File Input and Output (cont’d)
Example 2 import java.util.Scanner;
import javax.swing.JFileChooser;
public class FileGUI {
public static void main(String[] args) throws Exception {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(null) ==
JFileChooser.APPROVE_OPTION) {
// Get the selected file
java.io.File file = fileChooser.getSelectedFile();
// Create a Scanner for the fileScanner input = new Scanner(file);// Read text from the filewhile (input.hasNext()) {System.out.println(input.nextLine());}// Close the file
106
FileInputStream/FileOutputStream
FileInputStream/FileOutputStream is for reading/writing
bytes from/to files.
A java.io.FileNotFoundException will occur if you attempt
to create a FileInputStream with a nonexistent file.
Example
import java.io.*;
public class TestFileStream {
public static void main(String[] args) throws IOException {
// Create an output stream to the file
FileOutputStream output = new FileOutputStream("temp.txt",
true); //If append is true, data are appended to the existing file.
107
FileInputStream/FileOutputStream(cont’d)
// Output values to the file
for (int i = 1; i <= 10; i++)
output.write(i);
// Close the output stream
output.close();
// Create an input stream for the file
FileInputStream input = new FileInputStream("temp.txt");
// Read values from the file
int value;
while ((value = input.read()) != -1)
System.out.print(value + " ");
// Close the output stream
input.close();
}
}
108
The Serializable Interface
Serialization is the process of transforming an object into a
stream of bytes.
Deserialization is the reverse prorcess.
Objects of classes that implement the java.io.Seralizable
interface can be serializaed and deserialized.
Serialization allows objects to be easily saved to files or
sent to remote hosts over a network.
Classes whose instances to be stored in files or sent to
remote hosts should implement the java.io.Seralizable
interfaces.
ObjectInputStream/ObjectOutputStream enables you to
perform I/O for objects.
109
Serializable(cont’d)
Exampleimport java.io.*;
import java.io.Serializable;
public class TestObjectIOStream implements Serializable {
public static void main(String[] args) throws ClassNotFoundException,
IOException {
// Create an output stream for file object.dat
ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream("object.dat"));
// Write a string, double value, and object to the file
output.writeUTF("John");
output.writeDouble(85.5);
output.writeObject(new java.util.Date());
// Close output stream
output.close();
110
Serializable(cont’d)
// Create an input stream for file object.dat
ObjectInputStream input =
new ObjectInputStream(new FileInputStream("object.dat"));
// Write a string, double value, and object to the file
String name = input.readUTF();
double score = input.readDouble();
java.util.Date date = (java.util.Date)(input.readObject());
System.out.println(name + " " + score + " " + date);
// Close output stream
input.close();
}
}
111
Random-Access Files
Java provides the RandomAccessFile class to allow a
file to be read from and written to at random locations.
When creating a RandomAccessFile, you can specify
one of two modes
Mode “r” means that the stream is read-only,
and mode “rw” indicates that the stream allows both read and
write.
112
Random-Access Files(cont’d)
Example
import java.io.*;
public class TestRandomAccessFile {
public static void main(String[] args) throws IOException {
// Create a random access file
RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw");
// Write new integers to the file
for (int i = 0; i < 200; i++)
inout.writeInt(i);
// Display the current length of the file
System.out.println("Current file length is " + inout.length());
// Retrieve the first number
inout.seek(0); // Move the file pointer to the beginning
System.out.println("The first number is " + inout.readInt());
113
Random-Access Files(cont’d)
// Retrieve the second number
inout.seek(1*4); // Move the file pointer to the second number
System.out.println("The second number is " + inout.readInt());
// Retrieve the tenth number
inout.seek(9*4); // Move the file pointer to the tenth number
System.out.println("The tenth number is " + inout.readInt());
// Modify the eleventh number
inout.writeInt(555);
// Append a new number
inout.seek(inout.length()); // Move the file pointer to the end
inout.writeInt(999);
// Display the new length
System.out.println("The new length is " + inout.length());
// Retrieve the new eleventh number
inout.seek(10 * 4); // Move the file pointer to the eleventh number
System.out.println("The eleventh number is " + inout.readInt());
inout.close();
}
}114
Advanced Programming
Computer Science Program
116
Chapter Four
Multithreading
Introduction
One of the powerful features of Java is its built-in
support for multithreading.
Multithreading—the concurrent running of multiple
tasks within a program.
In many programming languages, you have to invoke
system-dependent procedures and functions to
implement multithreading.
This chapter introduces the concepts of threads and
how to develop multithreading programs in Java.
117
Thread Concepts
A program may consist of many tasks that can run
concurrently.
A thread is the flow of execution, from beginning to
end, of a task. It provides the mechanism for running
a task.
With Java, you can launch multiple threads from a
program concurrently.
These threads can be executed simultaneously in
multiprocessor systems.
118
Thread Concepts (cont’d)
119
(a) Here multiple threads are running on multiple CPUs.
(b) Here multiple threads share a single CPU.
Thread Concepts (cont’d)
Multithreading can make your program more
responsive and interactive, as well as enhance
performance.
For example,
A good word processor lets you print or save a file while you
are typing.
When downloading a large file, we can put multiple threads to
work—one to download the clip, and another to play it.
In some cases, multithreaded programs run faster
than single-threaded programs even on single-
processor systems.
120
Process vs. Threads
Process:
A process runs independently and isolated of other
processes.
It cannot directly access shared data in other processes.
The resources of the process are allocated to it via the
operating system, e.g. memory and CPU time.
Threads:
Threads are so called lightweight processes which have their
own call stack but an access shared data.
Every thread has its own memory cache. If a thread reads
shared data it stores this data in its own memory cache.
121
Thread States
Java thread can be in one of these states:
New – thread allocated & waiting for start()
Runnable – thread can execute
Blocked – thread waiting for event (I/O, etc.)
Terminated – thread finished
122
Thread States (cont’d)
123
Thread States
Creating and Executing Threads
The preferred means of creating multithreaded Java
applications is by implementing the Runnable
interface.
A Runnable object represents a “task” that can
execute concurrently with other tasks.
The Runnable interface declares a single method,
run.
You need to implement run method to tell the system
how your thread is going to run.
124
Creating and Executing Threads(cont’d)
125
Creating and Executing Threads(cont’d)
Example 1
public class HelloThread implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
Thread thread1 = new Thread( new
HelloThread() );
thread1.start();
}
}
126
Creating and Executing Threads(cont’d)
Example 2public class PrimeRun implements Runnable{
String msg;
PrimeRun (String mg)
{
msg=mg;
}
public void run()
{
for(int i=0;i<=5;i++)
{
System.out.println("Run method: "+msg);
}
}
127
Creating and Executing Threads(cont’d)
public static void main(String[] args) {
Thread dt1=new Thread(new PrimeRun("Run"));
Thread dt2=new Thread(new PrimeRun("Thread"));
dt1.start(); // this will start thread of object 1
dt2.start(); // this will start thread of object 2
}
}
128
Creating and Executing Threads(cont’d)
Example 3
public class TaskThreadDemo {
public static void main(String[] args) {
// Create tasks
PrintChar printA = new PrintChar('a', 100);
PrintChar printB = new PrintChar('b', 100);
PrintNum print100 = new PrintNum(100);
// Create threads
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
// Start threads
thread1.start();
thread2.start();
thread3.start();}
}
129
Creating and Executing Threads(cont’d)
// The task for printing a character a specified number of times
class PrintChar implements Runnable {
private char charToPrint; // The character to print
private int times; // The number of times to repeat
public PrintChar(char c, int t) {
charToPrint = c;
times = t;}
public void run(){
for (int i = 0; i < times; i++) {
System.out.print(charToPrint);
}
}
}
130
Creating and Executing Threads(cont’d)
// The task class for printing numbers from 1 to n for a given n
class PrintNum implements Runnable {
private int lastNum;
/** Construct a task for printing 1, 2, ... , n */
public PrintNum(int n) {
lastNum = n;
}
/** Tell the thread how to run */
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
}
}
}
Activity: Modify this program to display the result in a text area.
131
The Thread Class
The Thread class contains the constructors for
creating threads for tasks, and the methods for
controlling threads.
132
The Thread Class (cont’d)
You can use the yield() method to temporarily release
time for other threads.
Example:public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}
Every time a number is printed, the thread of the
print100 task is yielded. So each number is followed
by some characters.
133
The Thread Class(cont’d)
The sleep(long millis) method puts the thread to sleep
for the specified time in milliseconds to allow other
threads to execute.
Examplepublic void run() {
try {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
if (i >= 50) Thread.sleep(1) ;
}
}
catch (InterruptedException ex) {
}
}
134
The Thread Class(cont’d)
You can use the join() method to force one thread to wait
for another thread to finish.
Examplepublic void run() {
Thread thread4 = new Thread new PrintChar('c', 40));
thread4.start();
try {
f or (int i = 1; i <= lastNum; i++) {
System.out.print (" " + i);
if (i == 50) thread4.join();
}
}
catch (InterruptedException ex) {
}
}
A new thread4 is created. It prints character c 40 times.
The numbers from 50 to 100 are printed after thread
thread4 is finished.135
The Thread Class(cont’d)
To set priority for threads you can use setPriority
method.
Priorities are numbers ranging from 1 to 10.
Examp;le
thread3.setPriority(Thread.MAX_PRIORITY); //10
thread2.setPriority(Thread.NORM_PRIORITY); //5
thread1.setPriority(Thread.MIN_PRIORITY); //1
thread1.start();
thread2.start();
thread3.start();
136
Thread Pools
You learned how to create a thread to run a task like
this:
Runnable task = new TaskClass(task);
new Thread(task).start();
This approach is convenient for a single task
execution.
But it is not efficient for a large number of tasks,
because you have to create a thread for each task.
Starting a new thread for each task could limit
throughput and cause poor performance.
137
Thread Pool (cont’d)
A thread pool is ideal to manage the number of tasks
executing concurrently.
Java provides the Executor interface for executing
tasks in a thread pool and the ExecutorService
interface for managing and controlling tasks.
To create an Executor object, use the static methods
newFixedThreadPool(int).
If a thread completes executing a task, it can be
reused to execute another task.
ExecutorExample.java
138
Thread Synchronization
When multiple threads share an object and that object
is modified by one or more of the threads,
indeterminate results may occur.
If one thread is in the process of updating a shared
object and another thread also tries to update it, it is
unclear which thread’s update takes effect.
This can be solved by giving only one thread at a time
exclusive access to code that manipulates the
shared object.
Thread synchronization, coordinates access to
shared data by multiple concurrent threads.
139
Thread Synchronization (cont’d)
Example – without synchronizationimport java.util.concurrent.*;
public class AccountWithoutSync {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
executor.execute(new AddAPennyTask());
}
executor.shutdown();
// Wait until all tasks are finished
while (!executor.isTerminated()) {
}
System.out.println("What is balance? " + account.getBalance());
}
140
// A thread for adding a penny to the account
private static class AddAPennyTask implements Runnable {
public void run() {
account.deposit(1);
}
}
// An inner class for account
private static class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
141
public void deposit(int amount) {
int newBalance = balance + amount;
// This delay is deliberately added to magnify the
// data-corruption problem and make it easy to see.
try {
Thread.sleep(5);
}
catch (InterruptedException ex) {
}
balance = newBalance;
}
}
}
142
143
Thread Synchronization (cont’d)
A class is said to be thread-safe if an object of the class
does not cause a race condition in the presence of multiple
threads.
One approach is to make Account thread-safe by adding
the keyword synchronized in the deposit method as
follows:
public synchronized void deposit(double amount)
A synchronized method acquires a lock before it executes.
With the deposit method synchronized, the preceding
scenario cannot happen.
If Task 1 enters the method, Task 2 is blocked until Task 1
finishes the method,
144
Thread Synchronization (cont’d)
145
Thread Synchronization (cont’d)
A synchronized instance method implicitly acquires a
lock on the instance before it executes the method.
Java enables you to acquire locks explicitly, which
gives you more control for coordinating threads.
A lock is an instance of the Lock interface, which
defines the methods for acquiring and releasing locks.
lock() - Acquires the lock.
unlock() - Releases the lock.
newCondition() - creates any number of Condition objects,
which can be used for thread communications.
Example: AccountWithSyncUsingLock
146
Cooperation Among Threads
Thread synchronization suffices to avoid race
conditions by ensuring the mutual exclusion of
multiple threads in the critical region.
But, sometimes you also need a way for threads to
cooperate.
Conditions can be used to facilitate communications
among threads.
A thread can specify what to do under a certain
condition.
Conditions are objects created by invoking the
newCondition() method on a Lock object.
147
Cooperation Among Threads (cont’d)
Once a condition is created, you can use its await(),
signal(), and signalAll() methods for thread
communications.
The await() method causes the current thread to wait until the
condition is signaled.
The signal() method wakes up one waiting thread, and
the signalAll() method wakes all waiting threads.
Example: ThreadCooperation.java
148
149
Advanced Programming
Computer Science Program
151
Chapter four
Java Database Connectivity
Objective:
To introduce database systems,
and how to develop database
applications using Java.
152
Introduction
Database is an organized collection of data.
DBMS provides a mechanism to store, retrieve, organize
and modify data for many users.
Relational database – data is stored without consideration
of its physical structure.
SQL - a language used with relational database to perform
queries & to manipulate data.
E.g of RDBMSs: SQL Server, Oracle, Sybase, DB2,
MySQL, etc
Integrity Constraints - imposes a condition that all the
legal values in a table must satisfy.
153
Introduction (cont’d)
Three types of constraints: domain constraints,
primary key constraints, and foreign key
constraints. Domain constraints specify the permissible values for an
attribute.
The foreign key constraints define the relationships among
relations.
154
Introduction (cont’d)
155
JDBC
The Java API for developing Java database applications is
called JDBC.
JDBC provides Java programmers with a uniform interface
for accessing and manipulating a wide range of relational
databases.
Using the JDBC API, applications written in the Java can
execute SQL statements, retrieve results, present data in a
user-friendly interface, and propagate changes back to the
database.
The JDBC API can also be used to interact with multiple
data sources in a distributed, heterogeneous environment.
156
JDBC (cont’d)
157
Developing Database Applications
The JDBC API is a Java application program interface to
generic SQL databases.
The JDBC API consists of classes and interfaces for:
Establishing connections with databases,
Sending SQL statements to databases,
Processing the results of the SQL statements, and
Obtaining database metadata.
Four key interfaces are needed to develop any database
application using Java: Driver, Connection, Statement,
and ResultSet.
The JDBC API defines these interfaces.
The JDBC driver vendors provide implementation for
them. Programmers use the interfaces.
158
Developing Database Applications (cont’d)
A JDBC application:
loads an appropriate driver using the Driver interface,
connects to the database using the Connection interface,
creates and executes SQL statements using the Statement
interface, and
processes the result using the ResultSet interface if the
statements return results.
Note that some statements, such as SQL data
definition statements and SQL data modification
statements, do not return results.
159
Developing Database Applications (cont’d)
1. Loading drivers
An appropriate driver must be loaded using the
statement shown below before connecting to a
database.
Class.forName("JDBCDriverClass");
160
Database Driver Class
Access sun.jdbc.odbc.JdbcOdbcDriver
MySQL com.mysql.jdbc.Driver
Oracle oracle.jdbc.driver.OracleDriver
Developing Database Applications (cont’d)
2. Establishing connections.
To connect to a database, use the static method
getConnection(databaseURL) in the DriverManager
class, as follows:
Connection connection =
DriverManager.getConnection(databaseURL);
Example:
Connection connection = DriverManager.getConnection
("jdbc:odbc:ExampleMDBDataSource");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost/javabook
", "scott", "tiger");
161
Developing Database Applications (cont’d)
162
Database URL Pattern
Access jdbc:odbc:dataSource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSI
D
Developing Database Applications (cont’d)
3. Creating Statements
If a Connection object can be envisioned as a cable
linking your program to a database, an object of
Statement can be viewed as a cart that delivers SQL
statements for execution by the database and brings
the result back to the program
Once a Connection object is created, you can create
statements for executing SQL statements as follows:
Statement statement = connection.createStatement();
163
Developing Database Applications (cont’d)
4. Executing Statements
SQL DDL or update statement can be executed using
executeUpdate(String sql)
SQL query statement can be executed using
executeQuery(String sql).
The result of the query is returned in ResultSet.
For example, the following code executes the SQL
statement create table Temp (col1 char(5), col2 char(5)):
statement.executeUpdate("create table Temp (col1 char(5), col2
char(5))");
164
Developing Database Applications (cont’d)
The next code executes the SQL query select firstName,
mi, lastName from Student where lastName = 'Smith':
// Select the columns from the Student table
ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
165
Developing Database Applications (cont’d)
5. Processing ResultSet
The ResultSet maintains a table whose current row can be
retrieved.
The initial row position is null.
You can use the next method to move to the next row and
the various get methods to retrieve values from a current
row.
For example, the code given below displays all the results
from the preceding SQL query.
// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) + ". " + resultSet.getString(3));
166
Advanced Programming
Computer Science Program
168
Chapter 6
Networking in Java
Introduction
A network is a collection of computers and other devices that can
send data to and receive data from each other.
What a network program do?
Retrieve data
Send data – Once a connection between two machines is
established, Java programs can send data across the connection just
as easily as they can receive from it.
Peer-to-peer interaction
Games
Chat
File sharing
Servers
Searching the web
E-commerce
169
Introduction (cont’d)
When a computer needs to communicate with another
computer, it needs to know the other computer’s
address.
An Internet Protocol (IP) address uniquely identifies
the computer on the Internet.
TCP and UDP
TCP enables two hosts to establish a connection and
exchange streams of data.
TCP guarantees delivery of data and also guarantees that
packets will be delivered in the same order in which they
were sent.
UDP is a connectionless protocol.
170
Client/Server Computing
Networking is tightly integrated in Java.
Java API provides the classes for creating sockets to
facilitate program communications over the Internet.
Sockets are the endpoints of logical connections between
two hosts and can be used to send and receive data.
Java treats socket communications much as it treats I/O
operations; thus programs can read from or write to
sockets as easily as they can read from or write to files.
Network programming usually involves a server and one or
more clients.
171
Client/Server Computing (Cont’d)
The client sends requests to the server, and the server
responds.
The client begins by attempting to establish a connection
to the server.
The server can accept or deny the connection.
Once a connection is established, the client and the server
communicate through sockets.
The server must be running when a client attempts to
connect to the server.
The server waits for a connection request from a client.
172
The Server Socket
To establish a server, you need to create a server socket
and attach it to a port, which is where the server listens for
connections.
Port is a software address of a computer on the network.
The port identifies the TCP service on the socket.
A socket is a communication path to a port.
To communicate program over the network, give a way of
addressing the port. How? Create a socket and attach it to
the port.
Port numbers range from 0 to 65536, but port numbers 0 to
1024 are reserved for privileged services.
For instance, the email server runs on port 25, and the
Web server usually runs on port 80. 173
The Server Socket (cont’d)
You can choose any port number that is not currently
used by any other process.
The following statement creates a server socket
serverSocket:
ServerSocket serverSocket = new ServerSocket(port);
After a server socket is created, the server can use
the following statement to listen for connections:
Socket socket = serverSocket.accept();
174
The Client Socket
The client issues the following statement to request a
connection to a server:
Socket socket = new Socket(serverName, port);
ServerName is the server’s Internet host name or
IP address.
The following statement creates a socket at port 8000
on the client machine to connect to the host
130.254.204.36:
Socket socket = new Socket("130.254.204.36", 8000)
175
The Client Socket(cont’d)
The server creates a server socket and, once a
connection to a client is established, connects to the
client with a client socket.
176
Data Transmission Through Sockets
177
The server and client exchange data
through I/O streams on top of the socket.
Data Transmission…
Example: The client sends the radius to the server;
the server computes the area and sends it to the
client.
178
(a) The client sends the radius to the server.
(b) The server sends the area to the client.
Example: Sever
//Server.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame {
// Text area for displaying contents
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new Server();
}
public Server() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
179
Example: Sever(cont’d)
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new
ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new
DataInputStream(180
Example: Sever(cont’d)
outputToClient.writeDouble(area);jta.append("Radius received from client: " + radius + '\n');
jta.append("Area found: " + area + '\n');}
}
catch(IOException ex) {
System.err.println(ex);
}
}
}
181
Example: Client
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame {
// Text field for receiving radius
private JTextField jtf = new JTextField();
// Text area to display contents
private JTextArea jta = new JTextArea(); // IO streams
private DataOutputStream toServer;
private DataInputStream fromServer;
public static void main(String[] args) {
new Client();
}
182
Example: Client(cont’d)
public Client() {
// Panel p to hold the label and text field
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setHorizontalAlignment(JTextField.LEFT);
setLayout(new BorderLayout());
add(p, BorderLayout.NORTH);
add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(new TextFieldListener());
setTitle("Client");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
183
Example: Client(cont’d)
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost",8000);
// Socket socket = new Socket("130.254.204.36", 8000);
// Socket socket = new Socket("drake.Armstrong.edu", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(
socket.getInputStream());
// Create an output stream to send data to the server
toServer =
new DataOutputStream(socket.getOutputStream());
}
catch (IOException ex) {
jta.append(ex.toString() + '\n');
}
}
184
Example: Client(cont’d)
private class TextFieldListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
// Get the radius from the text field
double radius = Double.parseDouble(jtf.getText().trim());
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();
// Get area from the server
double area = fromServer.readDouble() ;
// Display to the text area
jta.append("Radius is " + radius + "\n");
jta.append("Area received from the server is "
+ area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
185
The InetAddress Class
To know who is connecting to sever, You can use the
InetAddress class.
InetAddress has three static methods
public static InetAddress getByName(String hostName)
public static InetAddress[] getAllByName(String hostName)
public static InetAddress getLocalHost( )
186
InetAddress (cont’d)
Example - A program that prints the address of host
import java.net.*;
public class HostName {
public static void main (String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.google.com");
}
}
}
187
InetAddress (cont’d)
Some computers have more than one Internet address.
Given a hostname, InetAddress.getAllByName() returns an
array that contains all the addresses corresponding to that
name.
Exampleimport java.net.*;
public class AllAddressOfGoogle {
public static void main (String[] args) {
try {
InetAddress[] addresses =
netAddress.getAllByName("www.google.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.google.com");
}188
InetAddress (cont’d)
Exampleimport java.net.*;
public class MyAddress {
public static void main (String[] args) {
try {
InetAddress address = InetAddress.getLocalHost( );
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find this computer's address.");
}
}
}
189
Serving Multiple Clients
Multiple clients are quite often connected to a single
server at the same time.
Typically, a server runs continuously on a server
computer, and clients from all over the Internet can
connect to it.
You can use threads to handle the server’s multiple
clients simultaneously.
Simply create a thread for each connection.
Here is how the server handles the establishment of
a connection:
190
while (true) {
Socket socket = serverSocket.accept(); // Connect to a client
Thread thread = new ThreadClass(socket);
thread.start();
}
The server socket can have many connections.
Each iteration of the while loop creates a new
connection.
Whenever a connection is established, a new thread is
created to handle communication between the server and
the new client; and this allows multiple connections to run
at the same time.
191
Advanced Programming
Computer Science Program
By Biruk
193
Chapter Seven
Remote Method Invocation
`
Objective:
Understand the role of distributed
objects in application development
Write Java programs that
communicate through distributed
object with remote objects
194
Introduction (cont’d)
Before the mid-80s, computers were
very expensive (hundred of thousands or even millions of
dollars)
very slow (a few thousand instructions per second)
not connected among themselves
After the mid-80s: two major developments
cheap and powerful microprocessor-based computers
appeared
computer networks
LANs at speeds ranging from 10 to 1000 Mbps
WANs at speed ranging from 64 Kbps to gigabits/sec
195
Introduction (cont’d)
Consequence
feasibility of using a large network of computers to work for the
same application; this is in contrast to the old centralized
systems where there was a single computer with its
peripherals.
Definition:
A distributed system is a collection of independent computers
that appears to its users as a single coherent system.
This definition has two aspects:
1. hardware: autonomous machines
2. software: a single system view for the users
196
Introduction (cont’d)
Why Distributed?
Resource and Data Sharing
printers, databases, multimedia servers, ...
Availability, Reliability
the loss of some instances can be hidden
Scalability, Extensibility
the system grows with demand (e.g., extra servers)
Performance
huge power (CPU, memory, ...) available
197
RMI
RMI is Java's distributed object solution.
RMI allows us to leverage on the processing power of
another computer. This is called distributed
computing.
RMI attempts to make communication over the
network as transparent as possible.
198
RMI (cont’d)
An RMI application is often composed of two separate
programs, a server and a client.
The object whose method makes the remote call is
called the client object. The remote object is called
the server object.
The computer running the Java code that calls the
remote method is the client for that call, and the
computer hosting the object that processes the call is
the server for that call.
199
Stubs and Parameter Marshaling
When client code wants to invoke a remote method on a
remote object, it actually calls an ordinary method on a
proxy object called a stub.
The stub resides on the client machine, not on the server.
A stub acts as a client local representative for the remote
object.
The client invokes a method on the local stub.
The stub packages the parameters used in the remote
method into a block of bytes. This packaging uses a
device-independent encoding for each parameter.
The process of encoding the parameters is called
parameter marshalling.
Purpose: to convert the parameters into a format suitable
for transport from one virtual machine to another. 200
Stubs…
The stub method on the client builds an information
block that consists of:
An identifier of the remote object to be used;
A description of the method to be called; and
The marshalled parameters.
The stub then sends this information to the server.
On the server side, a receiver object performs the
following actions for every remote method call:
It unmarshals the parameters.
It locates the object to be called.
It calls the desired method.
It captures and marshals the return value or exception of the call.
It sends a package consisting of the marshalled return data back to
the stub on the client.
201
202
RMI Registry
Is a simple name server provided for storing references to
remote objects.
The server is responsible for registering remote objects
with the registry service.
The registry keeps track of the addresses of remote
objects.
A remote objects handle can be stored using the methods
of java.rmi.Naming class.
A client can obtain a reference to a remote object by
looking up in the server registry.
203
204
The Server Side
To create a new remote object, first define an
interface that extends the java.rmi.Remote interface.
Purpose of Remote: to tag remote objects so that they
can be identified as such.
Your subinterface of Remote determines which
methods of the remote object clients may call.
A remote object may have many public methods, but
only those declared in a remote interface can be
invoked remotely.
205
//Hello Interface
import java.rmi.*;
public interface Hello extends Remote
{
public String hello() throws RemoteException;
}
206
The next step is to define a class that implements
this remote interface.
This class should extend
java.rmi.server.UnicastRemoteObject.
public class HelloImpl extends UnicastRemoteObject
implements Hello
UnicastRemoteObject provides a number of methods
that make remote method invocation work.
In particular, it marshals and unmarshals remote
references to the object.
207
//Hello Implementation
import java.rmi.*;
import java .rmi.server.*;
public class HelloImpl extends UnicastRemoteObject
implements Hello
{
public HelloImpl() throws RemoteException
{
}
public String hello() throws RemoteException
{
return "Hello World!";
}
}
208
Next, we need to write a server that makes the Hello
remote object available to the world. All it has is a
main( ) method.
It constructs a new HelloImpl object and binds that
object to the name “h" using the Naming class to talk
to the local registry.
A registry keeps track of the available objects on an
RMI server and the names by which they can be
requested.
209
//Hello Server
import java.rmi.*;
import java.rmi.server.*;
public class HelloServer
{
public static void main(String args [])
{
try
{
Naming.bind("h",new HelloImpl());
System.out.println("hello server is running");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
210
Client Side
Before a regular Java object can call a method, it needs a
reference to the object whose method it's going to call.
Before a client object can call a remote method, it needs a
remote reference to the object whose method it's going to
call.
A program retrieves this remote reference from a registry
on the server where the remote object runs.
It queries the registry by calling the registry's lookup( )
method.
The exact naming scheme depends on the registry; the
java.rmi.Naming class provides a URL-based scheme for
locating objects.
211
//Hello Client
import java.rmi.*;
public class HelloClient
{
public static void main(String args [])
{
try {
Hello h1=(Hello)Naming.lookup("rmi://localhost/h");
System.out.println(h1.hello());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
212
How to run?
I. Compile all using javac *.java
I. Give path c:\jdk1.6.0_06\bin
II. start rmiregistry
III. start java HelloServer
IV. java HelloClient
213
Reading Assignment
Read the difference between socket and RMI.
RMI is built on top of sockets, It translates method
calls and return values and sends those through
sockets.
Socket programming - you have to handle exactly
which sockets are being used, you specify TCP or
UDP, you handle all the formatting of messages
travelling between client and server. However, if you
have an existing program that talks over sockets that
you want to interface to, it doesn't matter what
language it's written in, as long as message formats
match.
214
RMI - hides much of the network specific code, you
don't have to worry about specific ports used (but you
can if you want), RMI handles the formatting of
messages between client and server. However, this
option is really only for communication between Java
programs. (You *could* interface Java RMI programs
with programs written in other languages, but there
are probably easier ways to go about it...)
RMI: remote method invocation. Strictly JAVA stuff.
outrside of java, known as RPC remote procedure
call.
Sockets is just a way to send data on a port to a
different
host, DATA not METHOD. it's up to you then to define
your own protocol. 215
You're talking apples and oranges here. Sockets
deals with the low-level workings of establishing and
maintaining connection between points in a network,
as far as the nature of a Java program as one running
inside a virtual machine allows.
RMI on the other hand, is just an application of
Sockets for transmitting messages between two Java
programs according to a set of rules and conditions.
What these rules and conditions do is they provide
you with a structure. Such that you don't have to worry
about the underlying workings of the connection and
can focus on higher-level design requirements.
Think of it like this, Without sockets RMI wouldn't
exist. But RMI is just a small application of Sockets.216