Java Programming and Internet Evolution
Java Programming and Internet Evolution
Presented by:
Mr. Bhushan Nemade, Anand Khandare
Shridhar Kamble and Sudhir Dhekane
Need for java ?
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
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
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
JAVA COMPILER
(translator)
JAVA INTERPRETER
(one for each different system)
Class Loader
Lightweight Binary Class Files
Multithreading
Dynamic
Good communication constructs
Secure
Java as Secure
Objective
Feature C++ C Ada Java
?
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
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
Compilation
# javac [Link]
results in [Link]
Execution
# java HelloInternet
Hello Internet
#
Simple Java Applet
}
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
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
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+
+
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
54
Unit II--Graphics Programming
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
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
64
… this is because
65
… this is because
66
Constructors
67
this keyword
68
this :: with a variable
69
this :: with a method
70
this :: as a function inside a constructor of “this” class
class MyApp {
int a;
72
static keyword
73
static keyword (with
variables)
class PurchaseOrder {
private static int POCount; // var. ‘a’ is shared by all objects of this class
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
77
Overriding (methods)
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
private
same class only
public
everywhere
protected
same class, same package, any subclass
(default)
same class, same package
80
super keyword
81
super :: with a method
82
super :: as a function inside a constructor of the
subclass
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 {
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
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
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
... 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
if (y == 0 ) {
throw new ArithmeticException();
}
else {
return a/b ;
}
} // end divide()
93
Defining your own exceptions
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
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
104
Listener Interfaces
105
Listener Interfaces
106
... the WindowListener interface has seven methods:
107
How to create an object of a
listener interface ?
108
Implementing the ActionListener Interface
and attaching an event handler to a button
109
Implementing 2 interfaces
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)
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
124
Another example
import [Link].*;
import [Link].*;
int x,y,width,height;
Dimension dm = size();
x = [Link]/4;
y = [Link] / 4;
width = [Link] / 2;
height = [Link] / 2;
[Link]([Link]);
[Link](x,y,width,height);
[Link]([Link]);
}
order of Applet method
execution
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 ….
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
new
wait()
start() sleep()
suspend()
blocked
runnable non-runnable
notify()
stop() slept
resume()
unblocked
dead 136
Threading Mechanisms...
[Link]();
An example
} // end main()
} // end class ThreadEx2
2nd method: Threads by implementing
Runnable interface
[Link]();
An example
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 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
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()
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
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
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
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](); }
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
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..
catch( UnknownHostException e )
[Link](1);
catch( IOException e )
[Link](1);
void communicate()
while(true)
try {
[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].*;
DataOutputStream os = null;
DataInputStream is = null;
[Link]( 1 );
try {
}
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
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
Network
Java on Java on a Java on a Java on
a Browser Desktop OS Smaller OS JavaOS
Java Applications!