0% found this document useful (0 votes)
9 views177 pages

Java Programming and Internet Evolution

The document provides an overview of Java, its significance in programming, and its role in the evolution of the internet. It discusses Java's features, such as being object-oriented, portable, and secure, while also comparing it to other programming languages like C++. Additionally, it outlines the development environment, lifecycle of Java code, and the importance of applets in creating interactive web applications.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views177 pages

Java Programming and Internet Evolution

The document provides an overview of Java, its significance in programming, and its role in the evolution of the internet. It discusses Java's features, such as being object-oriented, portable, and secure, while also comparing it to other programming languages like C++. Additionally, it outlines the development environment, lifecycle of Java code, and the importance of applets in creating interactive web applications.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Java

Foundations, Programming and Practice

Presented by:
Mr. Bhushan Nemade, Anand Khandare
Shridhar Kamble and Sudhir Dhekane
Need for java ?

•It is a global network of computers


that communicate with each other
using a variety of protocols and
overcoming various communication
barriers.
•It is like International Telephone
System
 Internet is much bigger than what
we think
 More than 25 years old
 More than doubling every year
 Technology effect
 suddenly every body sees the need
for a technology
 like the radio or the TV
 10 terabytes flows everyday
Internet

 Use of internet
advertisement/elections/newspapers
 information is public
 Ubiquitous technology
 Network is the computer
 Intranets - internal TCP/IP nets
 PC accounts for 55% of total IT
 Applications tied to platform - API lock-
in
Internet Evolution

Internet everywhere
Internet appliances
On line connects Price based services
to internet Live communities
File & mail Secure payments ?
TCP/IP Multi media Authoring ?
Webpages Java ?
Netscape VRML ?
HTML ?
?
10% of ?
20% of Total
Market
Market Market
Early Internet

 Early Internet supported only email .


 File Transfer Protocol development - ftp sites.
 Network News was added to the Internet.
 Archie - A program to canvass anonymous ftp sites and create a database of
what is available
 Gopher- A menu-driven interface used to search for information.
 Archie and Gopher could answer questions only like ‘what FTP server
contains info about “xxxx” ‘
World Wide Web

 World Wide Web conceptualized by Tim Berners-Lee at CERN in


Switzerland
 Concept of Hypertext led to the development of the Hypertext Markup
Language (HTML)
 Tim Berners-Lee proposed the ‘Browser’ program
 Scientists at CERN designed a TCP/IP based protocol to share Hypertext
information called HTTP.
 WWW officially is described as a” Wide-area hypermedia information
retrieval initiative aiming to give universal access to a large universe of
documents.
HTML

 Hypertext -A little Hype and a Little Text.


 Hypertext point to information which can be local or remotely located.
 HTML -Derivative of the SGML( Standard Generalized Markup Language).
 HTML -information , commands for the Browser for formatting documents.
 HTML -The de-facto language for publishing on the Internet.
 Hypermedia- Hyper-links to Multimedia.
Internet Tools
 Browsers- A tool used to view documents on the WWW
 Web servers - Machines which run the HTTP-server
Software that respond to HTTP requests which it receives
 Authoring Tools - Editors specially made for editing HTML
documents
 Filters -Tools to convert legacy documents to HTML format
 Scripting -Languages used for scripting
 WAIS- Wide Area Information Servers (WAIS) for
indexing and doing full text searches
How does the Web work ?

 Web -Designed around Client/Server Architecture


 Web Clients ( Web Browsers ) -send requests for documents to any Web Server
 Web Server -Program that responds to HTTP requests
 Hyperlink
 Web client connects to the specified Web Server
 The server responds by sending the information asked for
 The Browser formats the received HTML data and displays it
How does the Web
Work
Send
Sendthe
the“INFORMATION
“INFORMATIONABOUT
ABOUT C-DAC
C-DACACTS”
ACTS”

HTTP

The
Theclient
clientsends
sendsan
anHTTP
HTTPmessage
messageto
toaacomputer
computer
running
running a Web Server program and asks foraadocument
a Web Server program and asks for document

The information
about
C-DAC ACTS

The
Theweb
webserver
serversends
sendsthe
thehypermedia
hypermediaHTML
HTMLdocuments
documentstotothe
theclient.
client.
You
Youend
endup
upseeing
seeingthe
thedocument
documenton
onyour
yourscreen
screen
Java and Java Computing
Java - An Introduction

 Java - The new programming language from Sun Microsystems


 Java -Allows anyone to publish a web page with Java code in it
 Java - CPU Independent language
 Created for consumer electronics
 Java - James , Arthur Van , and others
 Java -The name that survived a patent search
 Oak -The predecessor of Java
 Java is “C++ -- ++ “
Java From 10,000 Ft.

 According to the world, Java is...


 According to Sun, Java is...
 On closer inspection, Java is
According to the World,
Java Is...

 Snazzy Web pages


 The cross-platform language we want
 The rest-of-the-worlds answer to Bill
 The C++ replacement we need
 The C++ replacement we dont need
 A bunch of hype
According to Sun, Java is...

 Simple and Powerful


 Object Oriented
 Portable
 Architecture Neutral
 Distributed
 Multi-threaded
 Robust, Secure/Safe
 Interpreted
 High Performance
 Dynamic pogramming language/platform.

Buzzword compliant!
On Closer Inspection, Java
is...

 Simple
 Pure
 Portable
 Surprisingly effective
As a whole, Java is a Comprehensive
Programming Solution

 Object Oriented
 Portable
 High Performance
 Geared for Distributed Environments
 Secure
