SlideShare a Scribd company logo
1 of 205
Internet and Java Foundations, Programming and Practice  Rajkumar Buyya School of Computer Science and Software Engineering Monash University Melbourne, Australia Email: rajkumar@dgs.monash.edu.au URL: http://www.dgs.monash.edu.au/~rajkumar
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What is the Internet ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Internet Technology Evolution ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Internet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Internet Evolution File & mail TCP/IP Webpages Netscape On line connects to internet Secure payments Multi media Authoring Java VRML HTML Internet everywhere Internet appliances Price based services Live communities ? ? ? ? ? ? ? 10% of Market 20% of Market Total Market
Early Internet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
World Wide Web ,[object Object],[object Object],[object Object],[object Object],[object Object]
HTML ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Internet Tools ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How does the Web work ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How does the Web Work HTTP Send the “INFORMATION ABOUT  C-DAC ACTS” The  information about  C-DAC  ACTS The client sends an HTTP message to a computer running a Web Server program and asks for a document The web server sends the hypermedia HTML documents to the client. You end up seeing the document on your screen
HTML document ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
URLs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
CGI (Common Gateway Interface) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Authoring  tools and Filters ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Preconfigured v/s Integrated Internet Products ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Future Directions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Interesting URLs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
API Bottleneck Network LAN LAN PC SUN MAC Server
The OS - Platform lock Application Application Application OS Applications tied to OS OS tied to Platform Application Application
The Web Application Application Application Application BROWSER OS OS OS OS * Seeded by HTML from CERN * Revolutionised by MOSAIC * Standardised, universal interface to data * Graphical * Broadcast capability - publish once, reach millions Application
Making life easier! ,[object Object],[object Object],[object Object],[object Object]
Java and Java Computing
Java - An Introduction ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java From 10,000 Ft. ,[object Object],[object Object],[object Object]
According to the World, Java Is... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
According to Sun, Java is... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Buzzword compliant!
On Closer Inspection, Java is... ,[object Object],[object Object],[object Object],[object Object]
As a whole, Java is a Comprehensive Programming Solution ,[object Object],[object Object],[object Object],[object Object],[object Object]
Java as Object Oriented ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java as Portable ,[object Object],[object Object],[object Object],[object Object],[object Object]
Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Windows 95 Macintosh Solaris Windows NT (translator) (same for all platforms) (one for each different system)
Java Write Once, Run Anywhere
Architecture Neutral & Portable ,[object Object],[object Object],[object Object],[object Object],[object Object]
Java as High Performance ,[object Object],[object Object],[object Object],[object Object],[object Object]
Java in the World of Distributed Computing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java as Secure ,[object Object],[object Object],[object Object],[object Object]
Object Oriented Languages  -a Comparison Feature C++ Objective 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++ ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],?
Basic Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
Two Types of JavaApplications ,[object Object],[object Object],[object Object],[object Object],[object Object]
Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine Runtime Environment Compile-time Environment Java Environment/ Life Cycle of Java Code Java Interpreter Just in Time Compiler
Java Development Kit ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hello Internet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Program Processing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Simple Java Applet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Calling an Applet ,[object Object],[object Object],[object Object],[object Object],[object Object]
Execution of Applets Hello Hello Java <app= “ Hello”> 4 APPLET Development “hello.java” AT  CDAC-India The Internet hello.class  AT C-DAC’S WEB SERVER 2 3 1 5 Create Applet tag in HTML document Accessing  from CRAY Corp. (USA) The browser creates a new window and  a  new thread and  then runs the code
Web Perspective ,[object Object],[object Object],[object Object]
Classical Web Perspective
Java Web Perspective
Significance of downloading Applets ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Power of  Java and the Web ,[object Object],[object Object],[object Object],[object Object],[object Object]
Lifecycle of Java Code
Bytecode Verifier ,[object Object],[object Object],[object Object],[object Object],[object Object]
Class Loader ,[object Object],[object Object],[object Object]
Security Manager ,[object Object],[object Object],[object Object],[object Object]
General Language Features ,[object Object],[object Object],[object Object],[object Object],[object Object]
Removed From C++ ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Added or Improved over C++ ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Rich Object Environment ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Main Packages ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java Fundamentals Constructs Graphics Multithreading Streams and Networking Networking
Unit I--Java Constructs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Unit II--Graphics Programming ,[object Object],[object Object],[object Object],[object Object]
Unit III--Advanced Features ,[object Object],[object Object],[object Object],[object Object]
Unit I -- What is Java ?    ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Types  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Classes and objects ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java programs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The first Java Application ,[object Object],[object Object],[object Object],[object Object],[object Object]
Declaring and creating objects ,[object Object],[object Object],[object Object],[object Object],India
Arrays (are objects in Java) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Arrays have  length ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
… this is because ,[object Object],[object Object]
… this is because
Constructors ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
this  keyword ,[object Object],[object Object],[object Object],[object Object],[object Object]
this  :: with a variable ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
this  :: with a method ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
this  ::  as a function inside a constructor of “this” class   ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Constructor is also  overloaded  (Java allows overloading of all methods, including constructors)
this  ::  as “this” object, when passed as parameter  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
static  keyword ,[object Object],[object Object],[object Object],[object Object],[object Object]
static  keyword (with variables) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 =  Math.sqrt(7.11); } }
Inheritance (subclassing) class Employee {  protected  String name;  protected  double salary; public void raise(double dd) {  salary += salary * dd/100; } public Employee ( … ) { … }  }
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 ( … ) { … }  }
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 ( … ) { … }  }
class First {   public First() { System.out.println(“ First class “); } } public class Second extends First {   public Second() { System.out.println(“Second class”); } } public class Third extends Second {   public Third() {System.out.println(“Third class”);} } Inheritance and Constructors First class  Second class Third class Topmost class constructor is invoked first  (like us …grandparent-->parent-->child->)
access modifiers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
super  keyword ,[object Object],[object Object],[object Object],[object Object]
super  :: with a method ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
super  ::  as a function inside a constructor of the subclass ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
final  keyword ,[object Object],[object Object],[object Object],[object Object],[object Object]
final   keyword   with  a variable ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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
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 equal)
abstract classes and interfaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 } }
sample interface interface  ResponceToMouseClick {  public void mouseDown();  public void mouseUp();  public void mouseDoubleClick(); }   class ConcreteMouseClick  implements   ResponseToMouse Click {  // all above methods implemented here }
Exceptions (error handling) code without exceptions : ... int a = 7, b = 0, result; if ( b != 0) {  result = a/b; } else {  System.out.println(“b is zero”); } ... code with exceptions : ... int a = 7, b = 0, result; try  {  result = a/b; } catch  (ArithmeticException e )  {  System.out.println(“b is zero”); } ... A nice way to handle errors in Java programs
Exceptions (cont’d) ... int a = 7, b = 0, result; try  {  result = a/b; /// more code .. reading from a file } catch  (ArithmeticException e )  {  System.out.println(“b is zero”); } catch  (IOException e ) {  System.out.println(“Can’t read”); } finally  {  Sysytem.out.println(“Closing file”); /// code to close file } ...
methods throwing exceptions public int divide (int x, int y )  throws  ArithmeticException {   if (y == 0 ) {  throw  new ArithmeticException();  } else {  return a/b ;  } } // end divide()
Defining your own exceptions public int divide (int x, int y ) throws MyException {  if (y == 0 ) {  throw new MyException();  } else {  return a/b ;  } } // end divide() class  MyException  extends ArithmeticException {}frm
GUI Programming in Java (AWT and Event Handling)
AWT - Abstract Windowing  Toolkit ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
AWT - Abstract Window Toolkit ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Adding Components via Layouts ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Adding Components via Layouts
Building Graphical User Interfaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
A sample GUI program Import java.awt.*; 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); f.setLayout(new FlowLayout()); f.add(b); f.add(tf); f.setSize(300, 300); f.setVisible(true); } }
output
Events b.addActionListener (  ); method to add a listener listener object Button f.addWindowListener (  ); Frame
Events ,[object Object],[object Object],[object Object],[object Object]
Listener Interfaces INTERFACE NAME (IN JAVA.AWT.EVENT )  [1]  ActionListener [2]  ItemListener [3]  MouseMotionListener [4]  MouseListener [5]  KeyListener [6]  FocusListener [7]  AdjustmentListener [8]  ComponentListener [9]  WindowListener [10]  ContainerListener [11]  TextListener
Listener Interfaces Each listener interface has methods that need to be implemented for handling different kinds of events. 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). For example, the  MouseMotionListener  interface has two 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. ... the  WindowListener  interface has seven methods:
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
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() {  b.addActionListener(  this  ); } public void actionPerformed(ActionEvent e ) {    // what to do when the button is clicked   if( e.getSource() == b )   {  System.out.println(“OK pressed&quot;); } } }
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() {  b.addActionListener(  this  ); f.addWindowListener( 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) { … } } Implementing 2 interfaces
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() {  f.addWindowListener( this ); } public void  windowClosing(WindowEvent e )  { … } } Need only implement the method(s) that are required, instead of all seven methods of the WindowListener interface
But, we can only use one Adapter at a time (no multiple inheritance)  I.e.,  cannot  have :  class MyApp extends  WindowAdapter, MouseAdapter, ... {  … … … ... }
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() {    f.addWindowListener( new FrameHandler() );   b.addMouseListener( new ButtonHandler() ); } class  ButtonHandler extends MouseAdapter {    public void mousePressed (MouseEvent e )  { … } } class  FrameHandler extends WindowAdapter {    public void windowClosing (WindowEvent e )  { … } } }
Popup Menu and Event Handling... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Popup Menu and Event Handling... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Popup Menu and Event Handling ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 MyApplet.java · javac MyApplet.java · Have MyApplet.class · Create  MyApplet.html   <applet code = MyApplet.class width = 200 height = 300 >  </applet>   · appletviewer MyApplet.html  (or open MyApplet.html in browsers like Netscape/IE).
Applet methods ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
A sample Applet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
sample Applet
another sample Applet (run in Applet  Viewer)
sample Applet  running within Netscape
sample Applet code import java.applet .*; // for Applet class import java.awt .*;  // for Graphics class public  class MyApplet  extends Applet  { public void  paint ( Graphics g ) { g.drawString(&quot;Hi there&quot;, 40, 40); g.drawOval(40, 60, 45, 45); g.drawRect(100, 60, 50, 50); g.drawLine(170, 60, 250, 170); } // end paint() public void  init () { setBackground(Color.yellow); } } // end class MyApplet
Another example ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
order of Applet method execution ,[object Object],[object Object],[object Object],[object Object]
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.
Incorporating Images and sound in Applets
sample Applet with sound … … …  (MyAppletSound.java)
how to do that …. Step 1 : LOAD (image of sound file) Step 2 : DISPLAY -or- PLAY
Applet that displays image import java.applet.*; import java.awt.*; public class MyApplet1  extends Applet { Image im;  public void init () { //  load im = getImage(getDocumentBase(),&quot;BOTTOMDOLLAR.JPG&quot;); setBackground(Color.yellow); } public void paint(Graphics g ) { g.drawImage(im, 50, 50, this); //  display }  } // end class MyApplet1
Applet that plays sound import java.applet.*; import java.awt.*; public class MyAppletSound  extends Applet { AudioClip ac;  public void init () { //  load ac = getAudioClip(getDocumentBase(), &quot;chirp1.au&quot;); } public void start() { ac.loop(); //  play } public void stop() { ac.stop();  // stop the sound upon leaving this web page } } // end class MyAppletSound
Multithreading in Java (A built-in feature in Java)
Single and Multithreaded Processes Single-threaded Process Single instruction stream Multiple instruction stream Multiplethreaded Process Threads of Execution Common Address Space threads are light-weight processes within a process
Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thread states new runnable non-runnable dead wait() sleep() suspend() blocked notify() slept resume() unblocked start() stop()
Threading Mechanisms... ,[object Object],[object Object]
1st method: Extending Thread class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
An example class MyThread extends Thread {  // the thread public void  run () { System.out.println(&quot; this thread is running ... &quot;); } } // 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. t.start(); } // end main() }  // end class ThreadEx2
2nd method: Threads by implementing Runnable interface ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
An example class MyThread implements Runnable  { public void run() { System.out.println(&quot; this thread is running ... &quot;); } } // 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(). t.start(); } // end main() }  // end class ThreadEx2
A  program with two threads   class MyThread implements Runnable  { public void run() { System.out.println(&quot;This is 'MyThread' ); } } class YourThread implements Runnable  { public void run() { System.out.println(&quot;This is 'YourThread');  } } class ThreadEx4 { public static void main(String [] args  ) { Thread t1 = new Thread(new MyThread()); Thread t2 = new Thread(new YourThread()); t1.start();   t2.start(); }  }  // end class ThreadEx4
Monitor model (for Syncronisation) Method 1 Method 2 Block 1 Key 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  { Shared  so; public YourThread (Shared s) { so = s; } public void run() {  so.method2 (); }  } // end class YourThread class HerThread implements Runnable  { Shared  so; public HerThread (Shared s) { so = s; } public void run() { so.method3 (); } } // end class HerThread 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++) { System.out.print(&quot;  [1] :: &quot; + i ) ; } }  // if the 'synchronized' is removed, the outcome is unpredictable public  synchronized void method2( ) { for (int i = 0; i < 200; i++) { System.out.print(&quot;  [2] :: &quot; + i ) ;  } }   // if the 'synchronized' is removed, the outcome is unpredictable public  synchronized void method3( ) { for (int i = 0; i < 200; i++) { System.out.print(&quot;  [3] :: &quot; + i ) ; } } } // end class Shared
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 )); t1.start(); t2.start(); t3.start(); } // end main() }  // end class ThreadEx5
Threads in Action... Cooperative threads - File Copy ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],buff[0] buff[1] Cooperative Parallel Synchronized Threads
Streams and I/O
Streams and I/O ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Display File Contents import java.io.*; public class FileToOut1 { public static void main(String args[]) { try  { FileInputStream infile = new FileInputStream(&quot;testfile.txt&quot;); byte buffer[] = new byte[50]; int nBytesRead; do  { nBytesRead = infile.read(buffer);   System.out.write(buffer, 0, nBytesRead); } while (nBytesRead == buffer.length); } catch (FileNotFoundException e)  { System.err.println(&quot;File not found&quot;); }  catch (IOException e) { System.err.println(&quot;Read failed&quot;); } } }
Filters ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Writing data to a file using Filters import java.io.*; public class GenerateData { public static void main(String args[]) { try  { FileOutputStream fos = new FileOutputStream(&quot;stuff.dat&quot;); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(2); dos.writeDouble(2.7182818284590451); dos.writeDouble(3.1415926535); dos.close(); fos.close(); } catch (FileNotFoundException e) {  System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
Reading data from a file using filters import java.io.*; public class ReadData { public static void main(String args[]) { try { FileInputStream fis = new FileInputStream(&quot;stuff.dat&quot;); DataInputStream dis = new DataInputStream(fis); int n = dis.readInt(); System.out.println(n); for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble()); } dis.close(); fis.close(); } catch (FileNotFoundException e) {  System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
Object serialization Write objects to a file, instead of writing primitive types. Use the  ObjectInputStream ,  ObjectOutputStream  classes, the same way that filters are used.
Write an object to a file import java.io.*; import java.util.*; public class WriteDate { public WriteDate () { Date d = new Date(); try { FileOutputStream f = new FileOutputStream(&quot;date.ser&quot;); ObjectOutputStream s = new ObjectOutputStream (f); s.writeObject (d); s.close (); }  catch (IOException e) { e.printStackTrace(); } public static void main (String args[]) { new WriteDate (); } }
Read an object from a file import java.util.*; public class ReadDate { public ReadDate () { Date d = null; ObjectInputStream s = null; try {  FileInputStream f = new FileInputStream (&quot;date.ser&quot;); s = new ObjectInputStream (f); } catch (IOException e) { e.printStackTrace(); } try { d = (Date) s.readObject  (); } catch (ClassNotFoundException e) { e.printStackTrace(); }  catch (InvalidClassException e) { e.printStackTrace(); }  catch (StreamCorruptedException e) { e.printStackTrace(); }  catch (OptionalDataException e) { e.printStackTrace(); }  catch (IOException e) { e.printStackTrace(); } System.out.println (&quot;Date serialized at: &quot;+ d); } public static void main (String args[]) { new ReadDate ();  } }
Network/Socket Programming  in Java
java.net ,[object Object],[object Object],[object Object],[object Object]
Part III - Networking ServerSocket(1234) Socket(“130.63.122.1”, 1234) Output/write stream Input/read stream Server_name: “cdacb.ernet.in”
Server side Socket Operations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Client side Socket Operations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
A simple server (simplified code)  import java.net.*;  import java.io.*; public class ASimpleServer { public static void main(String args[]) { // Register service on port 1234 ServerSocket s = new ServerSocket(1234);  Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string!  dos.writeUTF(“Hi there”); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } }
A simple client (simplified code)  import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket(&quot; 130.63.122.1 &quot;,1234);  // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); } }
Echo Server Client.. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Echo Server Client.. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Echo Server Client.. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Echo Server ... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Echo Server ...
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Echo Server ...
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Echo Server
Server Threads Message Passing Facility Server Process Client Process Client Process User Mode Kernel Mode Threads in Action...   Multithreaded Server
Java System Architecture & Availability
A Look Inside the Java Platform Java Virtual Machine Porting Interface Applets and Applications Java Base API Java Base Classes Java Standard Extension API Java Standard Extension Classes The  Java Base Platform (in black) Network Java on a Browser Java on a Desktop OS Java on a Smaller OS Java on  JavaOS Adapter OS Hardware Adapter OS Hardware JavaOS Hardware Adapter Browser OS Hardware
Java Applications! ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Universal Interface Internet Web Servers with JAVA applications Clients running any OS on any platform
Java on my platform ?  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java Development Tools  (Present and Planned)
Sun’s Java WorkShop ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Symantec Cafe 1.0 (Released) ,[object Object],[object Object],[object Object],[object Object],[object Object]
Microsoft Jakarta (Planned) ,[object Object],[object Object],[object Object]
Borland JBuilder ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Challenges & Possible Directions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Comments ,[object Object],[object Object],[object Object]
JDBC ,[object Object],[object Object]
Javascript and Java (Preview) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java for HPC! ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to Convert Programs to AWT 1.1... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to Convert Programs to AWT 1.1... ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to Convert Programs to AWT 1.1 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Just to Summarize ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thank You  ... ?

More Related Content

What's hot

Web programming by kiran and team
Web programming by kiran and teamWeb programming by kiran and team
Web programming by kiran and teamHemanth Kumar N
 
IJCER (www.ijceronline.com) International Journal of computational Engineerin...
IJCER (www.ijceronline.com) International Journal of computational Engineerin...IJCER (www.ijceronline.com) International Journal of computational Engineerin...
IJCER (www.ijceronline.com) International Journal of computational Engineerin...ijceronline
 
An introduction to mq light and bluemix
An introduction to mq light and bluemixAn introduction to mq light and bluemix
An introduction to mq light and bluemixmatthew1001
 
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183MQ Light for Bluemix - IBM Interconnect 2015 session AME4183
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183Robert Nicholson
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 

What's hot (7)

Software requirement
Software requirementSoftware requirement
Software requirement
 
02 intro
02   intro02   intro
02 intro
 
Web programming by kiran and team
Web programming by kiran and teamWeb programming by kiran and team
Web programming by kiran and team
 
IJCER (www.ijceronline.com) International Journal of computational Engineerin...
IJCER (www.ijceronline.com) International Journal of computational Engineerin...IJCER (www.ijceronline.com) International Journal of computational Engineerin...
IJCER (www.ijceronline.com) International Journal of computational Engineerin...
 
An introduction to mq light and bluemix
An introduction to mq light and bluemixAn introduction to mq light and bluemix
An introduction to mq light and bluemix
 
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183MQ Light for Bluemix - IBM Interconnect 2015 session AME4183
MQ Light for Bluemix - IBM Interconnect 2015 session AME4183
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 

Viewers also liked

La evolucion del pensamiento humano
La evolucion del pensamiento humanoLa evolucion del pensamiento humano
La evolucion del pensamiento humanoEuler Ruiz
 
Sight words self playing
Sight words self playingSight words self playing
Sight words self playingkmarshall
 
Aplicaciones Móviles- Crmmovil
Aplicaciones Móviles- CrmmovilAplicaciones Móviles- Crmmovil
Aplicaciones Móviles- Crmmovilcampuspartyquito
 
Cábula do Acordo Ortográfico
Cábula do Acordo OrtográficoCábula do Acordo Ortográfico
Cábula do Acordo OrtográficoMarisa Paço
 
Ttcn ingenierie protocoles-poly4
Ttcn ingenierie protocoles-poly4Ttcn ingenierie protocoles-poly4
Ttcn ingenierie protocoles-poly4hemanth kumar sonti
 
Trabajo toma_de_decisiones
Trabajo  toma_de_decisionesTrabajo  toma_de_decisiones
Trabajo toma_de_decisionesJessicaAlta
 

Viewers also liked (7)

La evolucion del pensamiento humano
La evolucion del pensamiento humanoLa evolucion del pensamiento humano
La evolucion del pensamiento humano
 
Sight words self playing
Sight words self playingSight words self playing
Sight words self playing
 
Ambiente Word
Ambiente WordAmbiente Word
Ambiente Word
 
Aplicaciones Móviles- Crmmovil
Aplicaciones Móviles- CrmmovilAplicaciones Móviles- Crmmovil
Aplicaciones Móviles- Crmmovil
 
Cábula do Acordo Ortográfico
Cábula do Acordo OrtográficoCábula do Acordo Ortográfico
Cábula do Acordo Ortográfico
 
Ttcn ingenierie protocoles-poly4
Ttcn ingenierie protocoles-poly4Ttcn ingenierie protocoles-poly4
Ttcn ingenierie protocoles-poly4
 
Trabajo toma_de_decisiones
Trabajo  toma_de_decisionesTrabajo  toma_de_decisiones
Trabajo toma_de_decisiones
 

Similar to Java

Similar to Java (20)

Java Test
Java TestJava Test
Java Test
 
Java
JavaJava
Java
 
Java and internet fundamentals.
Java and internet fundamentals.Java and internet fundamentals.
Java and internet fundamentals.
 
EMBEDDED WEB TECHNOLOGY
EMBEDDED WEB TECHNOLOGYEMBEDDED WEB TECHNOLOGY
EMBEDDED WEB TECHNOLOGY
 
Javascript - Getting started | DevCom ISITCom
Javascript - Getting started | DevCom ISITComJavascript - Getting started | DevCom ISITCom
Javascript - Getting started | DevCom ISITCom
 
Lecture 1- Introduction to Computers and the Internet.pptx
Lecture 1- Introduction to Computers and the Internet.pptxLecture 1- Introduction to Computers and the Internet.pptx
Lecture 1- Introduction to Computers and the Internet.pptx
 
abdelwahab alsammak_Chapter 1-Internet concepts.ppt
abdelwahab alsammak_Chapter 1-Internet concepts.pptabdelwahab alsammak_Chapter 1-Internet concepts.ppt
abdelwahab alsammak_Chapter 1-Internet concepts.ppt
 
fundamental of information technology (2)
fundamental of information technology  (2)fundamental of information technology  (2)
fundamental of information technology (2)
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Testing print-fr url
Testing print-fr urlTesting print-fr url
Testing print-fr url
 
java
javajava
java
 
1 web overview
1 web overview1 web overview
1 web overview
 
introduction to web application development
introduction to web application developmentintroduction to web application development
introduction to web application development
 
How does the web or internet work
How does the web or internet workHow does the web or internet work
How does the web or internet work
 
Web Technology – Web Server Setup : Chris Uriarte
Web Technology – Web Server Setup : Chris UriarteWeb Technology – Web Server Setup : Chris Uriarte
Web Technology – Web Server Setup : Chris Uriarte
 
Web engineering 2(lect 0)
Web engineering 2(lect 0)Web engineering 2(lect 0)
Web engineering 2(lect 0)
 
ICS 2203-WEB APPLICATION DEVELOPMENT-EDUC Y2S1_MATHCOMP.docx
ICS 2203-WEB APPLICATION DEVELOPMENT-EDUC Y2S1_MATHCOMP.docxICS 2203-WEB APPLICATION DEVELOPMENT-EDUC Y2S1_MATHCOMP.docx
ICS 2203-WEB APPLICATION DEVELOPMENT-EDUC Y2S1_MATHCOMP.docx
 
Webtechnologies
Webtechnologies Webtechnologies
Webtechnologies
 
Web Tech
Web TechWeb Tech
Web Tech
 

More from Vivastream

Exchange Solutions Datasheet_Ecommerce
Exchange Solutions Datasheet_EcommerceExchange Solutions Datasheet_Ecommerce
Exchange Solutions Datasheet_EcommerceVivastream
 
Exchange Solutions Datasheet_Customer Engagement Roadmap
Exchange Solutions Datasheet_Customer Engagement RoadmapExchange Solutions Datasheet_Customer Engagement Roadmap
Exchange Solutions Datasheet_Customer Engagement RoadmapVivastream
 
Vivastream Poster
Vivastream PosterVivastream Poster
Vivastream PosterVivastream
 
Vivastream Poster
Vivastream PosterVivastream Poster
Vivastream PosterVivastream
 
Breaking Up is Hard to Do: Small Businesses’ Love Affair with Checks
Breaking Up is Hard to Do: Small Businesses’ Love Affair with ChecksBreaking Up is Hard to Do: Small Businesses’ Love Affair with Checks
Breaking Up is Hard to Do: Small Businesses’ Love Affair with ChecksVivastream
 
EY Smart Commerce Report
EY Smart Commerce ReportEY Smart Commerce Report
EY Smart Commerce ReportVivastream
 
EY Global Consumer Banking Survey 2014
EY Global Consumer Banking Survey 2014EY Global Consumer Banking Survey 2014
EY Global Consumer Banking Survey 2014Vivastream
 
EY Global Consumer Banking Survey
EY Global Consumer Banking SurveyEY Global Consumer Banking Survey
EY Global Consumer Banking SurveyVivastream
 
Automation for RDC and Mobile
Automation for RDC and MobileAutomation for RDC and Mobile
Automation for RDC and MobileVivastream
 
Healthcare Payments Automation Center
Healthcare Payments Automation CenterHealthcare Payments Automation Center
Healthcare Payments Automation CenterVivastream
 
Next Generation Recognition Solutions
Next Generation Recognition SolutionsNext Generation Recognition Solutions
Next Generation Recognition SolutionsVivastream
 
Automation Services
Automation ServicesAutomation Services
Automation ServicesVivastream
 
Company Overview
Company OverviewCompany Overview
Company OverviewVivastream
 

More from Vivastream (20)

Exchange Solutions Datasheet_Ecommerce
Exchange Solutions Datasheet_EcommerceExchange Solutions Datasheet_Ecommerce
Exchange Solutions Datasheet_Ecommerce
 
Exchange Solutions Datasheet_Customer Engagement Roadmap
Exchange Solutions Datasheet_Customer Engagement RoadmapExchange Solutions Datasheet_Customer Engagement Roadmap
Exchange Solutions Datasheet_Customer Engagement Roadmap
 
Test
TestTest
Test
 
Tcap
TcapTcap
Tcap
 
SQA
SQASQA
SQA
 
Jeeva jessf
Jeeva jessfJeeva jessf
Jeeva jessf
 
Vivastream Poster
Vivastream PosterVivastream Poster
Vivastream Poster
 
Vivastream Poster
Vivastream PosterVivastream Poster
Vivastream Poster
 
APEX
APEXAPEX
APEX
 
Breaking Up is Hard to Do: Small Businesses’ Love Affair with Checks
Breaking Up is Hard to Do: Small Businesses’ Love Affair with ChecksBreaking Up is Hard to Do: Small Businesses’ Love Affair with Checks
Breaking Up is Hard to Do: Small Businesses’ Love Affair with Checks
 
EY Smart Commerce Report
EY Smart Commerce ReportEY Smart Commerce Report
EY Smart Commerce Report
 
EY Global Consumer Banking Survey 2014
EY Global Consumer Banking Survey 2014EY Global Consumer Banking Survey 2014
EY Global Consumer Banking Survey 2014
 
EY Global Consumer Banking Survey
EY Global Consumer Banking SurveyEY Global Consumer Banking Survey
EY Global Consumer Banking Survey
 
Serano
SeranoSerano
Serano
 
Accura XV
Accura XVAccura XV
Accura XV
 
Automation for RDC and Mobile
Automation for RDC and MobileAutomation for RDC and Mobile
Automation for RDC and Mobile
 
Healthcare Payments Automation Center
Healthcare Payments Automation CenterHealthcare Payments Automation Center
Healthcare Payments Automation Center
 
Next Generation Recognition Solutions
Next Generation Recognition SolutionsNext Generation Recognition Solutions
Next Generation Recognition Solutions
 
Automation Services
Automation ServicesAutomation Services
Automation Services
 
Company Overview
Company OverviewCompany Overview
Company Overview
 

Java

  • 1. Internet and Java Foundations, Programming and Practice Rajkumar Buyya School of Computer Science and Software Engineering Monash University Melbourne, Australia Email: rajkumar@dgs.monash.edu.au URL: http://www.dgs.monash.edu.au/~rajkumar
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. Internet Evolution File & mail TCP/IP Webpages Netscape On line connects to internet Secure payments Multi media Authoring Java VRML HTML Internet everywhere Internet appliances Price based services Live communities ? ? ? ? ? ? ? 10% of Market 20% of Market Total Market
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. How does the Web Work HTTP Send the “INFORMATION ABOUT C-DAC ACTS” The information about C-DAC ACTS The client sends an HTTP message to a computer running a Web Server program and asks for a document The web server sends the hypermedia HTML documents to the client. You end up seeing the document on your screen
  • 13.
  • 14.  
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21. API Bottleneck Network LAN LAN PC SUN MAC Server
  • 22. The OS - Platform lock Application Application Application OS Applications tied to OS OS tied to Platform Application Application
  • 23. The Web Application Application Application Application BROWSER OS OS OS OS * Seeded by HTML from CERN * Revolutionised by MOSAIC * Standardised, universal interface to data * Graphical * Broadcast capability - publish once, reach millions Application
  • 24.
  • 25. Java and Java Computing
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34. Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Windows 95 Macintosh Solaris Windows NT (translator) (same for all platforms) (one for each different system)
  • 35. Java Write Once, Run Anywhere
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. Object Oriented Languages -a Comparison Feature C++ Objective 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
  • 41.
  • 42.
  • 43.
  • 44.
  • 45. Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine Runtime Environment Compile-time Environment Java Environment/ Life Cycle of Java Code Java Interpreter Just in Time Compiler
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51. Execution of Applets Hello Hello Java <app= “ Hello”> 4 APPLET Development “hello.java” AT CDAC-India The Internet hello.class AT C-DAC’S WEB SERVER 2 3 1 5 Create Applet tag in HTML document Accessing from CRAY Corp. (USA) The browser creates a new window and a new thread and then runs the code
  • 52.
  • 55.
  • 56.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66. Java Fundamentals Constructs Graphics Multithreading Streams and Networking Networking
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79. … this is because
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88. 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 = Math.sqrt(7.11); } }
  • 89. Inheritance (subclassing) class Employee { protected String name; protected double salary; public void raise(double dd) { salary += salary * dd/100; } public Employee ( … ) { … } }
  • 90. 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 ( … ) { … } }
  • 91. 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 ( … ) { … } }
  • 92. class First { public First() { System.out.println(“ First class “); } } public class Second extends First { public Second() { System.out.println(“Second class”); } } public class Third extends Second { public Third() {System.out.println(“Third class”);} } Inheritance and Constructors First class Second class Third class Topmost class constructor is invoked first (like us …grandparent-->parent-->child->)
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99. 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
  • 100. 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 equal)
  • 101.
  • 102. 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 } }
  • 103. sample interface interface ResponceToMouseClick { public void mouseDown(); public void mouseUp(); public void mouseDoubleClick(); } class ConcreteMouseClick implements ResponseToMouse Click { // all above methods implemented here }
  • 104. Exceptions (error handling) code without exceptions : ... int a = 7, b = 0, result; if ( b != 0) { result = a/b; } else { System.out.println(“b is zero”); } ... code with exceptions : ... int a = 7, b = 0, result; try { result = a/b; } catch (ArithmeticException e ) { System.out.println(“b is zero”); } ... A nice way to handle errors in Java programs
  • 105. Exceptions (cont’d) ... int a = 7, b = 0, result; try { result = a/b; /// more code .. reading from a file } catch (ArithmeticException e ) { System.out.println(“b is zero”); } catch (IOException e ) { System.out.println(“Can’t read”); } finally { Sysytem.out.println(“Closing file”); /// code to close file } ...
  • 106. methods throwing exceptions public int divide (int x, int y ) throws ArithmeticException { if (y == 0 ) { throw new ArithmeticException(); } else { return a/b ; } } // end divide()
  • 107. Defining your own exceptions public int divide (int x, int y ) throws MyException { if (y == 0 ) { throw new MyException(); } else { return a/b ; } } // end divide() class MyException extends ArithmeticException {}frm
  • 108. GUI Programming in Java (AWT and Event Handling)
  • 109.
  • 110.
  • 111.
  • 113.
  • 114. A sample GUI program Import java.awt.*; 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); f.setLayout(new FlowLayout()); f.add(b); f.add(tf); f.setSize(300, 300); f.setVisible(true); } }
  • 115. output
  • 116. Events b.addActionListener ( ); method to add a listener listener object Button f.addWindowListener ( ); Frame
  • 117.
  • 118. Listener Interfaces INTERFACE NAME (IN JAVA.AWT.EVENT ) [1] ActionListener [2] ItemListener [3] MouseMotionListener [4] MouseListener [5] KeyListener [6] FocusListener [7] AdjustmentListener [8] ComponentListener [9] WindowListener [10] ContainerListener [11] TextListener
  • 119. Listener Interfaces Each listener interface has methods that need to be implemented for handling different kinds of events. 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). For example, the MouseMotionListener interface has two methods:
  • 120. 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. ... the WindowListener interface has seven methods:
  • 121. 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
  • 122. 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() { b.addActionListener( this ); } public void actionPerformed(ActionEvent e ) { // what to do when the button is clicked if( e.getSource() == b ) { System.out.println(“OK pressed&quot;); } } }
  • 123. 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() { b.addActionListener( this ); f.addWindowListener( 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) { … } } Implementing 2 interfaces
  • 124. 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() { f.addWindowListener( this ); } public void windowClosing(WindowEvent e ) { … } } Need only implement the method(s) that are required, instead of all seven methods of the WindowListener interface
  • 125. But, we can only use one Adapter at a time (no multiple inheritance) I.e., cannot have : class MyApp extends WindowAdapter, MouseAdapter, ... { … … … ... }
  • 126. 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() { f.addWindowListener( new FrameHandler() ); b.addMouseListener( new ButtonHandler() ); } class ButtonHandler extends MouseAdapter { public void mousePressed (MouseEvent e ) { … } } class FrameHandler extends WindowAdapter { public void windowClosing (WindowEvent e ) { … } } }
  • 127.
  • 128.
  • 129.
  • 131. 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 MyApplet.java · javac MyApplet.java · Have MyApplet.class · Create MyApplet.html <applet code = MyApplet.class width = 200 height = 300 > </applet> · appletviewer MyApplet.html (or open MyApplet.html in browsers like Netscape/IE).
  • 132.
  • 133.
  • 135. another sample Applet (run in Applet Viewer)
  • 136. sample Applet running within Netscape
  • 137. sample Applet code import java.applet .*; // for Applet class import java.awt .*; // for Graphics class public class MyApplet extends Applet { public void paint ( Graphics g ) { g.drawString(&quot;Hi there&quot;, 40, 40); g.drawOval(40, 60, 45, 45); g.drawRect(100, 60, 50, 50); g.drawLine(170, 60, 250, 170); } // end paint() public void init () { setBackground(Color.yellow); } } // end class MyApplet
  • 138.
  • 139.
  • 140. 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.
  • 141. Incorporating Images and sound in Applets
  • 142. sample Applet with sound … … … (MyAppletSound.java)
  • 143. how to do that …. Step 1 : LOAD (image of sound file) Step 2 : DISPLAY -or- PLAY
  • 144. Applet that displays image import java.applet.*; import java.awt.*; public class MyApplet1 extends Applet { Image im; public void init () { // load im = getImage(getDocumentBase(),&quot;BOTTOMDOLLAR.JPG&quot;); setBackground(Color.yellow); } public void paint(Graphics g ) { g.drawImage(im, 50, 50, this); // display } } // end class MyApplet1
  • 145. Applet that plays sound import java.applet.*; import java.awt.*; public class MyAppletSound extends Applet { AudioClip ac; public void init () { // load ac = getAudioClip(getDocumentBase(), &quot;chirp1.au&quot;); } public void start() { ac.loop(); // play } public void stop() { ac.stop(); // stop the sound upon leaving this web page } } // end class MyAppletSound
  • 146. Multithreading in Java (A built-in feature in Java)
  • 147. Single and Multithreaded Processes Single-threaded Process Single instruction stream Multiple instruction stream Multiplethreaded Process Threads of Execution Common Address Space threads are light-weight processes within a process
  • 148.
  • 149. Thread states new runnable non-runnable dead wait() sleep() suspend() blocked notify() slept resume() unblocked start() stop()
  • 150.
  • 151.
  • 152. An example class MyThread extends Thread { // the thread public void run () { System.out.println(&quot; this thread is running ... &quot;); } } // 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. t.start(); } // end main() } // end class ThreadEx2
  • 153.
  • 154. An example class MyThread implements Runnable { public void run() { System.out.println(&quot; this thread is running ... &quot;); } } // 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(). t.start(); } // end main() } // end class ThreadEx2
  • 155. A program with two threads class MyThread implements Runnable { public void run() { System.out.println(&quot;This is 'MyThread' ); } } class YourThread implements Runnable { public void run() { System.out.println(&quot;This is 'YourThread'); } } class ThreadEx4 { public static void main(String [] args ) { Thread t1 = new Thread(new MyThread()); Thread t2 = new Thread(new YourThread()); t1.start(); t2.start(); } } // end class ThreadEx4
  • 156. Monitor model (for Syncronisation) Method 1 Method 2 Block 1 Key Threads Monitor (synchronised) solves race-condition problem
  • 157. 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 { Shared so; public YourThread (Shared s) { so = s; } public void run() { so.method2 (); } } // end class YourThread class HerThread implements Runnable { Shared so; public HerThread (Shared s) { so = s; } public void run() { so.method3 (); } } // end class HerThread so
  • 158. 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++) { System.out.print(&quot; [1] :: &quot; + i ) ; } } // if the 'synchronized' is removed, the outcome is unpredictable public synchronized void method2( ) { for (int i = 0; i < 200; i++) { System.out.print(&quot; [2] :: &quot; + i ) ; } } // if the 'synchronized' is removed, the outcome is unpredictable public synchronized void method3( ) { for (int i = 0; i < 200; i++) { System.out.print(&quot; [3] :: &quot; + i ) ; } } } // end class Shared
  • 159. 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 )); t1.start(); t2.start(); t3.start(); } // end main() } // end class ThreadEx5
  • 160.
  • 162.
  • 163. Display File Contents import java.io.*; public class FileToOut1 { public static void main(String args[]) { try { FileInputStream infile = new FileInputStream(&quot;testfile.txt&quot;); byte buffer[] = new byte[50]; int nBytesRead; do { nBytesRead = infile.read(buffer); System.out.write(buffer, 0, nBytesRead); } while (nBytesRead == buffer.length); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read failed&quot;); } } }
  • 164.
  • 165. Writing data to a file using Filters import java.io.*; public class GenerateData { public static void main(String args[]) { try { FileOutputStream fos = new FileOutputStream(&quot;stuff.dat&quot;); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(2); dos.writeDouble(2.7182818284590451); dos.writeDouble(3.1415926535); dos.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
  • 166. Reading data from a file using filters import java.io.*; public class ReadData { public static void main(String args[]) { try { FileInputStream fis = new FileInputStream(&quot;stuff.dat&quot;); DataInputStream dis = new DataInputStream(fis); int n = dis.readInt(); System.out.println(n); for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble()); } dis.close(); fis.close(); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
  • 167. Object serialization Write objects to a file, instead of writing primitive types. Use the ObjectInputStream , ObjectOutputStream classes, the same way that filters are used.
  • 168. Write an object to a file import java.io.*; import java.util.*; public class WriteDate { public WriteDate () { Date d = new Date(); try { FileOutputStream f = new FileOutputStream(&quot;date.ser&quot;); ObjectOutputStream s = new ObjectOutputStream (f); s.writeObject (d); s.close (); } catch (IOException e) { e.printStackTrace(); } public static void main (String args[]) { new WriteDate (); } }
  • 169. Read an object from a file import java.util.*; public class ReadDate { public ReadDate () { Date d = null; ObjectInputStream s = null; try { FileInputStream f = new FileInputStream (&quot;date.ser&quot;); s = new ObjectInputStream (f); } catch (IOException e) { e.printStackTrace(); } try { d = (Date) s.readObject (); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvalidClassException e) { e.printStackTrace(); } catch (StreamCorruptedException e) { e.printStackTrace(); } catch (OptionalDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println (&quot;Date serialized at: &quot;+ d); } public static void main (String args[]) { new ReadDate (); } }
  • 171.
  • 172. Part III - Networking ServerSocket(1234) Socket(“130.63.122.1”, 1234) Output/write stream Input/read stream Server_name: “cdacb.ernet.in”
  • 173.
  • 174.
  • 175. A simple server (simplified code) import java.net.*; import java.io.*; public class ASimpleServer { public static void main(String args[]) { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF(“Hi there”); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } }
  • 176. A simple client (simplified code) import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket(&quot; 130.63.122.1 &quot;,1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); } }
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184. Server Threads Message Passing Facility Server Process Client Process Client Process User Mode Kernel Mode Threads in Action... Multithreaded Server
  • 185. Java System Architecture & Availability
  • 186. A Look Inside the Java Platform Java Virtual Machine Porting Interface Applets and Applications Java Base API Java Base Classes Java Standard Extension API Java Standard Extension Classes The Java Base Platform (in black) Network Java on a Browser Java on a Desktop OS Java on a Smaller OS Java on JavaOS Adapter OS Hardware Adapter OS Hardware JavaOS Hardware Adapter Browser OS Hardware
  • 187.
  • 188. Universal Interface Internet Web Servers with JAVA applications Clients running any OS on any platform
  • 189.
  • 190. Java Development Tools (Present and Planned)
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205. Thank You ... ?

Editor's Notes

  1. How do you write and distribute applications that run on all operating systems, versions, platforms. Different binaries reside in all machines Different binaries for user interfaces.
  2. 1