Java as Object Oriented

 “Objects all the way down”


 Simple and Familiar: “C++ Lite”
 No Pointers!
 Garbage Collector
 Dynamic Binding
 Single Inheritance with “Interfaces”
Java as Portable

 Unlike other language compilers, Java complier generates code


(byte codes) for Universal Machine.
 Java Virtual Machine (JVM): Interprets bytecodes at runtime
 Architecture Neutral
 No Link Phase
 Higher Level Portable Features: AWT, Unicode
Total Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows 95 Macintosh Solaris Windows NT


Java

Write Once, Run Anywhere


Architecture Neutral & Portable

 Java Compiler -Java source code to bytecode


 Bytecode - an intermediate form, closer to machine
representation
 A virtual machine on any target platform interprets the
bytecode
 Porting the java system to any new platform involves writing an
interpreter that supports the Java Virtual Machine
 The interpreter will figure out what the equivalent machine
dependent code to run
Java as High Performance

 JVM uses “lean and mean” bytecodes


 Small binary class filtes
 Just-in-time Compilers
 Multithreading
 Native Methods
Java in the World of Distributed
Computing

 Class Loader
 Lightweight Binary Class Files
 Multithreading
 Dynamic
 Good communication constructs
 Secure
Java as Secure

 Language designed as safe


 Strict compiler
 Dynamic Runtime Loading (Verifier)
 Runtime Security Manager
Object Oriented Languages -a
omparison

Objective
Feature C++ C Ada Java

Encapsulation Yes Yes Yes Yes


Inheritance Yes Yes No Yes
Multiple Inherit. Yes Yes No No
Polymorphism Yes Yes Yes Yes
Binding (Early/Late) Both Both Early Late
Concurrency Poor Poor Difficult Yes
Garbage Collection No Yes No Yes
Genericity Yes No Yes No
Class Libraries Yes Yes Limited Yes
Java better than C++ ?

 No Typedefs, Defines, or Preprocessor


 No Global Variables
 No Goto statements

?
 No Pointers
 No Unsafe Structures
 No Multiple Inheritance
 No Operator Overloading
 No Automatic Coercions
 No Fragile Data Types
Basic Data Types

 Types
boolean either true of false
char 16 bit Unicode 1.1
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (singed)
float 32-bit floating point (IEEE 754-1985)
double 64-bit floating point (IEEE 754-1985)
 String (class for manipulating strings)
 Java uses Unicode to represent characters internally
Java Integrates
Power of Compiled Languages
and
Flexibility of Interpreted
Languages
Two Types of JavaApplications

 Different ways to write/run a Java codes are:


Application- A stand-alone program that can be
invoked from command line . A program that
has a “main”
main method
Applet- A program embedded in a web page ,
to be run when the page is browsed . A
program that contains no “main” method

 Application -Java interpreter


 Applets- Java enabled web browser (Linked to HTML via
<APPLET> tag. in html file)
Java Environment/
Life Cycle of Java Code
Runtime
Compile-time Environment
Environment Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)

Just in
Java
Time
Interpreter Java
Java Compiler
Bytecodes Virtual
Java move locally machine
Compiler or through
network
Runtime System

Java
Bytecod Operating System
e
(.class )
Hardware
Java Development Kit

 javac - The Java Compiler


 java - The Java Interpreter
 jdb- The Java Debugger
 appletviewer -Tool to run the applets

 javap - to print the Java bytecodes


 javaprof - Java profiler
 javadoc - documentation generator
 javah - creates C header files
Hello Internet

// [Link]: Hello Internet program


class HelloInternet
{
public static void main(String args[])
{
[Link](“Hello Internet”);
}
}
Program Processing

 Compilation
# javac [Link]
results in [Link]
 Execution
# java HelloInternet
Hello Internet
#
Simple Java Applet

// [Link]: A sample applet


import [Link];
public class HelloWorld extends Applet {
public void paint(Graphics g)
{
[Link](“Hello World !”,25,25);
}

}
Calling an Applet

<HTML>
<TITLE> Hello Worls Applet </TITLE>
<APPLET code=“[Link]” width=500 height=500>
</APPLET>
</HTML>
Execution of Applets

2 4 5
1 3
APPLET [Link] Create Accessing The
Development AT C-DAC’S Applet from browser
“[Link]” WEB tag in CRAY Corp. creates
AT SERVER HTML (USA) a new
CDAC-India documen window and
t a new
thread and
then runs
the code
Hello Java
<app=
“Hello”> The Internet
Hello
Web Perspective

 How did Web interactions work?


 How do they work with Java?
 Distributed Java objects and the Web
Classical Web Perspective
Java Web Perspective
Significance of
downloading Applets

 Interactive WWW
 Flashy animation instead of static web pages
 Applets react to users input and dynamically change
 Display of dynamic data
 WWW with Java - more than a document publishing medium

[Link]
[Link]
Power of Java and the Web

 Deliver applications, not just information


 Eliminate porting
 Eliminate end-user installation
 Slash software distribution costs
 Reach millions of customers - instantly
Lifecycle of Java Code
Bytecode Verifier

 Called when class is first loaded in runtime environment


 Verifies bytecodes meet certain set of properties
 Verifier uses Theorem Prover
 Verified code runs faster
 After verification, interpreter defines memory layout
Class Loader

 Unique “Namespace” for each origin


 Local namespace classes are called “built-ins”
 Prevents class “spoofing”
Security Manager

 Prevents unauthorized disk read/writes


 Restricts network access
 Other access restrictions (native methods)
 Implementation is browser dependent
General Language
Features

 C/C++ like syntax


 No pointers
 Objects all the way down
 Objects request services of other objects through messages
 Messages result in invocation of class methods
Removed From C++

 Operator overloading
 Pointers and Array/pointers
 Multiple-inheritance of implementation
 Enum, typedef, #define
 Copy constructors, destructors
 Templates
 And other stuff....
Added or Improved over C+
+

 Interfaces: type Vs. class


 Garbage collection
 Exceptions (More powerful than C++)
 Strings
 Instanceof
 Package
 Multi-threads
Rich Object Environment

 Core Classes
language
Utilities
Input/Output
Low-Level Networking
Abstract Graphical User Interface
 Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
Main Packages

 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
Java Fundamentals
Constructs
Graphics
Multithreading
Streams and
Networking
Networking
53
Unit I--Java Constructs

 what is Java, basic constructs, including


 classes and objects
 constructors,
 this and super keywords,
 inheritance,
 abstract classes, interfaces,
 inner classes,
 exceptions.

54
Unit II--Graphics Programming

 How to build Graphical User Interfaces in Java:


 GUI components,
 event handling,
 layout management.

55
Unit III--Advanced Features

 Applets,
 Threads,
 Streams I/O,
 Networking

56
Unit I -- What is Java ?

 A programming language:
 Object oriented (no friends, all functions are members of classes, no
function libraries -- just class libraries)
 simple (no pointer arithmetic, no need for programmer to deallocate
memory)
 platform independent
 dynamic
 interpreted

57
Types

 Eight basic types


 4 integers (byte, short, int, short) [ int a; ]
 2 floating point (float, double) [ double a;]
 1 character (char) [ char a; ]
 1 boolean (boolean) [ boolean a; ]
 Everything else is an object
 String s;

58
Classes and objects

 declaring a class
class MyClass {
member variables;

member functions () ;

} // end class MyClass

59
Java programs

 Two kinds
 Applications
 have main()
 run from the OS prompt
 Applets
 have init(), start(), stop(), paint(), update(), repaint(), destroy()
 run from within a web page

60
The first Java Application

class MyApp {
public static void main(String s [ ] ) {
[Link](“Hello World”);
}
} // end class MyApp

61
Declaring and creating objects

 declare a reference
 String s;

 create/define an object
 s = new String (“India”);

India

62
Arrays (are objects in Java)

 declare
 int a [ ] ; // 1-dim
 int [ ] b ; // 1-dim
 int [ ] c [ ]; // 2-dim
 int c [ ][]; // 2-dim
 allocate space
 a = new int [7];
 c = new int [7][11];

63
Arrays have length

 used to retrieve the size of an array


 int a [ ] = new int [7]; // 1-dim
 [Link]([Link]); will print ‘7’

 int b [ ] [ ] = new int [7] [11];


 [Link]([Link]); will print ‘7’
 [Link]([Link] * b[0].length); will print ‘77’

64
… this is because

 Let int [][][][] array = new int [7][11][10][21] , then …

 [Link] * array[3].length * array[3][5].length * array[3][5]


[2].length is 7 x 11 x 10 x 21

65
… this is because

66
Constructors

 All objects are created through constructors


 They are invoked automatically
class Weight {
int lb; int oz;
public Weight (int a, int b ) {
lb = a; oz = b;
}
}

67
this keyword

 refers to “this” object (object in which it is used)


 usage:
 with an instance variable or method of “this” class
 as a function inside a constructor of “this” class
 as “this” object, when passed as parameter

68
this :: with a variable

 refers to “this” object’s data member


class Weight {
int lb; int oz;
public Weight (int lb, int oz ) {
[Link] = lb; [Link] = oz;
}
}

69
this :: with a method

 refers to another method of “this” class


class Weight {
public int m1 (int a) {
int x = this.m2(a); return x;
}
public int m2(int b) { return b*7 ; }
}

70
this :: as a function inside a constructor of “this” class

 must be used with a constructor


class Weight {
int lb, oz;
public Weight (int a, int b) { lb = a; oz = b; }
}
public Weight (int x) { this( x, 0); }
}

Constructor is also overloaded (Java allows overloading of all


methods, including constructors)
71
this :: as “this” object, when passed as
parameter

 refers to the object that used to call the calling method

class MyApp {
int a;

public static void main(String [] s ) { (new MyApp()).myMethod(); }

public void myMethod() { yourMethod(this); }

public void yourMethod(MyApp inMyApp) { inMyApp.a = 77; }


}

72
static keyword

 means “global”--all all objects refer to the same storage.


 applies to variables or methods”
 usage:
 with an instance variable of a class
 with a method of a class

73
static keyword (with
variables)

class PurchaseOrder {
private static int POCount; // var. ‘a’ is shared by all objects of this class

public static void main(String [] s ) {


PurchaseOrder po1 = new PurchaseOrder();
[Link]();
}

public void updatePOCount() { POCount++; }


}

74
static keyword (w/
methods)
class Math {
public static double sqrt(double x) {
// calculate
return result;
}
}
class MyApp {
public static void main(String [] s ) {
double dd;
dd = [Link](7.11);
}
}
75
Inheritance (subclassing)

class Employee {
protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}

76
Manager can be made a
sub/derived-class of Employee

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) {
bonus = salary * bb/100;
}
public Manager ( … ) { … }
}

77
Overriding (methods)

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) { …}
public void raise(double dd) {
salary += salary * dd/100 + bonus;
}
public Manager ( … ) { … }
}

78
Inheritance and Constructors

class First {
public First() { [Link](“ First class “); }
}
public class Second extends First {
public Second() { [Link](“Second class”); }
}
public class Third extends Second {
public Third() {[Link](“Third class”);}
}
First class
Second class
Third class

Topmost class constructor is invoked first


79
(like us …grandparent-->parent-->child->)
access modifiers

 private
 same class only
 public
 everywhere
 protected
 same class, same package, any subclass
 (default)
 same class, same package

80
super keyword

 refers to the superclass (base class)


 usage:
 with a variable or method (most common with a method)
 as a function inside a constructor of the subclass

81
super :: with a method

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) { …}
public void raise(double dd) { //overrides raise() of
Employee

[Link](dd); // call Employee’s raise()


salary += bonus;
}
public Manager ( … ) { … }
}

82
super :: as a function inside a constructor of the
subclass

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) { …}
public Manager ( String name, double salary, double bonus ) {

super(name, salary);
[Link] = bonus;
}
}

83
final keyword

 means “constant”
 applies to
 variables (makes a var. constant), or
 methods (makes a method non-overridable), or
 classes (makes a class non-subclassable means “objects
cannot be created”).

84
final keyword with a variable

class Math {

public final double pi = 3.1412;


public static double method(double x) {
double x = pi * pi;
}
}

note: variable pi is made “read-only”

85
final keyword with a method

class Employee {
protected String name;
protected double salary;
public final void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot ovveride method raise()
inside the Manager class 86
final keyword with a class

final class Employee {


protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot create class Manager as
a subclass of class Employee (all are
87

equal)
abstract classes and interfaces

 abstract classes
 may have both implemented and non-implemented
methods
 interfaces
 have only non-implemented methods
 (concrete classes)
 have all their methods implemented

88
sample abstract class

abstract class TwoDimensionalGeoFigure {


public abstract double area();
public abstract double perimeter();
public abstract void printInfo();
public void setOutlineColor(Color cc) {
// code to set the color
}
public void setInsideColor(Color cc) {
// code to set the color
}
}
89
sample interface

interface ResponceToMouseClick {
public void mouseDown();
public void mouseUp();
public void mouseDoubleClick();
}
class ConcreteMouseClick implements
ResponseToMouse Click {
// all above methods implemented
here
}
90
Exceptions (error handling)
A nice way to handle errors in Java programs

code without exceptions:


code with exceptions:
...
...
int a = 7, b = 0, result;
int a = 7, b = 0, result;
if ( b != 0) {
try {
result = a/b;
result = a/b;
}
}
else {
catch (ArithmeticException e )
[Link](“b is
{
zero”);
[Link](“b is
}
zero”);
...
}

... 91
Exceptions (cont’d)
...
int a = 7, b = 0, result;
try {
result = a/b;
/// more code .. reading from a file
}
catch (ArithmeticException e ) {
[Link](“b is zero”);
}
catch (IOException e ) {
[Link](“Can’t read”);
}
finally {
[Link](“Closing file”);
/// code to close file
} 92

...
methods throwing exceptions

public int divide (int x, int y ) throws ArithmeticException {

if (y == 0 ) {
throw new ArithmeticException();
}
else {
return a/b ;
}
} // end divide()

93
Defining your own exceptions

class MyException extends ArithmeticException {}frm

public int divide (int x, int y ) throws MyException {

if (y == 0 ) {
throw new MyException();
}
else {
return a/b ;
}
} // end divide()

94
GUI Programming in Java
(AWT and Event Handling)
AWT - Abstract Windowing
Toolkit

 Single Windowing Interface on Multiple Platforms


 Supports functions common to all window systems
 Uses Underlying Native Window system
 AWT provides
 GUI widgets
 Event Handling
 Containers for widgets
 Layout managers
 Graphic operations
AWT - Abstract Window
Toolkit

 Portable GUI - preserves native look & feel


 Standard GUI Components (buttons…)
 Containers - Panels, Frames, Dialogs
 Graphics class for custom drawing
 Layouts responsible for actual positioning of components:
 BorderLayout, GridLayout, FlowLayout, null
layoit
Adding Components via
Layouts

setLayout(new BorderLayout());
// Add text field to top
add("North",new TextField());
// Create the panel with buttons at the bottom...
Panel p = new Panel(); // FlowLayout
[Link](new Button("OK"));
[Link](new Button("Cancel"));
add("South",p);
Adding Components via
Layouts
Building Graphical User Interfaces

 import [Link].*;
 Assemble the GUI
 use GUI components,
 basic components (e.g., Button, TextField)
 containers (Frame, Panel)
 set the positioning of the components
 use Layout Managers
 Attach events

100
A sample GUI program

Import [Link].*;
class MyGui {
public static void main(String [] s ) {
Frame f = new Frame (“My Frame”);
Button b = new Button(“OK”);
TextField tf = new TextField(“George”, 20);
[Link](new FlowLayout());
[Link](b);
[Link](tf);
[Link](300, 300);
[Link](true);
}
}

101
output

102
Events

[Link]( );

Button
method to add a listener listener object
Frame

[Link]( );
103
Events

 Each GUI component (e.g., a Button) that wishes to


respond to an event type (e.g., click), must register
an event handler, called a Listener.
 The listener is an object of a "Listener" interface.
 A Listener class can be created by subclassing
(through "implements") one of Listener interfaces (all
listener inrefaces are in the [Link] package =
> must import [Link].*; )
 The registration of the listener is done by a call to a
method such as addActionListener(<Listener
Object>). Each GUI component class has one or more
such add…() methods, where applicable.

104
Listener Interfaces

INTERFACE NAME (IN [Link] )


[1] ActionListener
[2] ItemListener
[3] MouseMotionListener
[4] MouseListener
[5] KeyListener
[6] FocusListener
[7] AdjustmentListener
[8] ComponentListener
[9] WindowListener
[10] ContainerListener
[11] TextListener

105
Listener Interfaces

Each listener interface has methods that need to be implemented for


handling different kinds of events.

For example, the MouseMotionListener interface has two methods:

1) mouseDragged(MouseEvent) - Invoked when a mouse button is


pressed on a component and then dragged.
2) mouseMoved(MouseEvent) - Invoked when the mouse button has
been moved on a component (with no buttons down).

106
... the WindowListener interface has seven methods:

1) windowActivated(WindowEvent) - Invoked when a window is activated.


2) windowClosed(WindowEvent) - Invoked when a window has been closed.
3) windowClosing(WindowEvent) - Invoked when a window is in the process of being
closed.
4) windowDeactivated(WindowEvent) - Invoked when a window is de-activated.
5) windowDeiconified(WindowEvent) - Invoked when a window is de-iconified.
6) windowIconified(WindowEvent) - Invoked when a window is iconified.
7) windowOpened(WindowEvent) - Invoked when a window has been opened.

107
How to create an object of a
listener interface ?

Interfaces cannot be instantiated.

Therefore, cannot do new WindowListener();

Instead, have to subclass the interface and then create object of


the subclass

108
Implementing the ActionListener Interface
and attaching an event handler to a button

class MyApp implements ActionListener {


Button b = new Button(“OK”);
public static void main(String [] s ) {
(new MyApp()).go();
}
public void go() {
[Link]( this );
}
public void actionPerformed(ActionEvent e ) {
// what to do when the button is clicked
if( [Link]() == b )
{ [Link](“OK pressed"); }
}
}

109
Implementing 2 interfaces

class MyApp implements ActionListener, WindowListener {


Button b = new Button(“OK”);
Frame f = new Frame(“My Frame”);
public static void main(String [] s ) {(new MyApp()).go(); }
public void go() {
[Link]( this );
[Link]( this );
}
public void actionPerformed(ActionEvent e ) { … }
public void windowActivated(WindowEvent e ) { … }
public void windowClosed(WindowEvent e ) { … }
public void windowClosing(WindowEvent e ) { … }
public void windowDeactivated(WindowEvent e) { … }
public void windowDeiconified(WindowEvent e) { … }
public void windowIconified(WindowEvent e) { … }
public void windowOpened(WindowEvent e) { … }
} 110
or … use Adapters

class MyApp extends WindowAdapter {


Button b = new Button(“OK”);
Frame f = new Frame(“My Frame”);
public static void main(String [] s ) {(new MyApp()).go(); }
public void go() {
[Link]( this );
}
public void windowClosing(WindowEvent e ) { … }
}

Need only implement the method(s) that are required, instead of all
seven methods of the WindowListener interface

111
But, we can only use one Adapter at a time (no multiple
inheritance)

I.e., cannot have :

class MyApp extends WindowAdapter,


MouseAdapter, ... {
… … … ...
} 112
However … can use inner classes
instead !!!
class MyApp {
Button b = new Button(“OK”);
Frame f = new Frame(“My Frame”);
public static void main(String [] s ) {
((new MyApp()).go(); }
public void go() {
[Link]( new FrameHandler() );
[Link]( new ButtonHandler() );
}
class ButtonHandler extends MouseAdapter {
public void mousePressed (MouseEvent e ) { … }
}
class FrameHandler extends WindowAdapter {
public void windowClosing (WindowEvent e ) { … }
}
} 113
Popup Menu and Event Handling...

//[Link]: popup menu and event handling


import [Link];
import [Link].*;
import [Link].*;
public class popup extends Frame implements ActionListener, MouseListener
{
TextField text1;
PopupMenu popup;
MenuItem menuitem1, menuitem2, menuitem3;
public popup()
{
super( "Popup Menu" );
setLayout(new FlowLayout());
setBounds(10, 10, 300, 200 );
setVisible(true);
init();
}
public void init()
{
popup = new PopupMenu("Resource Usage" );
Popup Menu and Event Handling...

menuitem1 = new MenuItem("CPU");


[Link](this);
menuitem2 = new MenuItem("Disk");
[Link](this);
menuitem3 = new MenuItem("Memory");
[Link](this);
[Link](menuitem1);
[Link](menuitem2);
[Link](menuitem3);
add(popup);
text1 = new TextField(20);
[Link](20, 40, 120, 30 );
add(text1);
addMouseListener(this);
}
public void mousePressed(MouseEvent e )
{
if( [Link]() != 0 )
[Link](this, [Link](), [Link]() );
}
Popup Menu and Event Handling

public void mouseReleased( MouseEvent e )


{ [Link]("Mouse Released\n" ); }
public void mouseEntered( MouseEvent e )
{ [Link]("Mouse Entered\n" ); }
public void mouseExited( MouseEvent e )
{ [Link]("Mouse Exited\n" ); }
public void actionPerformed( ActionEvent e )
{
if( [Link]() == menuitem1 )
{ [Link]("CPU"); }
if( [Link]() == menuitem2 )
{ [Link]("Disk"); }
if( [Link]() == menuitem3 )
{ [Link]("Memory"); }
}
public static void main( String args[] )
{
popup p = new popup();
}
}
Applets and GUI
AWT & Applets
An Applet is a Java program capable of running from within a web
page (HTML document)

Steps to incorporate and run an applet:


· Have [Link]
· javac [Link]
· Have [Link]
· Create [Link]

<applet code = [Link] width = 200 height = 300 >


</applet>

· appletviewer [Link] (or open [Link] in browsers like


Netscape/IE).
118
Applet methods

Unlike Applications, Applets do not have


main().
Instead, they have : init(), start(), stop(),
paint(), update(), repaint(), destroy().

All methods need not be implemented --


there are default versions for all of them.
 AppletContext
 “Applet”derived from AWT Panel
 Hooks into Browser environment
 Can be used to link to another Web
119 page
A sample Applet

// [Link]: for processing applet methods


import [Link].*;
import [Link].*;
public class HelloApplet extends Applet
{

public void init() {

setBackground([Link]);
[Link]("init() method invoked");
}
public void start()
{
[Link]("start() method invoked");
}
public void paint( Graphics g )
{
[Link]("paint() method invoked");
[Link]( "Hi there", 24, 25 );
}
public void stop()
{
[Link]("stop() method invoked");
}
}
sample Applet

121
another sample Applet (run
in Applet Viewer)

122
sample Applet
running within Netscape

123
sample Applet code

import [Link].*; // for Applet class


import [Link].*; // for Graphics class
public class MyApplet extends Applet {
public void paint( Graphics g ) {
[Link]("Hi there", 40, 40);
[Link](40, 60, 45, 45);
[Link](100, 60, 50, 50);
[Link](170, 60, 250, 170);
} // end paint()
public void init() {
setBackground([Link]);
}
} // end class MyApplet

124
Another example

// [Link]: draws rectangle with yellow color fill

import [Link].*;

import [Link].*;

public class MyApplet extends Applet

public synchronized void paint(Graphics g)

int x,y,width,height;

Dimension dm = size();

x = [Link]/4;

y = [Link] / 4;

width = [Link] / 2;

height = [Link] / 2;

// Draw the rectangle in the center with colors!

[Link]([Link]);

[Link](x,y,width,height);

[Link]([Link]);

[Link](x + 1,y + 1,width - 2,height - 2);

}
order of Applet method
execution

As soon as the browser (or Appletviewer) accesses the page that


contains the applet:

It calls init(), first

It calls start(), second.

It calls paint(), third.

126
order of Applet method
execution (cont’d)

After the above three initial calls, invocation of the other methods
depends on user's activity while in the browser:
no activity => none of the methods is invoked
leave to a different URL => stop() is invoked (and if later come back to
this URL, then start() will be invoked).
close down the browser => destroy() is invoked
none of the above => either paint() or update() or repaint() is invoked.

127
Incorporating Images and
sound in Applets

128
sample Applet with sound

………
([Link])

129
how to do that ….

Step 1 : LOAD (image of sound file)

Step 2 : DISPLAY -or- PLAY

130
Applet that displays image
import [Link].*;
import [Link].*;
public class MyApplet1 extends Applet {
Image im;
public void init () {
// load
im = getImage(getDocumentBase(),"[Link]");
setBackground([Link]);
}
public void paint(Graphics g ) {
[Link](im, 50, 50, this); // display
}
} // end class MyApplet1

131
Applet that plays sound
import [Link].*;
import [Link].*;
public class MyAppletSound extends Applet {
AudioClip ac;
public void init () {
// load
ac = getAudioClip(getDocumentBase(), "[Link]");
}
public void start() {
[Link](); // play
}
public void stop() {
[Link](); // stop the sound upon leaving this web page
}
} // end class MyAppletSound

132
Multithreading in Java
(A built-in feature in Java)
Single and Multithreaded
Processes
threads are light-weight processes within a process

Single-threaded Process Multiplethreaded Process


Threads of
Execution

Single instruction stream Multiple instruction stream


Common
Address Space
Threads

 Java has built in thread support for Multithreading


 Synchronization
 Thread Scheduling
 Inter-Thread Communication:
currentThread start setPriority
yield run getPriority
sleep stop suspend
resume
 Java Garbage Collector is a low-priority thread
Thread states

new
wait()
start() sleep()
suspend()
blocked

runnable non-runnable
notify()
stop() slept
resume()
unblocked

dead 136
Threading Mechanisms...

 Create a class that extends the Thread class


 Create a class that implements the Runnable interface
1st method: Extending Thread
class
 1st Method: Extending the Thread class
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
 Creating thread:

MyThread thr1 = new MyThread();


 Start Execution:

[Link]();
An example

class MyThread extends Thread { // the thread


public void run() {
[Link](" this thread is running ... ");
}
} // end class MyThread

class ThreadEx2 { // a program that utilizes the


thread
public static void main(String [] args ) {
// note, the created object myThreadObject IS A Thread as
well.
MyThread t = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
[Link](); 139

} // end main()
} // end class ThreadEx2
2nd method: Threads by implementing
Runnable interface

class MyThread implements Runnable


{
.....
public void run()
{
// thread body of execution
}
}
 Creating Object:

MyThread myObject = new MyThread();


 Creating Thread Object:

Thread thr1 = new Thread( myObject );


 Start Execution:

[Link]();
An example

class MyThread implements Runnable {


public void run() {
[Link](" this thread is running ... ");
}
} // end class MyThread

class ThreadEx21 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
[Link]();
} // end main()
} // end class ThreadEx2
141
A program with two threads

class MyThread implements Runnable {


public void run() { [Link]("This is
'MyThread' ); }
}

class YourThread implements Runnable {


public void run() { [Link]("This is
'YourThread'); }
}

class ThreadEx4 {
public static void main(String [] args ) {
Thread t1 = new Thread(new MyThread());
Thread t2 = new Thread(new YourThread());
[Link](); 142

[Link]();
Monitor model (for Syncronisation)

Method 1

Method 2

Key
Block 1

Threads

Monitor (synchronised) solves race-condition problem


examples :: program with two threads and shared object

class MyThread implements Runnable {


Shared so;
public MyThread (Shared s) { so =
s;}
public void run() { so.method1(); }
} // end class MyThread

class YourThread implements Runnable


{ so
Shared so;
public YourThread (Shared s) { so =
s; }
public void run() { so.method2(); }
} // end class YourThread
144
class HerThread implements Runnable {
Shared so;
the monitor (shared object)

class Shared { // the 'monitor'

// if 'synchronized' is removed, the outcome is unpredictable


public synchronized void method1( ) {
for (int i = 0; i < 200; i++) { [Link](" [1] :: " + i )
;}
}

// if the 'synchronized' is removed, the outcome is unpredictable


public synchronized void method2( ) {
for (int i = 0; i < 200; i++) { [Link](" [2] :: " +
i); }
}

// if the 'synchronized' is removed, the outcome is unpredictable


public synchronized void method3( ) {
for (int i = 0; i < 200; i++) { [Link](" [3] :: " +
145
i);}
}
the driver

class MyMainClass {
public static void main(String [] args ) {
Shared sharedObject = new Shared ();
Thread t1 = new Thread(new
MyThread(sharedObject));
Thread t2 = new Thread(new
YourThread(sharedObject));
Thread t3 = new Thread(new
HerThread(sharedObject));

[Link]();
[Link]();
[Link]();

} // end main()

} // end class ThreadEx5 146


Threads
Threads in
in Action...
Action...
Cooperative
Cooperative threads
threads -- File
File Copy
Copy

reader()
reader()
{{ writer()
writer()
-- -- -- -- -- -- -- -- -- buff[0] {{
-- buff[0]
-- -- -- -- -- -- -- -- -- --
lock(buff[i]);
lock(buff[i]); lock(buff[i]);
buff[1] lock(buff[i]);
read(src,buff[i]);
read(src,buff[i]); buff[1] write(src,buff[i]);
write(src,buff[i]);
unlock(buff[i]);
unlock(buff[i]); unlock(buff[i]);
unlock(buff[i]);
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- }}
}}

Cooperative
Cooperative Parallel
Parallel
Synchronized
Synchronized Threads
Threads
Streams and I/O
Streams and I/O

 basic classes for file IO


 FileInputStream,for reading from a file
 FileOutputStream, for writing to a file
 Example:
Open a file "[Link]" for reading
FileInputStream fis = new FileInputStream("[Link]");

Open a file "[Link]" for writing


FileOutputStream fos = new FileOutputStream ("[Link]");

149
Display File Contents

import [Link].*;
public class FileToOut1 {
public static void main(String args[]) {
try {
FileInputStream infile = new FileInputStream("[Link]");
byte buffer[] = new byte[50];
int nBytesRead;
do {
nBytesRead = [Link](buffer);
[Link](buffer, 0, nBytesRead);
} while (nBytesRead == [Link]);
}
catch (FileNotFoundException e) {
[Link]("File not found");
}
catch (IOException e) { [Link]("Read failed"); }
} 150

}
Filters

•Once a stream (e.g., file) has been opened, we


can attach filters
•Filters make reading/writing more efficient
•Most popular filters:
• For basic types:
•DataInputStream, DataOutputStream
• For objects:
•ObjectInputStream, ObjectOutputStream

151
Writing data to a file using Filters

import [Link].*;
public class GenerateData {
public static void main(String args[]) {
try {
FileOutputStream fos = new FileOutputStream("[Link]");
DataOutputStream dos = new DataOutputStream(fos);
[Link](2);
[Link](2.7182818284590451);
[Link](3.1415926535);
[Link](); [Link]();
}
catch (FileNotFoundException e) {
[Link]("File not found");
}
catch (IOException e) {
[Link]("Read or write failed");
}
152
}
}
Reading data from a file using
filters
import [Link].*;
public class ReadData {
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("[Link]");
DataInputStream dis = new DataInputStream(fis);
int n = [Link]();
[Link](n);
for( int i = 0; i < n; i++ )
{ [Link]([Link]());
}
[Link](); [Link]();
}
catch (FileNotFoundException e) {
[Link]("File not found");
}
catch (IOException e) { [Link]("Read or write
153
failed");
}
Object serialization

Write objects to a file, instead of writing


primitive types.

Use the ObjectInputStream,


ObjectOutputStream classes, the same
way that filters are used.

154
Write an object to a file
import [Link].*;
import [Link].*;
public class WriteDate {
public WriteDate () {
Date d = new Date();
try {
FileOutputStream f = new FileOutputStream("[Link]");
ObjectOutputStream s = new ObjectOutputStream (f);
[Link] (d);
[Link] ();
}
catch (IOException e) { [Link](); }

public static void main (String args[]) {


new WriteDate ();
}
} 155
Read an object from a file

import [Link].*;
public class ReadDate {
public ReadDate () {
Date d = null;
ObjectInputStream s = null;
try { FileInputStream f = new FileInputStream ("[Link]");
s = new ObjectInputStream (f);
} catch (IOException e) { [Link](); }
try { d = (Date)[Link] (); }
catch (ClassNotFoundException e) { [Link](); }
catch (InvalidClassException e) { [Link](); }
catch (StreamCorruptedException e) { [Link](); }
catch (OptionalDataException e) { [Link](); }
catch (IOException e) { [Link](); }
[Link] ("Date serialized at: "+ d);
}
public static void main (String args[]) { new ReadDate
156
(); }
}
Network/Socket Programming in
Java
[Link]

 Used to manage:
 URL streams
 Client/server sockets
 Datagrams
Part III - Networking
ServerSocket(1234)

Output/write stream

Input/read stream

Socket(“[Link]”,
159
1234)
Server_name: “[Link]”
Server side Socket Operations

1. Open Server Socket:


String server; Socket slink;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for Client Request:
Socket client = [Link]();
3. Create I/O streams for communicating to clients
is = new DataInputStream( [Link]() );
os = new DataOutputStream( [Link]() );
4. Perform communication with client
Receiive from client: String line = [Link]();
Send to client: [Link]("Hello\n");
5. Close sockets: [Link]();

For multithreade server:


while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3) and does communication as
stated in (4). Remove thread once service is provided.
}
Client side Socket Operations

1. Get connection to server:


client = new Socket( server, port_id );
2. Create I/O streams for communicating to clients
is = new DataInputStream( [Link]() );
os = new DataOutputStream( [Link]() );
3. Perform communication with client
Receiive from client: String line = [Link]();
Send to client: [Link]("Hello\n");
4. Close sockets: [Link]();
A simple server (simplified code)

import [Link].*;
import [Link].*;
public class ASimpleServer {
public static void main(String args[]) {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=[Link](); // Wait and accept a connection
// Get a communication stream associated with the
socket
OutputStream s1out = [Link]();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
[Link](“Hi there”);
// Close the connection, but not the server socket
[Link]();
[Link](); 162
[Link]();
}
A simple client (simplified code)

import [Link].*;
import [Link].*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket("[Link]",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = [Link]();
DataInputStream dis = new DataInputStream(s1In);
String st = new String ([Link]());
[Link](st);
// When done, just close the connection and exit
[Link]();
[Link]();
[Link]();
} 163

}
Echo Server Client..

//[Link]: client interface to server


import [Link].*;
import [Link].*;
public class client
{
int port_id;
String server; Socket slink;
DataOutputStream os;
DataInputStream is;
DataInputStream kbd;
public client( String args[] )
{
server = args[0];
port_id = [Link](args[1]).intValue();
try
{
slink = new Socket( server, port_id );
os = new DataOutputStream( [Link]() );
is = new DataInputStream( [Link]() );
kbd = new DataInputStream( [Link] );
}
Echo Server Client..

catch( UnknownHostException e )

[Link]( "Don't know about host: " );

[Link](1);

catch( IOException e )

[Link]( "Could not get I/O for the connection to "+server);

[Link](1);

void communicate()

while(true)

try {

[Link]("Enter Input <end to stop>: ");

String line = [Link]();

[Link]( line+"\n" );
Echo Server Client..

if( [Link]("end") )
{ [Link](); [Link](); [Link]();
break;
}
String line2 = [Link]();
[Link]("Output: "+line2);
}
catch( IOException e )
{ [Link](e); }
}
}
public static void main( String [] args )
{
if( [Link] < 2 )
{
[Link]("Usage: java client server_name port_id" );
[Link](1);
}
client cln = new client( args );
[Link]();
}
}
Echo Server ...
// [Link]: echo server

import [Link].*;

import [Link].*;

public class server

// public final static int PORT = 4779;

public static void main( String [] args )

ServerSocket server = null;

DataOutputStream os = null;

DataInputStream is = null;

boolean shutdown = false;

if( [Link] < 1 )

[Link]( "Usage: java server port_num" );

[Link]( 1 );

int PORT = [Link](args[0]).intValue();

try {

server = new ServerSocket( PORT );

}
Echo Server ...

catch( IOException e )
{
[Link]( "Could not get I/O for the connection to: ");
}
while(!shutdown)
{
if( server != null )
{
try
{
Socket client = [Link]();
[Link]("Connected");
InetAddress cip = [Link]();
[Link]( "Client IP Addr: "+[Link]());
is = new DataInputStream( [Link]() );
os = new DataOutputStream( [Link]() );
for(;;)
{
String line = [Link]();
if( line == null )
break;
Echo Server ...
if( [Link]("end" ) )
{
shutdown = true;
break;
}
[Link]([Link]());
[Link]("\n");
[Link](line);
}
[Link](); [Link]();
}
catch( UnknownHostException e )
{
[Link]( "Server Open fails" );
}
catch( IOException e )
{
[Link]( "Could not get I/O for the connection to:"+args[0]);
}
}
}
Echo Server

[Link]( "Server Down" );


try {
[Link]();
} catch(IOException e) {}
}
}
Threads in Action...
Multithreaded Server

Server Process
Client
Process Server
Threads

Client Process

User Mode

Kernel Mode
Message Passing
Facility
Java System Architecture
& Availability
A Look Inside the Java Platform

Applets and Applications


Java Base API Java Standard Extension API
The
Java Java Base Classes Java Standard Extension Classes
Base
Platform Java Virtual Machine
(in black)
Porting Interface
Adapter Adapter
Adapter
Browser JavaOS
OS
OS OS

Hardware Hardware Hardware Hardware

Network
Java on Java on a Java on a Java on
a Browser Desktop OS Smaller OS JavaOS
Java Applications!

 Java applications are now available


 Cost of manfg zero, cost of distribution
zero, cost of marketing zero!
 Hot Java is lean - loads everything else
from the net.
 Java itself is small - 40k to 225k
 New class of small machines will emerge
 Java on cellular phones, credit cards,
washing machines, and everywhere ?
Just to Summarize

 Java as a Comprehensive Programming Solution


 Object Oriented
 Portable
 High Performance
 Geared for Distributed Environments
 Secure
 Highly suitable for Internet programming
Summary

 Java is really very well poised


 Incredible leverage from the Web
 Will impact the C++ and Smalltalk markets
 Rate of progress is astonishingly high
 Development environments
 CORBA linkages
 Components
 Fasten you seat-belts!
Thank
Thank You
You ...
...

You might also like