SlideShare a Scribd company logo
om
       JDK 1.1 AWT
       Event Handling




                                 .c
  =====================



                             DF
                            aP
                            vi
      n      ee
   w.
ww




   Object Computing, Inc.
                             1   AWT Event Handling
om
                              AWT




                                        .c
                                DF
  • Abstract Windowing Toolkit package
     – java.awt
                              aP
  • Easier to learn than Motif/X and MFC
  • Not as easy as using graphical GUI
                              vi
    builders
     – several companies are creating them for Java
               ee

     – will output Java code that uses the AWT package
  • AWT classes fall in four categories
     –    components
      n



     –    containers
   w.




     –    layout managers
     –    event handling
ww




     Object Computing, Inc.
                                2          AWT Event Handling
om
              Steps To Use AWT




                                                    .c
  • Create a container
     – Frame, Dialog, Window, Panel, ScrollPane




                                         DF
  • Select a LayoutManager
     – Flow, Border, Grid, GridBag, Card, none (null)
  • Create components
                              aP
     – Button, Checkbox, Choice, Label, List, TextArea,
       TextField, PopupMenu
  • Add components to container
                              vi
  • Specify event handling (changed in 1.1)
               ee

     – listeners are objects interested in events
     – sources are objects that “fire” events
     – register listeners with sources
      n


            • component.add<EventType>Listener
               – EventTypes are ActionEvent, AdjustmentEvent,
   w.




                 ComponentEvent, FocusEvent, ItemEvent, KeyEvent,
                 MouseEvent, TextEvent, WindowEvent
     – implement methods of listener interfaces
       in listener classes
ww




            • an event object is passed to the methods
            • ActionListener, AdjustmentListener, ComponentListener,
              FocusListener, ItemListener, KeyListener, MouseListener,
              MouseMotionListener, TextListener, WindowListener


     Object Computing, Inc.
                                        3               AWT Event Handling
om
           Event Sources,




                                                                .c
       Listeners, and Objects




                                                  DF
                                        Event Object
                                        • describes an event
                                        • ex. ActionEvent holds state of Shift key
                             tes
                         crea
                                        aP
   Event Source
                               vi
   • generates events
   • ex. Button
           pas
              ses
                  to
              ee

                       list
                           ene
                              rm
                                eth
                                   od
                                        Event Listener
                                        • any object can implement these interfaces
                                        • ex. ActionListener has method actionPerformed()
      n
   w.
ww




    Object Computing, Inc.
                                                 4                   AWT Event Handling
om
  Simple AWT
    Example




                                                      .c
                                           DF
  import java.awt.*;
  import java.awt.event.*;




      private
      private
                                aP
  public class SimpleAWT extends java.applet.Applet
  implements ActionListener, ItemListener {

                Button button = new Button("Push Me!");
                Checkbox checkbox = new Checkbox("Check Me!");
      private   Choice choice = new Choice();
                               vi
      private   Label label = new Label("Pick something!");

      public void init() {
           button.addActionListener(this);
                ee

           checkbox.addItemListener(this);
           choice.addItemListener(this);

           // An Applet is a Container because it extends Panel.
           setLayout(new BorderLayout());
      n



           choice.addItem("Red");
   w.



           choice.addItem("Green");
           choice.addItem("Blue");

           Panel panel = new Panel();
           panel.add(button);
ww




           panel.add(checkbox);
           panel.add(choice);

           add(label, "Center");
           add(panel, "South");
      }



      Object Computing, Inc.
                                          5               AWT Event Handling
om
          Simple AWT Example




                                                      .c
                (Cont’d)




                                          DF
      public void actionPerformed(ActionEvent e) {
           if (e.getSource() == button) {
                label.setText("The Button was pushed.");
           }
      }
                                aP
      public void itemStateChanged(ItemEvent e) {
           if (e.getSource() == checkbox) {
                label.setText("The Checkbox is now " +
                                vi
                               checkbox.getState() + ".");
           } else if (e.getSource() == choice) {
                label.setText(choice.getSelectedItem() + “ was selected.”);
           }
                 ee

      }
  }
      n
   w.
ww




       Object Computing, Inc.
                                          6                AWT Event Handling
om
                       Event Classes




                                                  .c
                                      DF
  • Hierarchy
    java.util.EventObject
     – java.awt.AWTEvent      aP
            • java.awt.event.ComponentEvent
                – java.awt.event.FocusEvent
                              vi
                – java.awt.event.InputEvent
                    • java.awt.event.KeyEvent
                    • java.awt.event.MouseEvent
               ee

            • java.awt.event.ActionEvent
            • java.awt.event.AdjustmentEvent
            • java.awt.event.ItemEvent
            • java.awt.event.TextEvent
      n



  • Can create custom, non-AWT event
   w.




    classes
     – extend java.util.EventObject
ww




     Object Computing, Inc.
                                      7           AWT Event Handling
om
       Event Object Contents




                                                       .c
                                           DF
  • java.util.EventObject
     – source holds a reference to the object that fired the event
     – java.awt.AWTEvent
            • id indicates event type
                                aP
                – set to a constant in specific event classes
                   (listed on following pages)
            • java.awt.event.ActionEvent
                – modifiers indicates state of control, shift, and meta (alt)
                              vi
                   keys
                – actionCommand holds the action specific command
                   string
               ee

                     • usually the label of a Button or MenuItem
            • java.awt.event.AdjustmentEvent
                – for Scrollbars
                                                                      used for
      n


                – value holds value
                                                                      checkboxes and
                – adjustmentType is unit +/-, block +/-, track        radio buttons
   w.




            • java.awt.event.ItemEvent
                – for Choice, List, Checkbox, and CheckboxMenuItem
                – stateChange indicates selected or deselected
            • java.awt.event.TextEvent
ww




                – listeners are notified of every keystroke that changes the
                   value
                – listeners are also notified when setText() is called
            • other subclasses are on the following pages


     Object Computing, Inc.
                                           8               AWT Event Handling
om
      Event Object Contents




                                                       .c
            (Cont’ d)




                                          DF
  • java.awt.AWTEvent
    – java.awt.event.ComponentEvent
                               aP
           • id indicates moved, resized, shown, or hidden
           • java.awt.event.ContainerEvent
               – id indicates added or removed
               – child holds a reference to the component added or
                             vi
                  removed
           • java.awt.event.FocusEvent
               – id indicates gained or lost
              ee

               – temporary indicates temporary or permanent
                  (see documentation in source)
           • java.awt.event.WindowEvent
      n


               – id indicates opened, closing, closed, iconified, deiconified,
                  activated, and deactivated
   w.




                                               brought to front
ww




    Object Computing, Inc.
                                         9                 AWT Event Handling
om
      Event Object Contents




                                                    .c
            (Cont’ d)




                                         DF
  • java.awt.AWTEvent
     – java.awt.event.InputEvent
                              aP
           • modifiers is a mask that holds
               – state of control, shift, and meta (alt) keys
               – state of mouse buttons 1, 2, & 3
           • when holds time the event occurred
                             vi
               – probably should have been put in java.util.EventObject!
           • java.awt.event.KeyEvent
              ee

               – id indicates typed, pressed, or released
               – keyChar holds the ascii code of the key pressed
               – keyCode holds a constant identifying the key pressed
                  (needed for non-printable keys)
      n


           • java.awt.event.MouseEvent
               – id indicates clicked, pressed, released, moved, entered,
   w.




                  exited, or dragged
               – clickCount holds # of times button was clicked
               – x,y hold location of mouse cursor
ww




    Object Computing, Inc.
                                        10              AWT Event Handling
om
    Event Listener Interfaces




                                                  .c
  • Class hierarchy and methods




                                       DF
     – java.util.EventListener
            • java.awt.event.ActionListener
                – actionPerformed
            • java.awt.event.AdjustmentListener

                              aP
                – adjustmentValueChanged
            • java.awt.event.ComponentListener
                – componentHidden, componentMoved, componentResized,
                   componentShown
            • java.awt.event.FocusListener
                              vi
                – focusGained, focusLost
            • java.awt.event.ItemListener
               ee

                – itemStateChanged
            • java.awt.event.KeyListener
                – keyPressed, keyReleased, keyTyped
            • java.awt.event.MouseListener
      n


                – mouseEntered, mouseExited,
                   mousePressed, mouseReleased, mouseClicked
   w.




            • java.awt.event.MouseMotionListener
                – mouseDragged, mouseMoved
            • java.awt.event.TextListener
                – textValueChanged
ww




            • java.awt.event.WindowListener
                – windowOpened, windowClosing, windowClosed,
                   windowActivated, windowDeactivated, windowIconified,
                   windowDeiconified


     Object Computing, Inc.
                                       11            AWT Event Handling
om
                 Event Sources and




                                            .c
                  Their Listeners




                                   DF
  • Component (ALL components extend this)
       – ComponentListener, FocusListener, KeyListener,


  •   Dialog - WindowListener
                                aP
         MouseListener, MouseMotionListener


  •   Frame - WindowListener
                                vi
  •   Button - ActionListener
                 ee

  •   Choice - ItemListener
  •   Checkbox - ItemListener
      n



  •   CheckboxMenuItem - ItemListener
   w.




  •   List - ItemListener, ActionListener   when an item is
                                            double-clicked

  •   MenuItem - ActionListener
ww




  •   Scrollbar - AdjustmentListener
  •   TextField - ActionListener, TextListener
  •   TextArea - TextListener
       Object Computing, Inc.
                                   12          AWT Event Handling
om
    Listener Adapter Classes




                                                      .c
                                          DF
  • Provide empty default implementations of
    methods in listener interfaces with more
    than one method
  • They include
                               aP
                              vi
     –    java.awt.event.ComponentAdapter
     –    java.awt.event.FocusAdapter
               ee

     –    java.awt.event.KeyAdapter
     –    java.awt.event.MouseAdapter
     –    java.awt.event.MouseMotionAdapter
      n


     –    java.awt.event.WindowAdapter
  • To use, extend from them
   w.




     – override methods of interest
     – usefulness is limited by single inheritance
ww




            • can’ do if another class is already being extended
                   t
            • implementation for methods that are not of interest could look
              like this
              public void windowIconified(WindowEvent e) {}



     Object Computing, Inc.
                                          13              AWT Event Handling
om
         Design For Flexibility




                                                                    .c
          and Maintainability




                                           DF
                                                           invokes app. methods              Event
                                        App
                                                                                            Handlers
  • Can separate




                                                                                                              rs
                                                                                                            ne
                                          pa ates




                                                                                                           d

                                                                                                   nts liste
                                            cre
                                            sse GU




                                                                                    co rs h re an
     – application code

                                                ss




                                                                                  of iste App dlers

                                                                                              t e as
                               aP                 elf I




                                                                                      mp an f.,
                                                                                            en rs
                                                                                                   n
                                                     an




                                                                                         on dle
                                                                                                 ve
                                                                                        sse ha
                                                       d
     – GUI code




                                                                                      pa ates
                                                                                    reg s
                                                                                        cre
                                                                   GUI
     – event handling code
  • Steps to achieve this separation
                              vi
     – create a single class whose constructor creates the
       entire GUI, possibly using other GUI-only classes
               ee

     – create the GUI by invoking this constructor from an
       application class
     – create classes whose only function is to be notified of
      n



       GUI events and invoke application methods
            • their constructors should accept references to application
   w.




              objects whose methods they will invoke
     – create event handling objects in a GUI class and
       register them with the components whose events they
ww




       will handle




     Object Computing, Inc.
                                           14                             AWT Event Handling
om
                     AWT Example




                                          .c
                                 DF
                              aP
                              vi
  • FontTest allows specification of text to be
    displayed, font name, style, color and size
               ee

  • It illustrates
     • creation of GUI components
      n



     • use of the Canvas and PopupMenu
   w.




     • component layout using BorderLayout,
         FlowLayout, and GridLayout
     • event handling
ww




  • Invoke with
     <APPLET CODE=FontTest.class WIDTH=580 HEIGHT=250>
     </APPLET>


     Object Computing, Inc.
                                 15          AWT Event Handling
om
                         FontTest.java




                                                       .c
                                          DF
  import   java.awt.*;
  import   java.awt.event.*;
  import   java.util.Enumeration;
  import   COM.ociweb.awt.ColorMap;


                                  aP
  public class FontTest extends java.applet.Applet
  implements ActionListener, AdjustmentListener, ItemListener, MouseListener {

     static final String DEFAULT_FONT = "Helvetica";
     static final String DEFAULT_TEXT = "FontTest";
                                vi
     static final int DEFAULT_SIZE = 24;

     private static final int BOX_SIZE = 3;
     private static final int MIN_SIZE = 6;
                 ee

     private static final int MAX_SIZE = 250;

     private CheckboxGroup styleGroup = new CheckboxGroup();
     private Checkbox boldRadio = new Checkbox("Bold", false, styleGroup);
     private Checkbox bothRadio = new Checkbox("Both", false, styleGroup);
      n


     private Checkbox italicRadio =
         new Checkbox("Italic", false, styleGroup);
   w.



     private Checkbox plainRadio = new Checkbox("Plain", true, styleGroup);
     private Choice fontChoice = new Choice();
     private List colorList = new List(4, false);
     private MyCanvas myCanvas = new MyCanvas();
     private PopupMenu popup = new PopupMenu("Font");
ww




     private Scrollbar scrollbar =
         new Scrollbar(Scrollbar.HORIZONTAL, DEFAULT_SIZE, BOX_SIZE,
                       MIN_SIZE, MAX_SIZE + BOX_SIZE);
     private TextField sizeField =
         new TextField(String.valueOf(DEFAULT_SIZE), 3);
     private TextField textField = new TextField(DEFAULT_TEXT, 40);



       Object Computing, Inc.
                                          16             AWT Event Handling
om
      FontTest.java (Cont’d)




                                                    .c
                                         DF
   public void init() {
       fontChoice.addItem("TimesRoman");
       fontChoice.addItem("Helvetica");
       fontChoice.addItem("Courier");


                             aP
       fontChoice.select(DEFAULT_FONT);

       Panel fontPanel = new Panel();
       fontPanel.add(new Label("Font:"));
       fontPanel.add(fontChoice);
                             vi
       Panel stylePanel = new Panel();
       stylePanel.add(plainRadio);
       stylePanel.add(boldRadio);
       stylePanel.add(italicRadio);
              ee

       stylePanel.add(bothRadio);

       Enumeration e = ColorMap.getColorNames();
       while (e.hasMoreElements()) {
           colorList.addItem((String) e.nextElement());
      n


       }
       colorList.select(0);
   w.




       Panel sizePanel = new Panel();
       sizePanel.add
           (new Label("Size (" + MIN_SIZE + "-" + MAX_SIZE + ")"));
       sizePanel.add(sizeField);
ww




       Panel westPanel = new Panel(new GridLayout(0, 1));
       westPanel.add(fontPanel);
                                                          unknown # of rows,
       westPanel.add(stylePanel);
                                                          one column
       westPanel.add(colorList);
       westPanel.add(sizePanel);



    Object Computing, Inc.
                                         17             AWT Event Handling
om
         FontTest.java (Cont’d)




                                                     .c
                                           DF
          setLayout(new BorderLayout());
          add(myCanvas, "Center");
          add(westPanel, "West");


                                aP
          add(textField, "North");
          add(scrollbar, "South");

          fontChoice.addItemListener(this);
          plainRadio.addItemListener(this);
          boldRadio.addItemListener(this);
                                vi
          italicRadio.addItemListener(this);
          bothRadio.addItemListener(this);
          colorList.addItemListener(this);
          sizeField.addActionListener(this);
                 ee

          textField.addActionListener(this);
          scrollbar.addAdjustmentListener(this);
          fontPanel.addMouseListener(this);
          stylePanel.addMouseListener(this);
          sizePanel.addMouseListener(this);
      n


          myCanvas.addMouseListener(this);

          MenuItem timesRomanItem = new MenuItem("TimesRoman");
   w.




          MenuItem helveticaItem = new MenuItem("Helvetica");
          MenuItem courierItem = new MenuItem("Courier");
          timesRomanItem.addActionListener(this);
          helveticaItem.addActionListener(this);
ww




          courierItem.addActionListener(this);
          popup.add(timesRomanItem);
          popup.add(helveticaItem);
          popup.add(courierItem);
          add(popup);
   }



       Object Computing, Inc.
                                           18            AWT Event Handling
om
      FontTest.java (Cont’d)




                                                  .c
    public void actionPerformed(ActionEvent e) {
       Object source = e.getSource();
       if (source == textField) {
           myCanvas.setText(textField.getText());




                                       DF
       } else if (source == sizeField) {
           int size = Integer.parseInt(sizeField.getText());
           scrollbar.setValue(size);
           setFont();
       } else if (source instanceof MenuItem) {
           MenuItem menuItem = (MenuItem) source;




       }
           }
               setFont();
                             aP
           if (menuItem.getParent() == popup) {
               fontChoice.select(e.getActionCommand());




   }
                             vi
   public void adjustmentValueChanged(AdjustmentEvent e) {
       if (e.getSource() == scrollbar) {
              ee

           sizeField.setText(String.valueOf(scrollbar.getValue()));
           setFont();
       }
   }

   public void itemStateChanged(ItemEvent e) {
      n


       Object source = e.getSource();
       if (source == fontChoice) {
   w.



           setFont();
       } else if (source instanceof Checkbox) {
           Checkbox checkbox = (Checkbox) source;
           if (checkbox.getCheckboxGroup() == styleGroup) {
               setFont();
ww




           }
       } else if (source == colorList) {
           Color color = ColorMap.getColor(colorList.getSelectedItem());
           myCanvas.setColor(color);
       }
   }



    Object Computing, Inc.
                                       19             AWT Event Handling
om
            FontTest.java (Cont’d)




                                                       .c
                                            DF
      // MouseListener methods that need no action.
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mouseClicked(MouseEvent e) {}


                                   aP
      public void mouseReleased(MouseEvent e) {}

      public void mousePressed(MouseEvent e) {

      }
          popup.show((Component) e.getSource(), e.getX(), e.getY());
                                   vi
      private void setFont() {
          int style = Font.PLAIN;

            Checkbox styleRadio = styleGroup.getSelectedCheckbox();
                    ee

            if (styleRadio == plainRadio) {
                style = Font.PLAIN;
            } else if (styleRadio == boldRadio) {
                style = Font.BOLD;
            } else if (styleRadio == italicRadio) {
      n


                style = Font.ITALIC;
            } else if (styleRadio == bothRadio) {
   w.



                style = Font.BOLD + Font.ITALIC;
            }

            Font font =
                new Font(fontChoice.getSelectedItem(),
ww




                         style,
                         Integer.parseInt(sizeField.getText()));

            myCanvas.setFont(font);
      }
  }



          Object Computing, Inc.
                                            20             AWT Event Handling
om
         FontTest.java (Cont’d)




                                                     .c
                                            DF
  class MyCanvas extends Canvas {
      private Color color = Color.black;
      private Font font =
          new Font(FontTest.DEFAULT_FONT,
                   Font.PLAIN,
                                aP
                   FontTest.DEFAULT_SIZE);
      private String text = FontTest.DEFAULT_TEXT;

      public void setColor(Color color) {
                                vi
          this.color = color;
          repaint();
      }
                 ee

      public void setFont(Font font) {
          this.font = font;
          repaint();
      }
      n


      public void setText(String text) {
          this.text = text;
          repaint();
   w.




      }

      public void paint(Graphics g) {
          g.setColor(color);
          g.setFont(font);
ww




          g.drawString(text, 10, 200);
      }
  }




       Object Computing, Inc.
                                            21       AWT Event Handling
om
                      ColorMap.java




                                                       .c
                                          DF
  package COM.ociweb.awt;

  import java.awt.Color;
  import java.util.Enumeration;
  import java.util.Hashtable;

  public class ColorMap {
                                  aP
      private static Hashtable hashtable = new Hashtable();

      static {
                                vi
          hashtable.put("White", Color.white);
          hashtable.put("Gray", Color.gray);
          hashtable.put("DarkGray", Color.darkGray);
          hashtable.put("Black", Color.black);
                 ee

          hashtable.put("Red", Color.red);
          hashtable.put("Pink", Color.pink);
          hashtable.put("Orange", Color.orange);
          hashtable.put("Yellow", Color.yellow);
          hashtable.put("Green", Color.green);
      n


          hashtable.put("Magenta", Color.magenta);
          hashtable.put("Cyan", Color.cyan);
          hashtable.put("Blue", Color.blue);
   w.




      }

      public static Color getColor(String name) {
          return (Color) hashtable.get(name);
ww




      }

      public static Enumeration getColorNames() {
          return hashtable.keys();
      }
  }



       Object Computing, Inc.
                                          22             AWT Event Handling
om
                        Appendix A




                                  .c
                              DF
                      JDK 1.0
                       AWT  aP
                   Event Handling
                            vi
      n      ee
   w.
ww




   Object Computing, Inc.
                             23      AWT Event Handling
om
   1.0 Default Event Handling




                                                            .c
                (delegation-based event handling was added in Java 1.1)




                                               DF
  • Provided by Component class
  • handleEvent(Event evt)
                                   aP
     – first method invoked when an event occurs
     – default implementation tests for specific types of
       events and invokes the methods below
                              vi
  • Methods to handle specific types of events
     – default implementations do nothing
                ee

     – they are
            • mouseDown and mouseUp
            • mouseDrag and mouseMove
            • mouseEnter and mouseExit
      n



            • keyDown and keyUp
            • gotFocus and lostFocus
   w.




               – from mouse click, tab key, or requestFocus method
            • action (discussed two slides ahead)

  • All event handling methods return boolean
ww




     – indicates whether they handled the event
     – if false, the event is handled recursively by
       containers

     Object Computing, Inc.
                                              24                AWT Event Handling
om
       Overriding 1.0 Default
         Event Handling




                                                      .c
  • Custom event handling methods other than




                                          DF
    handleEvent
     – created by overriding implementations in Component
       which do nothing
                               aP
     – invoked by the default handleEvent implementation
  • Custom handleEvent method
                              vi
     – created by overriding implementation in Component
     – can handle all events by comparing id field to
       constants in Event class to see what kind of event
               ee

       occurred
     – if overridden, other event handling methods will not
       be invoked unless
      n



            • they are invoked directly from this method
                – not recommended approach
   w.




            • this method invokes the handleEvent method of a superclass
                – recommended approach
                – do this if the event is not one you wish to handle in your
ww




                   handleEvent method
                – invoke with “return super.handleEvent(e); ”
                – first superclass to implement handleEvent is typically
                   Component which disperses the event to methods which
                   handle specific types of events


     Object Computing, Inc.
                                          25              AWT Event Handling
om
                 1.0 Action Events




                                                           .c
  • Most user interface components generate
    “action” events




                                            DF
     – Label and TextArea don’ generate any events
                                t
     – List and Scrollbar generate events that are not
       “action” events
            • must be handled in a handleEvent method,
                                aP
              not an action method

  • Default handleEvent invokes
    public boolean action(Event evt, Object what)
                              vi
  • Second argument varies based on the
    component
               ee

     – Button
            • String representing button label
     – Checkbox (and radiobutton)
      n


            • Boolean state (true for on, false for off)
            • generated when picked
   w.




     – Choice (option menu)
            • String representing selected item
     – TextField
ww




            • null
            • generated when user presses return key
            • not when field is exited with mouse or tab key
               – use lostFocus method to catch that


     Object Computing, Inc.
                                           26              AWT Event Handling
ww
Java Tutorial                           Extending Classes and Interfaces



                                      Inheritance in Java
                                                                                               java-06.fm




                 w.
Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base
class or superclass) with another class (called the derived class or subclass). In Java,



                            ne
inheritance is used for two purposes:

1. class inheritance - create a new class as an extension of another class, primarily for the purpose
   of code reuse. That is, the derived class inherits the public methods and public data of the

   inheritance.
                                        ev
   base class. Java only allows a class to have one immediate base class, i.e., single class

2. interface inheritance - create a new class to implement the methods defined as part of an



                                                        ia
   interface for the purpose of subtyping. That is a class that implements an interface “conforms
   to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.



                                                                      PD
In Java, these two kinds of inheritance are made distinct by using different language syntax. For
class inheritance, Java uses the keyword extends and for interface inheritance Java uses the
keyword implements.

public class derived-class-name extends base-class-name {
    // derived class methods extend and possibly override
                                                                           F.
                                                                                    co
    // those of the base class
}

public class class-name implements interface-name {


}
    // class provides an implementation for the methods
    // as specified by the interface
                                                                                                m
Greg Lavender                                    Slide 1 of 12                                   6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                               Example of class inhertiance
                                                                                                java-06.fm




                 w.
package MyPackage;




                            ne
class Base {
    private int x;
    public int f() { ... }



                                        ev
    protected int g() { ... }
}

class Derived extends Base {
    private int y;

                                                         ia
    public int f() { /* new implementation for Base.f() */ }



                                                                       PD
    public void h() { y = g(); ... }
}

In Java, the protected access qualifier means that the protected item (field or method) is visible to a



                                                                            F.
any derived class of the base class containing the protected item. It also means that the protected
item is visible to methods of other classes in the same package. This is different from C++.




                                                                                    co
Q: What is the base class of class Object? I.e., what would you expect to get if you executed the
following code?

Object x = new Object();
System.out.println(x.getClass().getSuperclass());

                                                                                                m
Greg Lavender                                     Slide 2 of 12                                     6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                        Order of Construction under Inheritance
                                                                                                java-06.fm




                 w.
Note that when you construct an object, the default base class constructor is called implicitly, before
the body of the derived class constructor is executed. So, objects are constructed top-down under



                            ne
inheritance. Since every object inherits from the Object class, the Object() constructor is always
called implicitly. However, you can call a superclass constructor explicitly using the builtin super
keyword, as long as it is the first statement in a constructor.



                                        ev
For example, most Java exception objects inherit from the java.lang.Exception class. If you wrote
your own exception class, say SomeException, you might write it as follows:




                                                         ia
public class SomeException extends Exception {

        public SomeException() {

        }

        public SomeException(String s) {
                                                                       PD
          super(); // calls Exception(), which ultimately calls Object()




        }
                                                                            F.
          super(s); // calls Exception(String), to pass argument to base class


        public SomeException (int error_code) {
          this("error”); // class constructor above, which calls super(s)
          System.err.println(error_code);                                           co
}
        }

                                                                                                 m
Greg Lavender                                     Slide 3 of 12                                   6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                                    Abstract Base Classes
                                                                                            java-06.fm




                 w.
An abstract class is a class that leaves one or more method implementations unspecified by
declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A



                            ne
subclass is required to override the abstract method and provide an implementation. Hence, an
abstract class is incomplete and cannot be instantiated, but can be used as a base class.

abstract public class abstract-base-class-name {


                                         ev
    // abstract class has at least one abstract method

        public abstract return-type abstract-method-name ( formal-params );



                                                         ia
        ... // other abstract methods, object methods, class methods



                                                                       PD
}

public class derived-class-name extends abstract-base-class-name {

        public return-type abstract-method-name (formal-params) { stmt-list; }

        ... // other method implementations
                                                                              F.
                                                                                        co
}

It would be an error to try to instantiate an object of an abstract type:

abstract-class-name obj = new abstract-class-name();

That is, operator new is invalid when applied to an abstract class.
                                                                            // ERROR!

                                                                                             m
Greg Lavender                                     Slide 4 of 12                               6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                               Example abstract class usage
                                                                                                java-06.fm




                 w.
abstract class Point {
    private int x, y;



                            ne
    public Point(int x, int y) { this.x = x; this.y = y; }
    public void move(int dx, int dy)
    { x += dx; y += dy; plot(); }



                                        ev
    public abstract void plot(); // has no implementation
}

abstract class ColoredPoint extends Point {
    private int color;

                                                         ia
    protected public ColoredPoint(int x, int y, int color)



                                                                       PD
    { super(x, y); this.color = color; }
}

class SimpleColoredPoint extends ColoredPoint {



                                                                            F.
    public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); }
    public void plot() { ... } // code to plot a SimpleColoredPoint
}



                                                                                    co
Since ColoredPoint does not provide an implementation of the plot method, it must be declared
abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an
error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point


                                                                                                m
reference and initialize it with an instance of a subclass object that implements the plot method:

Point p = new SimpleColoredPoint(a, b, red); p.plot();


Greg Lavender                                     Slide 5 of 12                                   6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                                              Interfaces
                                                                                                java-06.fm




                 w.
An abstract class mixes the idea of mutable data in the form of instance variables, non-abstract
methods, and abstract methods. An abstract class with only static final instance variables and all



                            ne
abstract methods is called an interface. An interface is a specification, or contract, for a set of
methods that a class that implements the interface must conform to in terms of the type signature of
the methods. The class that implements the interface provides an implementation for each method,
just as with an abstract method in an abstract class.


                                        ev
So, you can think of an interface as an abstract class with all abstract methods. The interface itself
can have either public, package, private or protected access defined. All methods declared in an



                                                         ia
interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered
redundant to declare a method in an interface to be abstract.


an interface, then they are implicitly defined to be:

• public.
                                                                       PD
You can define data in an interface, but it is less common to do so. If there are data fields defined in



• static, and
• final
                                                                            F.
In other words, any data defined in an interface are treated as public constants.
                                                                                    co
                                                                                                 m
Note that a class and an interface in the same package cannot share the same name.

Methods declared in an interace cannot be declared final. Why?



Greg Lavender                                     Slide 6 of 12                                   6/15/99
ww
Java Tutorial                           Extending Classes and Interfaces



                                     Interface declaration
                                                                                               java-06.fm




                 w.
Interface names and class names in the same package must be distinct.




                            ne
public interface interface-name {

        // if any data are defined, they must be constants
        public static final type-name var-name = constant-expr;


                                        ev
        // one or more implicitly abstract and public methods
        return-type method-name ( formal-params );



                                                        ia
}

An interface declaraion is nothing more than a specification to which some class that purports to


                                                                      PD
implement the interface must conform to in its implementation. That is, a class the implements the
interface must have defined implementations for each of the interface methods.

The major reason for interfaces being distinct elements in Java is that you often want to define some


                                                                           F.
operation to operate on objects that all conform to the same interface. So, you can define some code in
a very general way, with a guarantee that by only using the methods defined in the interface, that all



                                                                                    co
objects that implement the interface will have defined implementations for all the methods.

For example, you might define a Shape interface that defines an area() method, and so you would
expect that any class that implements the Shape interface, would define an area method. So, if I



                                                                                                m
have a list of references to objects that implement the Shape interface, I can legitimately invoke the
area method, abstractly, on each of these objects and expect to obtain as a result a value that
represents the area of some shape.



Greg Lavender                                    Slide 7 of 12                                   6/15/99
ww
Java Tutorial                           Extending Classes and Interfaces



                    Separation of Interface from Implementations
                                                                                               java-06.fm




                 w.
Interfaces are specifications for many possible implementations. Interfaces are used to define a
contract for how you interact with an object, independent of the underlying implementation. The



                            ne
objective of an object-oriented programmer is to separate the specification of the interface from the
hidden details of the implementation.

Consider the specification of a common LIFO stack.

public interface StackInterface {
    boolean empty();                    ev
                                                        ia
    void push(Object x);
    Object pop() throws EmptyStackException;
    Object peek() throws EmptyStackException;
}

                                                                      PD
Note that the methods in this interface are defined to operate on objects of type Object. Since a stack
is a “container type”, it is very common to use the base class for all objects, namely Object, as the


                                                                           F.
type of the arguments and results to a container type. Since all objects ultimately inherit from class
Object, we can always generically refer to any object in the system using an Object reference.



                                                                                    co
However, when we pop from a stack, we have to explicitly type case from the very general type
Object to a concrete type, so that we can manipulate the object concretely.

Q: How many different ways are there to implement a stack? If we are using just using a Stack object



                                                                                                m
(as opposed to implementing it ourselves) should we care?




Greg Lavender                                    Slide 8 of 12                                   6/15/99
ww
Java Tutorial                     Extending Classes and Interfaces



                    Stack implementation of the StackInterface
                                                                                 java-06.fm




                w.
public class Stack implements StackInterface {



                         ne
        private Vector v = new Vector();         // use java.util.Vector class




                                  ev
        public boolean empty() { return v.size() == 0; }

        public void push(Object item) { v.addElement(item); }

        public Object pop() {
            Object obj = peek();
                                                  ia
                                                                PD
            v.removeElementAt(v.size() - 1);
            return obj;
        }




                                                                     F.
        public Object peek() throws EmptyStackException {
            if (v.size() == 0)
               throw new EmptyStackException();



                                                                         co
            return v.elementAt(v.size() - 1);
        }
}



                                                                                 m
Greg Lavender                              Slide 9 of 12                           6/15/99
ww
Java Tutorial                              Extending Classes and Interfaces



                      Should a stack use or inherit from a vector?
                                                                                                     java-06.fm




                  w.
The java.util.Stack class is defined as a subclass of the java.util.Vector class, rather than using a
Vector object as in the previous example. This sort of inheritance is not subtype inheritance, because



                             ne
the interface of a Stack object can be violated because a Vector has a “wider” interface than a Stack,
i.e., a vector allows insertion into the front and the rear, so it is possible to violate the stack contract
by treating a stack object as a vector, and violating the LIFO specification of a stack.

public class Stack extends Vector {

                                          ev
   public Object push(Object item) {addElement(item); return item;}
   public Object pop() {



                                                           ia
        Object obj;
        int len = size();



                                                                         PD
        obj = peek();
        removeElementAt(len - 1);
        return obj;
   }
   public Object peek() {
        int len = size();
        if (len == 0) throw new EmptyStackException();
                                                                               F.
                                                                                         co
        return elementAt(len - 1);
   }
   public boolean empty() { return size() == 0;}
}

Vector v = new Stack(); // legal - base class reference to subclass object
v.insertElementAt(x, 2); // insert object x into Vector slot 2!!                                     m
Greg Lavender                                       Slide 10 of 12                                     6/15/99
ww
Java Tutorial                            Extending Classes and Interfaces



                When to use an Interface vs when to use an abstract class
                                                                                                 java-06.fm




                   w.
Having reviewed their basic properties, there are two primary differences between interfaces and
abstract classes:



                            ne
• an abstract class can have a mix of abstract and non-abstract methods, so some default
  implementations can be defined in the abstract base class. An abstract class can also have static
  methods, static data, private and protected methods, etc. In other words, a class is a class, so it


                                         ev
  can contain features inherent to a class. The downside to an abstract base class, is that since their
  is only single inheritance in Java, you can only inherit from one class.
• an interface has a very restricted use, namely, to declare a set of public abstract method



                                                         ia
  singatures that a subclass is required to implement. An interfaces defines a set of type
  constraints, in the form of type signatures, that impose a requirement on a subclass to implement
  the methods of the interface. Since you can inherit multiple interfaces, they are often a very


                                                                       PD
  useful mechanism to allow a class to have different behaviors in different situations of usage by
  implementing multiple interfaces.




                                                                            F.
It is usually a good idea to implement an interface when you need to define methods that are to be
explicitly overridden by some subclass. If you then want some of the methods implemented with



                                                                                      co
default implementations that will be inherited by a subclass, then create an implementation class
for the interface, and have other class inherit (extend) that class, or just use an abstract base class
instead of an interface.




                                                                                                  m
Greg Lavender                                     Slide 11 of 12                                    6/15/99
ww
Java Tutorial                             Extending Classes and Interfaces



                     Example of default interface implementations
                                                                                                   java-06.fm




interface X {
    void f();    w.
                             ne
    int g();
}




                                         ev
class XImpl implements X {
    void g() { return -1; } // default implementation for g()
}

class Y extends XImpl implements X {
    void f() { ... } // provide implementation for f()
                                                          ia
                                                                        PD
}

Note that when you invoke an abtract method using a reference of the type of an abstract class or an
interface, the method call is dynamically dispatched.

X x = new Y();
x.f();
                                                                              F.
                                                                                       co
The call x.f() causes a run-time determination of the actual type of object that ‘x’ refers to, then a
method lookup to determine which implementation of f() to invoke. In this case, Y.f(x) is called, but
the type of x is first converted to Y so that the ‘this’ reference is initialized to a reference of type Y
inside of f(), since the implicit type signature of Y.f() is really Y.f(final Y this);

                                                                                                    m
Greg Lavender                                      Slide 12 of 12                                    6/15/99
ww
       w.n
                 ee
                        vi
                          aP
                             DF
           Java Array



1
DF
                          Agenda



                      aP
 ●   What is an array


                 vi
 ●   Declaration of an array
            ee
 ●   Instantiation of an array
 ●   Accessing array element
       .n
 ●   Array length
 ●   Multi-dimensional array
   w
ww




                                   2
DF
        aP
        vi
       ee
   .n
   w


   What is an Array?
ww




                       3
DF
          Introduction to Arrays



                      aP
 ●   Suppose we have here three variables of type int with


                 vi
     different identifiers for each variable.
            ee
        int number1;
        int number2;
        int number3;
       .n
        number1 = 1;
        number2 = 2;
   w

        number3 = 3;
ww



     As you can see, it seems like a tedious task in order to just
     initialize and use the variables especially if they are used for
     the same purpose.


                                                                        4
DF
          Introduction to Arrays



                     aP
 ●   In Java and other programming languages, there is one


                 vi
     capability wherein we can use one variable to store a list of
     data and manipulate them more efficiently. This type of
            ee
     variable is called an array.
       .n
 ●   An array stores multiple data items of the same data type, in
     a contiguous block of memory, divided into a number of
     slots.
   w
ww




                                                                     5
DF
         aP
        vi
       ee
   .n

       Declaration of
   w
ww




         an Array
                        6
DF
                Declaring Arrays



                        aP
 ●   To declare an array, write the data type, followed by a set of


                 vi
     square brackets[], followed by the identifier name.
             ee
 ●   For example,
          int []ages;
          .n
     or
          int ages[];
   w
ww




                                                                      7
DF
          aP
        vi
       ee
   .n

       Instantiation of
   w
ww




          an Array
                          8
DF
                   Array Instantiation



                               aP
 ●   After declaring, we must create the array and specify its


                         vi
     length with a constructor statement.
                ee
 ●   Definitions:
      –   Instantiation
          .n
            ●   In Java, this means creation
   w

      –   Constructor
            ●   In order to instantiate an object, we need to use a constructor for this. A
ww



                constructor is a method that is called to create a certain object.
            ●   We will cover more about instantiating objects and constructors later.




                                                                                              9
DF
              Array Instantiation



                     aP
 ●   To instantiate (or create) an array, write the new keyword,


                 vi
     followed by the square brackets containing the number of
     elements you want the array to have.
            ee
 ●   For example,
        //declaration
       .n
         int ages[];

        //instantiate object
   w

        ages = new int[100];

     or, can also be written as,
ww



        //declare and instantiate object
        int ages[] = new int[100];




                                                                   10
DF
       Array Instantiation



          aP
        vi
       ee
   .n
   w
ww




                             11
DF
              Array Instantiation



                      aP
 ●   You can also instantiate an array by directly initializing it with


                  vi
     data.
            ee
 ●   For example,
        int arr[] = {1, 2, 3, 4, 5};
       .n

     This statement declares and instantiates an array of integers
     with five elements (initialized to the values 1, 2, 3, 4, and 5).
   w
ww




                                                                          12
DF
                 Sample Program



                      aP
 1    //creates an array of boolean variables with identifier
 2    //results. This array contains 4 elements that are




                   vi
 3    //initialized to values {true, false, true, false}
 4
 5    boolean results[] = { true, false, true, false };
             ee
 6
 7    //creates an array of 4 double variables initialized
 8    //to the values {100, 90, 80, 75};
 9
         .n
 10   double []grades = {100, 90, 80, 75};
 11
 12   //creates an array of Strings with identifier days and
   w

 13   //initialized. This array contains 7 elements
 14
 15   String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,
ww



      “Sun”};




                                                                    13
DF
          aP
        vi
       ee
   .n
   w


       Accessing Array
ww




          Element
                         14
DF
 Accessing an Array Element



                         aP
 ●   To access an array element, or a part of the array, you use


                    vi
     a number called an index or a subscript.
              ee
 ●   index number or subscript
      –   assigned to each member of the array, to allow the program to
          .n
          access an individual member of the array.
      –   begins with zero and progress sequentially by whole numbers to the
   w

          end of the array.
      –   NOTE: Elements inside your array are from 0 to (sizeOfArray-1).
ww




                                                                               15
DF
 Accessing an Array Element



                    aP
 ●   For example, given the array we declared a while ago, we


                vi
     have
        //assigns 10 to the first element in the array
           ee
        ages[0] = 10;

        //prints the last element in the array
       .n
        System.out.print(ages[99]);
   w
ww




                                                                16
DF
 Accessing an Array Element



                        aP
 ●   NOTE:


                   vi
     –   once an array is declared and constructed, the stored value of each
         member of the array will be initialized to zero for number data.
             ee
     –   for reference data types such as Strings, they are NOT initialized to
         blanks or an empty string “”. Therefore, you must populate the String
         arrays explicitly.
   w     .n
ww




                                                                                 17
DF
 Accessing an Array Element



                     aP
 ●   The following is a sample code on how to print all the


                 vi
     elements in the array. This uses a for loop, so our code is
     shorter.
            ee
     1   public class ArraySample{
     2      public static void main( String[] args ){
         .n
     3         int[] ages = new int[100];
     4         for( int i=0; i<100; i++ ){
     5            System.out.print( ages[i] );
   w

     6         }
     7      }
     8   }
ww




                                                                   18
DF
           Coding Guidelines



                  aP
 1. It is usually better to initialize or instantiate the


              vi
   array right away after you declare it. For example,
   the declaration,
         ee
      int []arr = new int[100];
     .n

   is preferred over,
   w


      int []arr;
ww



      arr = new int[100];




                                                            19
DF
          Coding Guidelines



                 aP
 2. The elements of an n-element array have indexes


             vi
   from 0 to n-1. Note that there is no array element
   arr[n]! This will result in an array-index-out-of-
         ee
   bounds exception.
     .n
 3. Remember: You cannot resize an array.
   w
ww




                                                        20
DF
        aP
        vi
       ee
   .n
   w


       Array Length
ww




                      21
DF
                    Array Length



                      aP
 ●   In order to get the number of elements in an array, you can


                  vi
     use the length field of an array.
            ee
 ●   The length field of an array returns the size of the array. It
     can be used by writing,
       .n
                          arrayName.length
   w
ww




                                                                      22
DF
                    Array Length



                     aP
1   public class ArraySample {
2      public static void main( String[] args ){



                  vi
3         int[] ages = new int[100];
4            ee
5           for( int i=0; i<ages.length; i++ ){
6              System.out.print( ages[i] );
7           }
8       }
        .n
9   }
   w
ww




                                                   23
DF
            Coding Guidelines



                    aP
 1. When creating for loops to process the elements of an


                vi
    array, use the array object's length field in the condition
    statement of the for loop. This will allow the loop to adjust
          ee
    automatically for different-sized arrays.
      .n
 2. Declare the sizes of arrays in a Java program using named
    constants to make them easy to change. For example,
   w


   final int ARRAY_SIZE = 1000; //declare a constant
ww



   . . .
   int[] ages = new int[ARRAY_SIZE];




                                                                    24
DF
        aP
        vi
       ee
   .n

   Multi-Dimensional
   w
ww




         Array
                       25
DF
       Multidimensional Arrays



                    aP
 ●   Multidimensional arrays are implemented as arrays of


                 vi
     arrays.
           ee
 ●   Multidimensional arrays are declared by appending the
     appropriate number of bracket pairs after the array name.
   w   .n
ww




                                                                 26
DF
       Multidimensional Arrays



                    aP
 ●   For example,


                vi
     // integer array 512 x 128 elements
           ee
     int[][] twoD = new int[512][128];

     // character array 8 x 16 x 24
     char[][][] threeD = new char[8][16][24];
       .n

     // String array 4 rows x 2 columns
   w

     String[][] dogs = {{ "terry", "brown" },
                        { "Kristin", "white" },
                        { "toby", "gray"},
ww



                        { "fido", "black"}
                       };




                                                  27
DF
       Multidimensional Arrays



                      aP
 ●   To access an element in a multidimensional array is just the


                  vi
     same as accessing the elements in a one dimensional array.
            ee
 ●   For example, to access the first element in the first row of
     the array dogs, we write,
       .n

        System.out.print( dogs[0][0] );
   w


     This will print the String "terry" on the screen.
ww




                                                                    28
DF
                            Summary



                            aP
 ●   Arrays


                      vi
     –   Definition
              ee
     –   Declaration
     –   Instantiation and constructors (brief overview – to be discussed
         more later)
         .n
     –   Accessing an element
     –   The length field
   w


     –   Multidimensional Arrays
ww




                                                                            29
ww
                           core
      w.
             ne
           evprogramming

     Handling
              iMouse and
               aP
                   DF
      Keyboard Events
                      .c
                         om
1        © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
ww
        Agenda
                      w.
    •
    •
                                    ne
      General event-handling strategy
      Handling events with separate listeners
    •                                        ev
      Handling events by implementing interfaces
    • Handling events with named inner classes
                                               ia
    • Handling events with anonymous inner
      classes                                     PD
    • The standard AWT listener types
    • Subtleties with mouse events                    F.
    • Examples                                               co
                                                                     m
2       Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
    General Strategy
                   w.
                                 ne
    • Determine what type of listener is of interest
       – 11 standard AWT listener types, described on later slide.
                                          ev
              • ActionListener, AdjustmentListener,
                ComponentListener, ContainerListener,
                                            ia
                FocusListener, ItemListener, KeyListener,

                WindowListener
    • Define a class of that type
                                               PD
                MouseListener, MouseMotionListener, TextListener,



                                                    F.
       – Implement interface (KeyListener, MouseListener, etc.)
       – Extend class (KeyAdapter, MouseAdapter, etc.)
    • Register an object of your listener class          co
      with the window
       – w.addXxxListener(new MyListenerClass());
              • E.g., addKeyListener, addMouseListener
                                                                 m
3    Handling Mouse and Keyboard Events       www.corewebprogramming.com
ww Events with a
    Handling
       w.
    Separate Listener: Simple Case
           ne
    • Listener does not need to call any methods
      of the window to which it is attached
               ev
    import java.applet.Applet;

                   ia
    import java.awt.*;

                      PD
    public class ClickReporter extends Applet {
      public void init() {

                          F.
        setBackground(Color.yellow);
        addMouseListener(new ClickListener());

    }
      }
                             co
                                m
4    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww Listener: Simple Case
    Separate
        w.
    (Continued)
           ne
    import java.awt.event.*;


               ev
    public class ClickListener extends MouseAdapter {
      public void mousePressed(MouseEvent event) {

                  ia
        System.out.println("Mouse pressed at (" +
                           event.getX() + "," +

      }              PD    event.getY() + ").");

    }
                        F.
                           co
                              m
5    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww
    Generalizing Simple Case
                   w.
                                 ne
    • What if ClickListener wants to draw a circle
      wherever mouse is clicked?
                                          ev
    • Why can’t it just call getGraphics to get a
      Graphics object with which to draw?
                                            ia
    • General solution:
                                               PD
       – Call event.getSource to obtain a reference to window or
         GUI component from which event originated
       – Cast result to type of interest           F.
       – Call methods on that reference                   co
                                                                  m
6    Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww Events with Separate
    Handling
        w.
    Listener: General Case
           ne
    import java.applet.Applet;

               ev
    import java.awt.*;


                   ia
    public class CircleDrawer1 extends Applet {
      public void init() {

                      PD
        setForeground(Color.blue);
        addMouseListener(new CircleListener());

    }
      }
                          F.
                             co
                                m
7    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww Listener: General
    Separate
       w.
    Case (Continued)
           ne
    import java.applet.Applet;
    import java.awt.*;

               ev
    import java.awt.event.*;



                  ia
    public class CircleListener extends MouseAdapter {
      private int radius = 25;

                     PD
        public void mousePressed(MouseEvent event) {
          Applet app = (Applet)event.getSource();

                        F.
          Graphics g = app.getGraphics();
          g.fillOval(event.getX()-radius,

                           co
                     event.getY()-radius,
                     2*radius,


    }
        }
                     2*radius);
                                                              m
8       Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww Listener: General
    Separate
       w.
    Case (Results)
           ne
              ev
                   ia
                      PD
                         F.
                            co
                                                           m
9    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww 2: Implementing a
     Case
         w.
     Listener Interface
            ne
     import java.applet.Applet;
     import java.awt.*;

                 ev
     import java.awt.event.*;


                     ia
     public class CircleDrawer2 extends Applet
                            implements MouseListener {

                        PD
       private int radius = 25;

       public void init() {
                           F
         setForeground(Color.blue);
         addMouseListener(this);
                                                 .c
       }
                                                        om
10    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww
     Implementing a Listener
          w.
     Interface (Continued)
             ne
         public
         public
                           void
                           void
                                         mouseEntered(MouseEvent event) {}
                                         mouseExited(MouseEvent event) {}
         public
         public  ev        void
                           void
                                         mouseReleased(MouseEvent event) {}
                                         mouseClicked(MouseEvent event) {}

                     ia
                        PD
         public void mousePressed(MouseEvent event) {
           Graphics g = getGraphics();
           g.fillOval(event.getX()-radius,

                           F
                      event.getY()-radius,
                      2*radius,
                      2*radius);                                  .c
     }
         }
                                                                         om
11       Handling Mouse and Keyboard Events                 www.corewebprogramming.com
ww
     Case 3: Named Inner Classes
                    w.
     import java.applet.Applet;
     import java.awt.*;           ne
     import java.awt.event.*;
                                           ev
                                             ia
     public class CircleDrawer3 extends Applet {
       public void init() {
         setForeground(Color.blue);
         addMouseListener(new CircleListener());PD
       }
                                                    F.
                                                           co
                                                                   m
12    Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww Inner Classes
     Named
         w.
     (Continued)
            ne
     • Note: still part of class from previous slide

                ev
         private class CircleListener
                       extends MouseAdapter {

                   ia
           private int radius = 25;


                      PD
              public void mousePressed(MouseEvent event) {
                Graphics g = getGraphics();

                         F
                g.fillOval(event.getX()-radius,
                           event.getY()-radius,
                           2*radius,                .c
         }
              }
                           2*radius);
                                                           om
     }
13       Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww 4: Anonymous Inner
     Case
         w.
     Classes
            ne
     public class CircleDrawer4 extends Applet {
       public void init() {

               ev
         setForeground(Color.blue);
         addMouseListener
           (new MouseAdapter() {

                  ia
              private int radius = 25;


                     PD  public void mousePressed(MouseEvent event) {
                           Graphics g = getGraphics();


                        F. g.fillOval(event.getX()-radius,
                                      event.getY()-radius,


                         }
                           co         2*radius,
                                      2*radius);



     }
         }
                  });
                                                                     m
14       Handling Mouse and Keyboard Events         www.corewebprogramming.com
ww Handling Strategies:
     Event
         w.
     Pros and Cons
            ne
     • Separate Listener
        – Advantages
               ev
               • Can extend adapter and thus ignore unused methods
               • Separate class easier to manage
                   ia
        – Disadvantage
                      PD
               • Need extra step to call methods in main window
     • Main window that implements interface
        – Advantage
                         F.
               • No extra steps needed to call methods in main
                 window
        – Disadvantage
                            co
               • Must implement methods you might not care about
                                                                 m
15    Handling Mouse and Keyboard Events        www.corewebprogramming.com
ww Handling Strategies:
     Event
         w.
     Pros and Cons (Continued)
            ne
     • Named inner class
        – Advantages
               ev
               • Can extend adapter and thus ignore unused methods
               • No extra steps needed to call methods in main
                   ia
                 window
        – Disadvantage
                      PD
               • A bit harder to understand
     • Anonymous inner class
        – Advantages      F.
                             co
               • Same as named inner classes
               • Even shorter
        – Disadvantage
                                m
               • Much harder to understand
16    Handling Mouse and Keyboard Events       www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Summary)
            ne                               Adapter Class

               ev
               Listener
     ActionListener
                                               (If Any)          Registration Method
                                                                addActionListener


                  ia
     AdjustmentListener
     ComponentListener                     ComponentAdapter
                                                                addAdjustmentListener
                                                                addComponentListener

     FocusListener
     ItemListener
                     PD
     ContainerListener                     ContainerAdapter
                                           FocusAdapter
                                                                addContainerListener
                                                                addFocusListener
                                                                addItemListener
     KeyListener
     MouseListener
                        F.                 KeyAdapter
                                           MouseAdapter
                                                                addKeyListener
                                                                addM ouseListener
     MouseMotionListener
     TextListener
     WindowListener        co              MouseMotionAdapter

                                           WindowAdapter
                                                                addM ouseMotionListener
                                                                addTextListener
                                                                addWindowListener

                              m
17    Handling Mouse and Keyboard Events                        www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Details)
             ne
     • ActionListener
        – Handles buttons and a few other actions
                ev
               • actionPerformed(ActionEvent event)
     • AdjustmentListener
                   ia
        – Applies to scrolling
                      PD
               • adjustmentValueChanged(AdjustmentEvent event)
     • ComponentListener

               •         F.
        – Handles moving/resizing/hiding GUI objects
                   componentResized(ComponentEvent event)
               •
               •
                            co
                   componentMoved (ComponentEvent event)
                   componentShown(ComponentEvent event)
               •
                               m
                   componentHidden(ComponentEvent event)

18    Handling Mouse and Keyboard Events       www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Details Continued)
             ne
     • ContainerListener
        – Triggered when window adds/removes GUI controls
                ev
               • componentAdded(ContainerEvent event)
               • componentRemoved(ContainerEvent event)
     • FocusListeneria
                       PD
        – Detects when controls get/lose keyboard focus
               • focusGained(FocusEvent event)

                          F.
               • focusLost(FocusEvent event)


                             co
                                m
19    Handling Mouse and Keyboard Events         www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Details Continued)
             ne
     • ItemListener
        – Handles selections in lists, checkboxes, etc.
                ev
               • itemStateChanged(ItemEvent event)
     • KeyListener
                    ia
        – Detects keyboard events
                       PD
               • keyPressed(KeyEvent event) -- any key pressed
                 down

                          F.
               • keyReleased(KeyEvent event) -- any key released
               • keyTyped(KeyEvent event) -- key for printable char
                   released
                             co
                                m
20    Handling Mouse and Keyboard Events           www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Details Continued)
             ne
     • MouseListener
        – Applies to basic mouse events
               •
               •ev mouseEntered(MouseEvent event)
                   mouseExited(MouseEvent event)
               •
                    ia
                   mousePressed(MouseEvent event)
               •
               •       PD
                   mouseReleased(MouseEvent event)
                   mouseClicked(MouseEvent event) -- Release without
                   drag

                          F.
                     – Applies on release if no movement since press
     • MouseMotionListener
                             co
        – Handles mouse movement

                                m
               • mouseMoved(MouseEvent event)
               • mouseDragged(MouseEvent event)
21    Handling Mouse and Keyboard Events        www.corewebprogramming.com
ww AWT Event Listeners
     Standard
         w.
     (Details Continued)
             ne
     • TextListener
        – Applies to textfields and text areas
                ev
               • textValueChanged(TextEvent event)
     • WindowListener
                    ia
        – Handles high-level window events
                       PD
               • windowOpened, windowClosing, windowClosed,
                 windowIconified, windowDeiconified,

                          F.
                 windowActivated, windowDeactivated
                  – windowClosing particularly useful

                             co
                                m
22    Handling Mouse and Keyboard Events         www.corewebprogramming.com
ww
     Mouse Events: Details
                    w.
                                  ne
     • MouseListener and MouseMotionListener
       share event types
     • Location of clicks                  ev
        – event.getX() and event.getY()
     • Double clicks                         ia
        – Determined by OS, not by programmer
        – Call event.getClickCount()
                                                PD
     • Distinguishing mouse buttons                 F.
        – Call event.getModifiers() and compare to
          MouseEvent.Button2_MASK for a middle click and   co
          MouseEvent.Button3_MASK for right click.
        – Can also trap Shift-click, Alt-click, etc.               m
23    Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww Example: Spelling-
     Simple
         w.
     Correcting Textfield
            ne
     • KeyListener corrects spelling during typing
     • ActionListener completes word on ENTER
                ev
     • FocusListener gives subliminal hints
                   ia
                       PD
                          F.
                             co
                                                            m
24    Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww
      Example: Simple Whiteboard
                     w.
     import java.applet.Applet;
     import java.awt.*;            ne
     import java.awt.event.*;
                                            ev
     public class SimpleWhiteboard extends Applet {
       protected int lastX=0, lastY=0;
                                              ia
       public void init() {
         setBackground(Color.white);             PD
         setForeground(Color.blue);
         addMouseListener(new PositionRecorder());
                                                     F.
       }
         addMouseMotionListener(new LineDrawer());
                                                            co
       protected void record(int x, int y) {

       }
         lastX = x; lastY = y;                                      m
25     Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
     Simple Whiteboard (Continued)
                   w.
                                 ne
     private class PositionRecorder extends MouseAdapter {

                                          ev
       public void mouseEntered(MouseEvent event) {
         requestFocus(); // Plan ahead for typing

       }
         record(event.getX(), event.getY());
                                            ia
                                               PD
         public void mousePressed(MouseEvent event) {
           record(event.getX(), event.getY());

     }
         }
                                                   F.
     ...
                                                          co
                                                                  m
26   Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
         Simple Whiteboard (Continued)
                       w.
         ...                         ne
                                              ev
         private class LineDrawer extends MouseMotionAdapter {
           public void mouseDragged(MouseEvent event) {
             int x = event.getX();
             int y = event.getY();
                                                ia
             Graphics g = getGraphics();
             g.drawLine(lastX, lastY, x, y);
             record(x, y);                         PD
         }
           }
                                                       F.
     }
                                                              co
                                                                      m
27       Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
     Simple Whiteboard (Results)
                   w.
                                 ne
                                          ev
                                            ia
                                               PD
                                                   F.
                                                          co
                                                                  m
28   Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
     Whiteboard: Adding Keyboard
        w.
     Events
            ne
     import java.applet.Applet;
     import java.awt.*;

               ev
     import java.awt.event.*;

     public class Whiteboard extends SimpleWhiteboard {

                   ia
       protected FontMetrics fm;


                      PD
       public void init() {
         super.init();


                         F.
         Font font = new Font("Serif", Font.BOLD, 20);
         setFont(font);


       }
                            co
         fm = getFontMetrics(font);
         addKeyListener(new CharDrawer());


                               m
29     Handling Mouse and Keyboard Events   www.corewebprogramming.com
ww
         Whiteboard (Continued)
                       w.
         ...
                                     ne
         private class CharDrawer extends KeyAdapter {

                                              ev
           // When user types a printable character,
           // draw it and shift position rightwards.


                                                ia
             public void keyTyped(KeyEvent event) {


                                                   PD
               String s = String.valueOf(event.getKeyChar());
               getGraphics().drawString(s, lastX, lastY);
               record(lastX + fm.stringWidth(s), lastY);

         }
             }
                                                       F.
     }
                                                              co
                                                                      m
30       Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
     Whiteboard (Results)
                   w.
                                 ne
                                          ev
                                            ia
                                               PD
                                                   F.
                                                          co
                                                                  m
31   Handling Mouse and Keyboard Events          www.corewebprogramming.com
ww
     Summary
                    w.
     • General strategy
                                  ne
        – Determine what type of listener is of interest
                                           ev
               • Check table of standard types
        – Define a class of that type
                                             ia
               • Extend adapter separately, implement interface,

                 in anonymous inner class        PD
                 extend adapter in named inner class, extend adapter

        – Register an object of your listener class with the window
               • Call addXxxListener                       F.
     • Understanding listeners
        – Methods give specific behavior.                         co
               • Arguments to methods are of type XxxEvent
                      – Methods in MouseEvent of particular interest      m
32    Handling Mouse and Keyboard Events                 www.corewebprogramming.com
ww
                            core
       w.
              ne
                    evprogramming
                       ia
                          PD
                   Questions?
                             F.
                                co
                                                                      m
33        © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
ww
     Preview
                    w.
                                  ne
     • Whiteboard had freehand drawing only
        – Need GUI controls to allow selection of other drawing
          methods
                                           ev
     • Whiteboard had only “temporary” drawing
                                             ia
        – Covering and reexposing window clears drawing
                                                PD
        – After cover multithreading, we’ll see solutions to this
          problem
               • Most general is double buffering
     • Whiteboard was “unshared”                      F.
        – Need network programming capabilities so that two  co
          different whiteboards can communicate with each other
                                                                     m
34    Handling Mouse and Keyboard Events            www.corewebprogramming.com
ww
       w.n
                  ee
                         vi
                           aP
                              DF
           Inheritance



1
DF
                     Agenda




                 aP
  ●   What is and Why Inheritance?
  ●   How to derive a sub-class?


              vi
  ●   Object class
         ee
  ●   Constructor calling chain
  ●   “super” keyword
      .n

  ●   Overriding methods
   w


  ●   Hiding methods
      Hiding fields
ww



  ●


  ●   Type casting
  ●   Final class and final methods
                                      2
DF
        aP
        vi
       ee
   .n
   w


          What is
ww




       Inheritance?
                      3
DF
             What is Inheritance?




                   aP
 ●   Inheritance is the concept of a child class (sub class)


               vi
     automatically inheriting the variables and methods
     defined in its parent class (super class).
           ee
 ●   A primary feature of object-oriented programming
     along with encapsulation and polymorphism
   w   .n
ww




                                                               4
DF
         Why Inheritance? Reusability




                        aP
 ●   Benefits of Inheritance in OOP : Reusability


                    vi
     –   Once a behavior (method) is defined in a super class,
         that behavior is automatically inherited by all subclasses
              ee
          ●   Thus, you write a method only once and it can be used by
              all subclasses.
         .n

     –   Once a set of properties (fields) are defined in a super
         class, the same set of properties are inherited by all
   w


         subclasses
ww



          ●   A class and its children share common set of properties
     –   A subclass only needs to implement the differences
         between itself and the parent.

                                                                         5
DF
          aP
        vi
       ee
   .n
   w


       How to derive a
ww




        sub-class?
                         6
DF
                  extends keyword




                     aP
 ●   To derive a child class, we use the extends keyword.


                 vi
 ●   Suppose we have a parent class called Person.
            ee
     public class Person {
        protected String name;
         .n
        protected String address;

         /**
   w


           * Default constructor
           */
ww



         public Person(){
              System.out.println(“Inside Person:Constructor”);
              name = ""; address = "";
         }
         . . . .
     }
                                                                 7
DF
                 extends keyword




                    aP
 ●    Now, we want to create another class named Student


                vi
 ●    Since a student is also a person, we decide to just
            ee
      extend the class Person, so that we can inherit all the
      properties and methods of the existing class Person.
        .n
 ●    To do this, we write,
   w


     public class Student extends Person {
ww



        public Student(){
           System.out.println(“Inside Student:Constructor”);
        }
        . . . .
     }

                                                               8
DF
     What You Can Do in a Sub-class




                   aP
 ●   A subclass inherits all of the “public” and “protected”


               vi
     members (fields or methods) of its parent, no matter
     what package the subclass is in
           ee
 ●   If the subclass is in the same package as its parent,
     it also inherits the package-private members (fields
       .n

     or methods) of the parent
   w
ww




                                                               9
DF
     What You Can Do in a Sub-class
           Regarding Fields



                   aP
 ●   The inherited fields can be used directly, just like any


               vi
     other fields.
           ee
 ●   You can declare new fields in the subclass that are
     not in the super class
       .n
 ●   You can declare a field in the subclass with the same
     name as the one in the super class, thus hiding it
   w


     (not recommended).
     A subclass does not inherit the private members of
ww



 ●

     its parent class. However, if the super class has
     public or protected methods for accessing its private
     fields, these can also be used by the subclass.
                                                            10
DF
     What You Can Do in a Sub-class
          Regarding Methods



                   aP
 ●   The inherited methods can be used directly as they are.


                vi
 ●   You can write a new instance method in the subclass that
           ee
     has the same signature as the one in the super class,
     thus overriding it.
     You can write a new static method in the subclass that
       .n
 ●

     has the same signature as the one in the super class,
     thus hiding it.
   w


 ●   You can declare new methods in the subclass that are
ww



     not in the super class.



                                                               11
DF
         aP
        vi
       ee
   .n
   w


        Object Class
ww




                       12
DF
                      Object Class




                      aP
 ●   Object class is mother of all classes
     –   In Java language, all classes are sub-classed (extended)
         from the Object super class


                    vi
     –   Object class is the only class that does not have a parent
               ee
         class
 ●   Defines and implements behavior common to all
         .n
     classes including the ones that you write
     –   getClass()
   w


     –   equals()
ww



     –   toString()
     –   ...


                                                                      13
DF
                Class Hierarchy




                 aP
 ●   A sample class hierarchy



              vi
          ee
   w  .n
ww




                                  14
DF
            Super class & Sub class




                      aP
 ●   Super class (Parent class)
         Any class above a specific class in the class hierarchy.


                  vi
     –

 ●   Sub class (Child class)
            ee
     –   Any class below a specific class in the class hierarchy.
   w     .n
ww




                                                                    15
DF
        aP
        vi
       ee
   .n
   w


  Constructor Calling
ww




        Chain
                        16
DF
 How Constructor method of a Super
         class gets called



                      aP
 ●   A subclass constructor invokes the constructor of


                  vi
     the super class implicitly
            ee
     –   When a Student object, a subclass (child class), is
         instantiated, the default constructor of its super class
         (parent class), Person class, is invoked implicitly before
         .n
         sub-class's constructor method is invoked
 ●   A subclass constructor can invoke the constructor
   w


     of the super explicitly by using the “super” keyword
ww



     –   The constructor of the Student class can explicitly invoke
         the constructor of the Person class using “super”
         keyword
     –   Used when passing parameters to the constructor of the
         super class                                                  17
DF
 Example: Constructor Calling Chain




                   aP
 ●   To illustrate this, consider the following code,


                vi
     public static void main( String[] args ){
           ee
        Student anna = new Student();
     }
     In the code, we create an object of class Student.
       .n
 ●

     The output of the program is,
   w


     Inside Person:Constructor
ww



     Inside Student:Constructor




                                                          18
DF
 Example: Constructor Calling Chain




                 aP
 ●   The program flow is shown below.


              vi
          ee
   w   .n
ww




                                        19
DF
        aP
        vi
       ee
   .n
   w


   “super” keyword
ww




                     20
DF
            The “super” keyword




                   aP
 ●   A subclass can also explicitly call a constructor of


               vi
     its immediate super class.
           ee
 ●   This is done by using the super constructor call.
       .n

 ●   A super constructor call in the constructor of a
   w


     subclass will result in the execution of relevant
     constructor from the super class, based on the
ww



     arguments passed.


                                                            21
DF
             The “super” keyword




                   aP
 ●   For example, given our previous example classes


               vi
     Person and Student, we show an example of a
     super constructor call.
          ee
 ●   Given the following code for Student,
       .n

     public Student(){
        super( "SomeName", "SomeAddress" );
   w


        System.out.println("Inside Student:Constructor");
     }
ww




                                                            22
DF
               The “super” keyword




                      aP
 ●   Few things to remember when using the super


                  vi
     constructor call:
            ee
     –   The super() call must occur as the first statement in a
         constructor
     –   The super() call can only be used in a constructor (not in
         .n

         ordinary methods)
   w
ww




                                                                      23
DF
             The “super” keyword




                   aP
 ●   Another use of super is to refer to members of the


               vi
     super class (just like the this reference ).
           ee
 ●   For example,

     public Student() {
       .n
        super.name = “somename”;
        super.address = “some address”;
   w

     }
ww




                                                          24
DF
        aP
        vi
       ee
   .n
   w


  Overriding Methods
ww




                       25
DF
               Overriding methods




                      aP
 ●   If a derived class needs to have a different
     implementation of a certain instance method from


                  vi
     that of the super class, override that instance
     method in the sub class
            ee
     –   Note that the scheme of overriding applies only to
         instance methods
         .n
     –   For static methods, it is called hiding methods
     The overriding method has the same name,
   w

 ●

     number and type of parameters, and return type as
ww



     the method it overrides
 ●   The overriding method can also return a subtype of
     the type returned by the overridden method. This is
     called a covariant return type
                                                              26
DF
      Example: Overriding Methods




                   aP
 ●   Suppose we have the following implementation for


               vi
     the getName method in the Person super class,
           ee
     public class Person {
        :
        :
       .n
        public String getName(){
           System.out.println("Parent: getName");
   w

           return name;
        }
     }
ww




                                                        27
DF
       Example: Overriding Methods




                   aP
 ●   To override the getName method of the super class
     Person in the subclass Student, reimplement the


                vi
     method with the same signature
           ee
     public class Student extends Person{
        :
        public String getName(){
       .n
           System.out.println("Student: getName");
           return name;
        }
   w


        :
     }
ww



 ●   Now, when we invoke the getName method of an
     object of the subclass Student, the getName method of
     the Student would be called, and the output would be,
                 Student: getName
                                                             28
DF
 Modifiers in the Overriding Methods




                      aP
 ●   The access specifier for an overriding method can


                  vi
     allow more, but not less, access than the overridden
     method
            ee
     –   For example, a protected instance method in the super
         class can be made public, but not private, in the subclass.
         .n

 ●   You will get a compile-time error if you attempt to
     change an instance method in the super class to a
   w


     class method in the subclass, and vice versa
ww




                                                                       29
DF
        aP
        vi
       ee
   .n

        Runtime
   w


  Polymorphism with
ww




  Overriding Methods
                       30
DF
            What is Polymorphism?




                     aP
 ●   Polymorphism in a Java program


                 vi
     –   The ability of a reference variable to change
            ee
         behavior according to what object instance it is
         holding.
         This allows multiple objects of different subclasses
         .n
     –
         to be treated as objects of a single super class,
         while automatically selecting the proper methods to
   w


         apply to a particular object based on the subclass it
ww



         belongs to
     –   (We will talk more on Polymorphism during our
         Polymorphism presentation.)

                                                                 31
DF
 Example: Runtime Polymorphism




                aP
 Code:


             vi
      Person person2 = new Student();
           ee
      person2.myMethod("test4");
     .n
      Person person3 = new InternationalStudent();
      person3.myMethod("test5");
   w


 Result:
ww




   myMethod(test4) in Student class is called
   myMethod(test5) in InternationalStudent class is called
                                                       32
DF
         aP
        vi
       ee
   .n
   w


       Hiding Methods
ww




                        33
DF
                 Hiding Methods




                  aP
 ●   If a subclass defines a class method (static method)


               vi
     with the same signature as a class method in the
     super class, the method in the subclass “hides” the
          ee
     one in the super class
   w   .n
ww




                                                            34
DF
 Example: Coding of Hiding Static
            Method



                  aP
  class Animal {


              vi
     public static void testClassMethod() {
       System.out.println("The class method in Animal.");
        ee
     }
  }
    .n

  // The testClassMethod() of the child class hides the one of the
   w

  // super class – it looks like overriding, doesn't it? But
  // there is difference. We will talk about in the following slide.
ww



  class Cat extends Animal {
     public static void testClassMethod() {
       System.out.println("The class method in Cat.");
     }
                                                                  35
  }
DF
Overriding Method vs. Hiding Method




                     aP
 ●   Hiding a static method of a super class looks like


                 vi
     overriding an instance method of a super class
            ee
 ●   The difference comes during runtime
     –   When you override an instance method, you get the benefit
         of run-time polymorphism
         .n

     –   When you override an static method, there is no runt-time
   w


         polymorphism
ww




                                                                     36
DF
Example: Overriding Method vs. Hiding
      Method during Runtime



                   aP
    // Create object instance of Cat.



               vi
    Cat myCat = new Cat();
         ee
    // The object instance is Cat type
    // and assigned to Animal type variable.
    Animal myAnimal2 = myCat;
    .n

    // For static method, the static method of
    // the super class gets called.
   w


    Animal.testClassMethod();
ww



    // For instance method, the instance method
    // of the subclass is called even though
    // myAnimal2 is a super class type. This is
    // run-time polymorphism.
    myAnimal2.testInstanceMethod();
                                                  37
DF
        aP
        vi
       ee
   .n
   w


       Hiding Fields
ww




                       38
DF
                     Hiding Fields




                     aP
 ●   Within a sub class, a field that has the same name as


                 vi
     a field in the super class hides the super class' field,
     even if their types are different
            ee
 ●   Within the subclass, the field in the super class
     cannot be referenced by its simple name
         .n

     –   Instead, the field must be accessed through super keyword
   w


 ●   Generally speaking, hiding fields is not a
     recommended programming practice as it makes
ww



     code difficult to read


                                                                 39
DF
        aP
        vi
       ee
   .n
   w


       Type Casting
ww




                      40
DF
                    What is “Type”?




                      aP
 ●   When an object instance is created from a class, we


                  vi
     say the object instance is “type” of the class and its
     super classes
            ee
 ●   Example:
         .n
          Student student1 = new Student();
     –   student1 object instance is the type of Student or it is
   w


         Student type
     –   student1 object instance is also type of Person if Student is
ww



         a child class of Person
     –   student1 object instance is also type of Object


                                                                     41
DF
              What is Significance?




                      aP
 ●   An object instance of a particular type can be used in


                  vi
     any place where an instance of the type and its super
     type is called for
            ee
 ●   Example:
         .n
     –   student1 object instance is a “type” of TuftsStudent,
         Student, and Peson
   w


     –   student1 object can be used in any place where object
         instance of the type of TuftsStudent, Student, or Person is
ww



         called for
 ●   This enables polymorphism

                                                                       42
DF
                Implicit Type Casting




                        aP
 ●   An object instance of a subclass can be assigned to a


                   vi
     variable (reference) of a parent class through implicit
     type casting – this is safe since an object instance of a
             ee
     subclass “is” also the type of the super class
 ●   Example
          .n

      –   Let's assume Student class is a child class of Person class
   w

      –   Let's assume TuftsStudent class is a child class of Student
          class
ww



      TuftsStudent tuftstudent = new TuftsStudent();
      Student student = tuftsstudent; // Implicit type casting
      Person person = tuftsstudent; // Implicit type casting
      Object object = tuftsstudent; // Implicit type casting
                                                                        43
DF
  Type Casting between Objects




                 aP
              vi
       ee
  tuftsstudent


    student              TuftsStudent
   .n
                       Object instance

    person
   w
ww




                                         44
DF
               Explicit Type Casting




                      aP
 ●   An object instance of a super class must be assigned to


                  vi
     a variable (reference) of a child class through explicit
     type casting
            ee
     –   Not doing it will result in a compile error since the type
         assignment is not safe
         .n

     –   Compiler wants to make sure you know what you are doing
   w

 ●   Example
     –   Let's assume Student class is a child class of Person class
ww



     Person person1 = new Student();
     Student student1 = (Student) person1; // Explicit type casting


                                                                      45
DF
 Runtime Type Mismatch Exception




                     aP
 ●   Even with explicit casting, you could still end up


                 vi
     having a runtime error
            ee
 ●   Example
     –   Let's assume Student class is a child class of Person class
         .n
     –   Let's assume Teacher class is also a child class of Person
         class
   w


     Person person1 = new Student();
ww



     Person person2 = new Teacher();
     Student student1 = (Student) person1; // Explicit type casting
     // No compile error, but runtime type mismatch exception
     Student student2 = (Student) person2;
                                                                      46
DF
     Use instanceof Operator to
Prevent Runtime Type Mismatch Error



                      aP
 ●   You can check the type of the object instance using


                 vi
     instanceof before the type casting
            ee
 ●   Example
     Person person1 = new Student();
         .n
     Person person2 = new Teacher();
   w


     // Do the casting only when the type is verified
ww



     if (person2 instanceof Student) {
         Student student2 = (Student) person2;
     }

                                                           47
DF
         aP
        vi
       ee
   .n
   w


       Final Class &
ww




       Final Method
                       48
DF
                      Final Classes




                      aP
 ●   Final Classes



                  vi
     –   Classes that cannot be extended
     –   To declare final classes, we write,
            ee
            public final ClassName{
               . . .
         .n
            }
 ●   Example:
   w


           public final class Person {
              . . .
ww



           }

 ●   Other examples of final classes are your wrapper
     classes and String class
     –   You cannot create a subclass of String class   49
DF
                        Final Methods




                         aP
●   Final Methods


                     vi
    –   Methods that cannot be overridden
                ee
    –   To declare final methods, we write,
           public final [returnType] [methodName]([parameters]){
              . . .
           .n
           }

    Static methods are automatically final
   w

●
ww




                                                               50
DF
        Example: final Methods




               aP
  public final String getName(){



            vi
     return name;
  }
       ee
   .n
   w
ww




                                   51
DF
        aP
        vi
       ee
        Inheritance
   .n
   w
ww




                      52
DF
          aP
        vi
       ee
       Abstract Class &
   .n

        Java Interface
   w
ww




                          1
DF
                    Agenda




                aP
  ●   What is an Abstract method and an Abstract class?
  ●   What is Interface?


             vi
  ●   Why Interface?
         ee
  ●   Interface as a Type
  ●   Interface vs. Class
      .n

  ●   Defining an Interface
   w


  ●   Implementing an Interface
      Implementing multiple Interface's
ww



  ●


  ●   Inheritance among Interface's
  ●   Interface and Polymorphism
  ●   Rewriting an Interface                          2
DF
        aP
        vi
       ee
   .n
   w


       What is
ww




  an Abstract Class?
                       3
DF
                  Abstract Methods




                    aP
 ●   Methods that do not have implementation (body)


                  vi
 ●   To create an abstract method, just write the method
            ee
     declaration without the body and use the abstract
     keyword
         .n
     –   No { }
   w


 ●   For example,
ww



         // Note that there is no body
         public abstract void someMethod();



                                                           4
DF
                    Abstract Class




                     aP
 ●   An abstract class is a class that contains one or


                 vi
     more abstract methods
            ee
 ●   An abstract class cannot instantiated
     // You will get a compile error on the following code
         .n
     MyAbstractClass a1 = new MyAbstractClass();
 ●   Another class (Concrete class) has to provide
   w


     implementation of abstract methods
ww



     –   Concrete class has to implement all abstract methods of
         the abstract class in order to be used for instantiation
     –   Concrete class uses extends keyword

                                                                    5
DF
            Sample Abstract Class




                   aP
 public abstract class LivingThing {




               vi
    public void breath(){
       System.out.println("Living Thing breathing...");
    }
           ee
     public void eat(){
        System.out.println("Living Thing eating...");
       .n
     }
   w

     /**
      * Abstract method walk()
ww



      * We want this method to be implemented by a
      * Concrete class.
      */
     public abstract void walk();
 }

                                                          6
DF
         Extending an Abstract Class




                    aP
 ●   When a concrete class extends the LivingThing


                vi
     abstract class, it must implement the abstract
     method walk(), or else, that subclass will also
           ee
     become an abstract class, and therefore cannot be
     instantiated.
         .n

     For example,
   w

 ●


     public class Human extends LivingThing {
ww



         public void walk(){
            System.out.println("Human walks...");
         }

     }                                                   7
DF
     When to use Abstract Methods &




                     aP
            Abstract Class?
 ●   Abstract methods are usually declared where two


                 vi
     or more subclasses are expected to fulfill a similar
     role in different ways through different
            ee
     implementations
     –   These subclasses extend the same Abstract class and
         .n

         provide different implementations for the abstract
         methods
   w


 ●   Use abstract classes to define broad types of
ww



     behaviors at the top of an object-oriented
     programming class hierarchy, and use its
     subclasses to provide implementation details of the
     abstract class.
                                                               8
DF
        aP
        vi
       ee
   .n
   w


   What is Interface?
ww




                        9
DF
              What is an Interface?




                      aP
 ●   It defines a standard and public way of specifying


                 vi
     the behavior of classes
            ee
     –   Defines a contract
 ●   All methods of an interface are abstract methods
         .n
     –   Defines the signatures of a set of methods, without the
         body (implementation of the methods)
   w


 ●   A concrete class must implement the interface (all
     the abstract methods of the Interface)
ww



 ●   It allows classes, regardless of their locations in the
     class hierarchy, to implement common behaviors

                                                                   10
DF
            Example: Interface




                 aP
             vi
 // Note that Interface contains just set of method
         ee
 // signatures without any implementations.
 // No need to say abstract modifier for each method
 // since it assumed.
     .n

 public interface Relation {
   w

       public boolean isGreater( Object a, Object b);
       public boolean isLess( Object a, Object b);
ww



       public boolean isEqual( Object a, Object b);
 }



                                                        11
DF
 Example 2: OperatorCar Interface




                  aP
 public interface OperateCar {




              vi
     // constant declarations, if any
          ee
     // method signatures
     int turn(Direction direction,
      .n
         double radius, double startSpeed, double endSpeed);
     int changeLanes(Direction direction, double startSpeed,
                      double endSpeed);
   w

     int signalTurn(Direction direction, boolean signalOn);
     int getRadarFront(double distanceToCar,
ww



                       double speedOfCar);
     int getRadarRear(double distanceToCar,
                       double speedOfCar);
           ......
     // more method signatures
 }
                                                          12
DF
         aP
        vi
       ee
   .n
   w


       Why Interface?
ww




                        13
DF
         Why do we use Interfaces?
                Reason #1




                       aP
 ●   To reveal an object's programming interface


                   vi
     (functionality of the object) without revealing its
     implementation
              ee
     –   This is the concept of encapsulation
         .n
     –   The implementation can change without affecting
         the caller of the interface
   w


     –   The caller does not need the implementation at the
         compile time
ww



          ●   It needs only the interface at the compile time
          ●   During runtime, actual object instance is associated
              with the interface type
                                                                     14
DF
         Why do we use Interfaces?
                Reason #2




                     aP
 ●   To have unrelated classes implement similar


                 vi
     methods (behaviors)
              ee
     –   One class is not a sub-class of another
 ●   Example:
         .n
     –   Class Line and class MyInteger
          ● They are not related through inheritance
   w


          ● You want both to implement comparison methods
ww



              – checkIsGreater(Object x, Object y)
              – checkIsLess(Object x, Object y)
              – checkIsEqual(Object x, Object y)
     –   Define Comparison interface which has the three
         abstract methods above                             15
DF
         Why do we use Interfaces?
                Reason #3




                      aP
 ●   To model multiple inheritance


                  vi
     –   A class can implement multiple interfaces while it can
         extend only one class
            ee
   w     .n
ww




                                                                  16
DF
         Interface vs. Abstract Class




                     aP
 ●   All methods of an Interface are abstract methods


                 vi
     while some methods of an Abstract class are
     abstract methods
            ee
     –   Abstract methods of abstract class have abstract
         modifier
         .n

 ●   An interface can only define constants while
     abstract class can have fields
   w


 ●   Interfaces have no direct inherited relationship with
ww



     any particular class, they are defined independently
     –   Interfaces themselves have inheritance relationship
         among themselves
                                                               17
DF
         aP
        vi
       ee
   .n
   w


       Interface as a
ww




           Type
                        18
DF
               Interface as a Type




                    aP
 ●   When you define a new interface, you are defining a


                vi
     new reference type
           ee
 ●   You can use interface names anywhere you can use
     any other type name
     If you define a reference variable whose type is an
       .n
 ●

     interface, any object you assign to it must be an
     instance of a class that implements the interface
   w
ww




                                                           19
DF
          Example: Interface as a Type




                      aP
 ●   Let's say Person class implements PersonInterface


                  vi
     interface
     You can do
 ●
             ee
      –   Person p1 = new Person();
          .n
      –   PersonInterface pi1 = p1;
      –   PersonInterface pi2 = new Person();
   w
ww




                                                         20
DF
        aP
        vi
       ee
   .n
   w


   Interface vs. Class
ww




                         21
DF
 Interface vs. Class: Commonality




                     aP
 ●   Interfaces and classes are both types


                   vi
     –   This means that an interface can be used in places
         where a class can be used
            ee
     –   For example:
         .n
          // Recommended practice
          PersonInterface     pi = new Person();
   w

          // Not recommended practice
          Person        pc = new Person();
ww



 ●   Interface and Class can both define methods



                                                              22
DF
     Interface vs. Class: Differences




                     aP
 ●   The methods of an Interface are all abstract


                 vi
     methodsee
     –   They cannot have bodies
 ●   You cannot create an instance from an interface
         .n
     –   For example:
          PersonInterface   pi = new PersonInterface(); //ERROR!
   w


 ●   An interface can only be implemented by classes or
     extended by other interfaces
ww




                                                                   23
DF
        aP
        vi
       ee
   .n
   w


   Defining Interface
ww




                        24
DF
              Defining Interfaces




                   aP
 ●   To define an interface, we write:


               vi
           ee
     public interface [InterfaceName] {
           //some methods without the body
         .n
     }
   w
ww




                                             25
DF
               Defining Interfaces




                   aP
 ●   As an example, let's create an interface that defines


               vi
     relationships between two objects according to the
     “natural order” of the objects.
          ee
     public interface Relation {
         .n

         public boolean isGreater( Object a, Object b);
   w

         public boolean isLess( Object a, Object b);
         public boolean isEqual( Object a, Object b);
ww



     }




                                                             26
DF
        aP
        vi
       ee
   .n
   w


       Implementing
ww




         Interface
                      27
DF
             Implementing Interfaces




                       aP
 ●   To create a concrete class that implements an interface,
     use the implements keyword.



                  vi
     /**
      * Line class implements Relation interface
             ee
      */
     public class Line implements Relation {
           private double x1;
        .n
           private double x2;
           private double y1;
           private double y2;
   w


           public Line(double x1, double x2, double y1, double y2){
ww



               this.x1 = x1;
               this.x2 = x2;
               this.y1 = y1;
               this.y2 = y2;
           }

          // More code follows                                        28
DF
           Implementing Interfaces
 public double getLength(){




                     aP
        double length = Math.sqrt((x2-x1)*(x2-x1) +
                       (y2-y1)* (y2-y1));
        return length;
     }




                vi
     public boolean isGreater( Object a, Object b){
         double aLen = ((Line)a).getLength();
          ee
         double bLen = ((Line)b).getLength();
         return (aLen > bLen);
     }
         .n
     public boolean isLess( Object a, Object b){
         double aLen = ((Line)a).getLength();
         double bLen = ((Line)b).getLength();
   w

         return (aLen < bLen);

     }
ww



     public boolean isEqual( Object a, Object b){
         double aLen = ((Line)a).getLength();
         double bLen = ((Line)b).getLength();
         return (aLen == bLen);
     }
 }
                                                      29
DF
           Implementing Interfaces




                   aP
 ●   When your class tries to implement an interface,


               vi
     always make sure that you implement all the
     methods of that interface, or else, you would
          ee
     encounter this error,
       .n

     Line.java:4: Line is not abstract and does not override
   w

       abstract method
       isGreater(java.lang.Object,java.lang.Object) in Relation
ww



     public class Line implements Relation
           ^
     1 error



                                                                  30
DF
              Implementing Class




                  aP
 ●   Implementing class can have its own methods


               vi
 ●   Implementing class extend a single super class or
          ee
     abstract class
   w   .n
ww




                                                         31
DF
        aP
        vi
       ee
   .n
   w


     Implementing
ww




   Multiple Interfaces
                         32
DF
     Relationship of an Interface to a




                     aP
                  Class
 ●   A concrete class can only extend one super class,


                 vi
     but it can implement multiple Interfaces
            ee
     –   The Java programming language does not permit
         multiple inheritance (inheritance is discussed later in
         this lesson), but interfaces provide an alternative.
         .n

 ●   All abstract methods of all interfaces have to be
   w


     implemented by the concrete class
ww




                                                                   33
DF
     Example: Implementing Multiple




                    aP
               Interfaces
 ●   A concrete class extends one super class but


                 vi
     multiple Interfaces:
            ee
     public class ComputerScienceStudent
                    extends Student
         .n
                    implements PersonInterface,
                               AnotherInterface,
   w

                               Thirdinterface{

         // All abstract methods of all interfaces
ww



         // need to be implemented.
     }



                                                     34
DF
        aP
        vi
       ee
   .n
   w


     Inheritance
ww




   Among Interfaces
                      35
DF
      Inheritance Among Interfaces




                   aP
 ●   Interfaces are not part of the class hierarchy


                vi
 ●   However, interfaces can have inheritance
           ee
     relationship among themselves
       .n

     public interface PersonInterface {
        void doSomething();
   w


     }
ww



     public interface StudentInterface
                      extends PersonInterface {
        void doExtraSomething();
     }


                                                      36
DF
         aP
        vi
       ee
   .n
   w


        Interface &
ww




       Polymorphism
                      37
DF
       Interface and Polymorphism




                  aP
 ●   Interfaces exhibit polymorphism as well, since


               vi
     program may call an interface method, and the
     proper version of that method will be executed
          ee
     depending on the type of object instance passed to
     the interface method call
   w   .n
ww




                                                          38
DF
        aP
        vi
       ee
   .n
   w


  Rewriting Interfaces
ww




                         39
DF
      Problem of Rewriting an Existing
                 Interface




                     aP
 ●   Consider an interface that you have developed called DoIt:
          public interface DoIt {


                 vi
            void doSomething(int i, double x);
            int doSomethingElse(String s);
            ee
          }
 ●   Suppose that, at a later time, you want to add a third method to
     DoIt, so that the interface now becomes:
       .n

           public interface DoIt {
   w

             void doSomething(int i, double x);
             int doSomethingElse(String s);
ww



             boolean didItWork(int i, double x, String s);
           }
 ●   If you make this change, all classes that implement the old DoIt
     interface will break because they don't implement all methods of
     the the interface anymore
                                                                   40
DF
      Solution of Rewriting an Existing
                  Interface




                   aP
 ●   Create more interfaces later
 ●   For example, you could create a DoItPlus interface that


               vi
     extends DoIt:
          ee
     public interface DoItPlus extends DoIt {
       boolean didItWork(int i, double x, String s);
     }
       .n

 ●   Now users of your code can choose to continue to use
     the old interface or to upgrade to the new interface
   w
ww




                                                         41
DF
        aP
        vi
       ee
   .n

    When to Use an
   w


  Abstract Class over
ww




     an Interface?
                        42
DF
     When to use an Abstract Class
            over Interface?




                     aP
 ●   For non-abstract methods, you want to use them


                 vi
     when you want to provide common implementation
     code for all sub-classes
            ee
     –   Reducing the duplication
         .n
 ●   For abstract methods, the motivation is the same
     with the ones in the interface – to impose a
   w


     common behavior for all sub-classes without
     dictating how to implement it
ww



 ●   Remember a concrete can extend only one super
     class whether that super class is in the form of
     concrete class or abstract class
                                                        43
DF
          aP
        vi
       ee
       Abstract Class &
   .n

        Java Interface
   w
ww




                          44
DF
          aP
        vi
       ee
       Java I/O Stream
   .n
   w
ww




                         1
DF
                      Topics




                aP
  ●   What is an I/O stream?


             vi
  ●   Types of Streams
  ●   Stream class hierarchy
        ee
  ●   Control flow of an I/O operation using Streams
      Byte streams
      .n
  ●

  ●   Character streams
   w


  ●   Buffered streams
      Standard I/O streams
ww



  ●

  ●   Data streams
  ●   Object streams
  ●   File class
                                                       2
DF
         aP
        vi
       ee
   .n
   w


       What is an I/O
ww




         Stream?
                        3
DF
                       I/O Streams




                     aP
 ●   An I/O Stream represents an input source or an


                 vi
     output destination
            ee
 ●   A stream can represent many different kinds of
     sources and destinations
         .n
     –   disk files, devices, other programs, a network
         socket, and memory arrays
   w


 ●   Streams support many different kinds of data
ww



     –   simple bytes, primitive data types, localized
         characters, and objects
 ●   Some streams simply pass on data; others
     manipulate and transform the data in useful ways.
                                                          4
DF
                      I/O Streams




                    aP
 ●   No matter how they work internally, all streams


                vi
     present the same simple model to programs that
     use them
            ee
     –   A stream is a sequence of data
   w     .n
ww




                                                       5
DF
                   Input Stream




                  aP
 ●   A program uses an input stream to read data from


              vi
     a source, one item at a time
          ee
   w   .n
ww




                                                              6
                                        source:java.sun.com
DF
                  Output Stream




                  aP
 ●   A program uses an output stream to write data to a


               vi
     destination, one item at time
          ee
   w   .n
ww




                                                          7
DF
        aP
        vi
       ee
   .n
   w


   Types of Streams
ww




                      8
DF
             General Stream Types




                    aP
 ●   Character and Byte Streams


                vi
     –   Character vs. Byte
            ee
 ●   Input and Output Streams
     –   Based on source or destination
         .n

 ●   Node and Filter Streams
   w


     –   Whether the data on a stream is manipulated or
         transformed or not
ww




                                                          9
DF
         Character and Byte Streams




                       aP
 ●   Byte streams
     –   For binary data


                   vi
     –   Root classes for byte streams:
              ee
          ●   The InputStream Class
          ●   The OutputStream Class
         .n
          ●   Both classes are abstract
 ●   Character streams
   w


     –   For Unicode characters
ww



     –   Root classes for character streams:
          ●   The Reader class
          ●   The Writer class
          ●   Both classes are abstract        10
DF
              Input and Output Streams




                      aP
 ●   Input or source streams


                   vi
     –   Can read from these streams
     –   Root classes of all input streams:
              ee
          ●   The InputStream Class
              The Reader Class
         .n
          ●


 ●   Output or sink (destination) streams
   w


     –   Can write to these streams
ww



     –   Root classes of all output streams:
          ●   The OutputStream Class
          ●   The Writer Class

                                               11
DF
            Node and Filter Streams




                     aP
 ●   Node streams (Data sink stream)


                 vi
     –   Contain the basic functionality of reading or writing
         from a specific location
            ee
     –   Types of node streams include files, memory and
         pipes
         .n

 ●   Filter streams (Processing stream)
   w


     –   Layered onto node streams between threads or
         processes
ww



     –   For additional functionality- altering or managing
         data in the stream
 ●   Adding layers to a node stream is called stream
     chaining                                                    12
DF
        aP
        vi
       ee
   .n
   w


       Stream Class
ww




        Hierarchy
                      13
DF
 Streams
 InputStream




                aP
               vi
 OutputStream
          ee
     .n
 Reader
   w


 Writer
ww




                      14
DF
               Abstract Classes




                 aP
 ●   InputStream & OutputStream


              vi
 ●   Reader & Writer
          ee
   w  .n
ww




                                  15
DF
   InputStream Abstract Class




         aP
        vi
       ee
   .n
   w
ww




                                16
DF
   InputStream Abstract Class




         aP
        vi
       ee
   .n
   w
ww




                                17
DF
   Node InputStream Classes




        aP
        vi
       ee
   .n
   w
ww




                              18
DF
   Filter InputStream Classes




         aP
        vi
       ee
   .n
   w
ww




                                19
DF
   OutputStream Abstract Class




          aP
        vi
       ee
   .n
   w
ww




                                 20
DF
   Node OutputStream Classes




         aP
        vi
       ee
   .n
   w
ww




                               21
DF
   Filter OutputStream Classes




         aP
        vi
       ee
   .n
   w
ww




                                 22
DF
   The Reader Class: Methods




         aP
        vi
       ee
   .n
   w
ww




                               23
DF
   The Reader Class: Methods




         aP
        vi
       ee
   .n
   w
ww




                               24
DF
       Node Reader Classes




          aP
        vi
       ee
   .n
   w
ww




                             25
DF
       Filter Reader Classes




          aP
        vi
       ee
   .n
   w
ww




                               26
DF
   The Writer Class: Methods




        aP
        vi
       ee
   .n
   w
ww




                               27
DF
       Node Writer Classes




         aP
        vi
       ee
   .n
   w
ww




                             28
DF
       Filter Writer Classes




          aP
        vi
       ee
   .n
   w
ww




                               29
DF
        aP
        vi
       ee
   .n

     Control Flow of
   w


  I/O Operation using
ww




       Streams
                        30
DF
   Control Flow of an I/O operation




                aP
 Create a stream object and associate it with a data-


             vi
   source (data-destination)
        ee
 Give the stream object the desired functionality
   through stream chaining
     .n
 while (there is more information)
    read(write) next data from(to) the stream
   w


 close the stream
ww




                                                        31
DF
         aP
        vi
       ee
   .n
   w


        Byte Stream
ww




                      32
DF
                     Byte Stream




                    aP
 ●   Programs use byte streams to perform input and


                vi
     output of 8-bit bytes
            ee
 ●   All byte stream classes are descended from
     InputStream and OutputStream
         .n
 ●   There are many byte stream classes
     –   FileInputStream and FileOutputStream
   w


 ●   They are used in much the same way; they differ
ww



     mainly in the way they are constructed



                                                       33
DF
     When Not to Use Byte Streams?




                     aP
 ●   Byte Stream represents a kind of low-level I/O that


                 vi
     you should avoid
            ee
     –   If the data contains character data, the best
         approach is to use character streams
         .n
     –   There are also streams for more complicated data
         types
   w


 ●   Byte streams should only be used for the most
     primitive I/O
ww



 ●   All other streams are based on byte stream


                                                            34
DF
       Example: FileInputStream &




                     aP
           FileOutputStream
 public class CopyBytes {


               vi
   public static void main(String[] args) throws IOException {
      FileInputStream in = null;
          ee
      FileOutputStream out = null;
      try {
         in = new FileInputStream("xanadu.txt");
      .n

         out = new FileOutputStream("outagain.txt");
         int c;
   w


        while ((c = in.read()) != -1) {
ww



          out.write(c);
        }
      }
      // More code
                                                                 35
DF
          Example: FileInputStream &




                         aP
              FileOutputStream
         finally {


                    vi
            if (in != null) {
                in.close();
            }
              ee
            if (out != null) {
                out.close();
         .n

            }
         }
   w


     }
 }
ww




                                       36
DF
  Simple Byte Stream input and




         aP
             output


        vi
       ee
   .n
   w
ww




                                 37
DF
        aP
        vi
       ee
   .n
   w


   Character Stream
ww




                      38
DF
                  Character Stream




                     aP
 ●   The Java platform stores character values using


                 vi
     Unicode conventions
            ee
 ●   Character stream I/O automatically translates this
     internal format to and from the local character set.
         .n
     –   In Western locales, the local character set is usually
         an 8-bit superset of ASCII.
   w


 ●   All character stream classes are descended from
     Reader and Writer
ww



 ●   As with byte streams, there are character stream
     classes that specialize in file I/O: FileReader and
     FileWriter.
                                                                  39
DF
                  Character Stream




                    aP
 ●   For most applications, I/O with character streams is
     no more complicated than I/O with byte streams.


                vi
     –   Input and output done with stream classes
         automatically translates to and from the local
           ee
         character set.
     –   A program that uses character streams in place of
      .n

         byte streams automatically adapts to the local
         character set and is ready for internationalization —
   w


         all without extra effort by the programmer.
ww



     –   If internationalization isn't a priority, you can simply
         use the character stream classes without paying
         much attention to character set issues.
     –   Later, if internationalization becomes a priority, your
         program can be adapted without extensive recoding. 40
DF
  Example: FileReader & FileWriter




                     aP
 public class CopyCharacters {


               vi
   public static void main(String[] args) throws IOException {
      FileReader inputStream = null;
          ee
      FileWriter outputStream = null;

      try {
      .n

         inputStream = new FileReader("xanadu.txt");
         outputStream = new FileWriter("characteroutput.txt");
   w


        int c;
ww



        while ((c = inputStream.read()) != -1) {
           outputStream.write(c);
        }
      }
      // More code                                               41
DF
     Example: FileReader & FileWriter




                       aP
         finally {


                   vi
            if (inputStream != null) {
                inputStream.close();
            }
             ee
            if (outputStream != null) {
                outputStream.close();
         .n

            }
         }
   w


     }
 }
ww




                                          42
DF
 Character Stream and Byte Stream




                    aP
 ●   Character streams are often "wrappers" for byte


                vi
     streamsee
 ●   The character stream uses the byte stream to
     perform the physical I/O, while the character stream
     handles translation between characters and bytes.
         .n

     –   FileReader, for example, uses FileInputStream,
   w


         while FileWriter uses FileOutputStream
ww




                                                            43
DF
                  Line-Oriented I/O




                    aP
 ●   Character I/O usually occurs in bigger units than


                vi
     single characters
            ee
      – One common unit is the line: a string of
        characters with a line terminator at the end
         .n
     –   A line terminator can be a carriage-return/line-
         feed sequence ("rn"), a single carriage-return
   w


         ("r"), or a single line-feed ("n").
ww




                                                            44
DF
  Example: Line-oriented I/O




                  aP
   File inputFile = new File("farrago.txt");
   File outputFile = new File("outagain.txt");


             vi
   FileReader in = new FileReader(inputFile);
       ee
   FileWriter out = new FileWriter(outputFile);

   BufferedReader inputStream = new BufferedReader(in);
   .n

   PrintWriter outputStream = new PrintWriter(out);
   w


   String l;
   while ((l = inputStream.readLine()) != null) {
ww



      System.out.println(l);
      outputStream.println(l);
   }

   in.close();                                            45
   out.close();
DF
          aP
        vi
       ee
   .n
   w


       Buffered Stream
ww




                         46
DF
            Why Buffered Streams?




                    aP
 ●   An unbuffered I/O means each read or write
     request is handled directly by the underlying OS


                 vi
     –   This can make a program much less efficient, since
         each such request often triggers disk access,
            ee
         network activity, or some other operation that is
         relatively expensive.
         .n
 ●   To reduce this kind of overhead, the Java platform
     implements buffered I/O streams
   w


     –   Buffered input streams read data from a memory
ww



         area known as a buffer; the native input API is called
         only when the buffer is empty
     –   Similarly, buffered output streams write data to a
         buffer, and the native output API is called only when
         the buffer is full.                                      47
DF
     How to create Buffered Streams?




                         aP
 ●   A program can convert a unbuffered stream into a


                   vi
     buffered stream using the wrapping idiom
              ee
     –   A unbuffered stream object is passed to the constructor
         for a buffered stream class
          .n
 ●   Example
         inputStream =
   w


           new BufferedReader(new FileReader("xanadu.txt"));
ww



         outputStream =
           new BufferedWriter(new FileWriter("characteroutput.txt"));


                                                                        48
DF
          Buffered Stream Classes




                  aP
 ●   BufferedInputStream and BufferedOutputStream


              vi
     create buffered byte streams
          ee
 ●   BufferedReader and BufferedWriter create buffered
     character streams
   w   .n
ww




                                                         49
DF
           Flushing Buffered Streams




                     aP
 ●   It often makes sense to write out a buffer at critical


                  vi
     points, without waiting for it to fill. This is known as
     flushing the buffer.
             ee
 ●   Some buffered output classes support autoflush,
     specified by an optional constructor argument.
          .n

      –   When autoflush is enabled, certain key events cause
          the buffer to be flushed
   w


      –   For example, an autoflush PrintWriter object flushes
ww



          the buffer on every invocation of println or format.
 ●   To flush a stream manually, invoke its flush method
      –   The flush method is valid on any output stream, but
          has no effect unless the stream is buffered.           50
DF
        aP
        vi
       ee
   .n
   w


   Standard Streams
ww




                      51
DF
 Standard Streams on Java Platform




                    aP
 ●   Three standard streams


                vi
     –   Standard Input, accessed through System.in
            ee
     –   Standard Output, accessed through System.out
     –   Standard Error, accessed through System.err
         .n

 ●   These objects are defined automatically and do not
     need to be opened
   w


 ●   System.out and System.err are defined as
ww



     PrintStream objects



                                                          52
DF
        aP
        vi
       ee
   .n
   w


       Data Streams
ww




                      53
DF
                   Data Streams




                  aP
 ●   Data streams support binary I/O of primitive data


               vi
     type values (boolean, char, byte, short, int, long,
     float, and double) as well as String values
          ee
 ●   All data streams implement either the DataInput
     interface or the DataOutput interface
       .n

 ●   DataInputStream and DataOutputStream are most
   w


     widely-used implementations of these interfaces
ww




                                                           54
DF
                 DataOutputStream




                     aP
●   DataOutputStream can only be created as a wrapper


                 vi
    for an existing byte stream object
       out = new DataOutputStream(
           ee
              new BufferedOutputStream(
              new FileOutputStream(dataFile)));
        .n

       for (int i = 0; i < prices.length; i ++) {
   w


          out.writeDouble(prices[i]);
          out.writeInt(units[i]);
ww



          out.writeUTF(descs[i]);
       }

                                                        55
DF
                    DataInputStream




                      aP
 ●   Like DataOutputStream, DataInputStream must be
     constructed as a wrapper for a byte stream


                  vi
 ●   End-of-file condition is detected by catching
     EOFException, instead of testing for an invalid return
                ee
     value
         in = new DataInputStream(
         .n
              new BufferedInputStream(
              new FileInputStream(dataFile)));
   w


         try{
ww



             double price = in.readDouble();
             int unit = in.readInt();
             String desc = in.readUTF();
         } catch (EOFException e){
         }
                                                              56
DF
         aP
        vi
       ee
   .n
   w


       Object Streams
ww




                        57
DF
                   Object Streams




                    aP
 ●   Object streams support I/O of objects


                 vi
     –   Like Data streams support I/O of primitive data types
            ee
     –   The object has to be Serializable type
 ●   The object stream classes are ObjectInputStream
         .n
     and ObjectOutputStream
     –   These classes implement ObjectInput and
   w


         ObjectOutput, which are subinterfaces of DataInput
ww



         and DataOutput
     –   An object stream can contain a mixture of primitive
         and object values

                                                                 58
DF
         Input and Output of Complex




                     aP
                    Object
 ●   The writeObject and readObject methods are


                 vi
     simple to use, but they contain some very
     sophisticated object management logic
            ee
     –   This isn't important for a class like Calendar, which
         just encapsulates primitive values. But many objects
         .n

         contain references to other objects.
   w

 ●   If readObject is to reconstitute an object from a
     stream, it has to be able to reconstitute all of the
ww



     objects the original object referred to.
     –   These additional objects might have their own
         references, and so on.
                                                                 59
DF
                    WriteObject




                  aP
 ●   The writeObject traverses the entire web of object


               vi
     references and writes all objects in that web onto
     the stream
          ee
 ●   A single invocation of writeObject can cause a large
     number of objects to be written to the stream.
   w   .n
ww




                                                            60
DF
     I/O of multiple referred-to objects




                  aP
 ●   Object a contains references to objects b and c,


               vi
     while b contains references to d and e
          ee
   w   .n
ww




                                                        61
DF
     I/O of multiple referred-to objects




                   aP
 ●   Invoking writeObject(a) writes not just a, but all the


                vi
     objects necessary to reconstitute a, so the other
     four objects in this web are written also
           ee
 ●   When a is read back by readObject, the other four
     objects are read back as well, and all the original
       .n

     object references are preserved.
   w
ww




                                                              62
DF
          aP
        vi
       ee
   .n
   w


       Closing Streams
ww




                         63
DF
              Always Close Streams




                    aP
 ●   Closing a stream when it's no longer needed is very


                 vi
     important — so important that your program should
     use a finally block to guarantee that both streams
            ee
     will be closed even if an error occurs
     –   This practice helps avoid serious resource leaks.
   w     .n
ww




                                                             64
ww
        w          .n
                     ee
                          vi
                            aP
                               DF
      File Class

65
DF
                   The File Class




                   aP
 ●   Not a stream class


               vi
 ●   Important since stream classes manipulate File
           ee
     objects
 ●   Abstract representation of actual files and directory
       .n
     pathname
   w
ww




                                                             66
DF
       The File Class: Constructors




                  aP
 ●   Has four constructors


               vi
          ee
   w   .n
ww




                                      67
DF
       The File Class: Methods




           aP
         vi
       ee
   .n
   w
ww




                                 68
DF
       The File Class: Methods




           aP
         vi
       ee
   .n
   w
ww




                                 69
DF
            The File Class: Example




                       aP
 1    import java.io.*;




                vi
 2

      public class FileInfoClass {
 3
            ee
 4       public static void main(String args[]) {
 5          String fileName = args[0];
        .n

 6          File fn = new File(fileName);
   w

 7          System.out.println("Name: " + fn.getName());
 8          if (!fn.exists()) {
ww



 9             System.out.println(fileName
 10                               + " does not exists.");
 11   //continued...

                                                            70
DF
       The File Class: Example




              aP
 12    /* Create a temporary directory instead. */




           vi
 13    System.out.println("Creating temp directory...");
       fileName = "temp";
 14
       ee
 15    fn = new File(fileName);
 16    fn.mkdir();
      .n

 17    System.out.println(fileName +
   w

 18        (fn.exists()? "exists": "does not exist"));
 19    System.out.println("Deleting temp directory...");
ww



 20    fn.delete();
 21    //continued...



                                                         71
DF
            The File Class: Example




                       aP
 24




                    vi
 25         System.out.println(fileName + " is a " +
                        (fn.isFile()? "file." :"directory."));
 26
            ee
 27

 28         if (fn.isDirectory()) {
        .n

 29             String content[] = fn.list();
   w

 30             System.out.println("The content of this directory:
 43             for (int i = 0; i < content.length; i++) {
ww



 44                 System.out.println(content[i]);
 45             }
 46         }
 35
                                                             72
 36   //continued...
DF
            The File Class: Example




                       aP
 36




                 vi
 37

            if (!fn.canRead()) {
 38
            ee
 39             System.out.println(fileName
 40                                + " is not readable.");
        .n

 41             return;
   w

 42         }
 43   //continued...
ww




                                                             73
DF
              The File Class: Example




                       aP
 47           System.out.println(fileName + " is " + fn.length()




                   vi
 48                              + " bytes long.");
              System.out.println(fileName + " is " +
 49
              ee
 50                         fn.lastModified() + " bytes long.");
 51
          .n

 52           if (!fn.canWrite()) {
   w

 53               System.out.println(fileName
 54                                   + " is not writable.");
ww



 55           }
 56       }
 57   }

                                                                74
DF
              Modified InputStream/




                       aP
              OutputStream Example
 24           } catch (IOException ie) {




                   vi
 25               ie.printStackTrace();
 26           }
              ee
 27       }
 28
          .n
 29       public static void main(String args[]) {
 30           String inputFile = args[0];
   w


 31           CopyFile cf = new CopyFile();
ww



 32           cf.copy(inputFile);
 33       }
 34   }


                                                     75
ww
        w.n
                  ee
                         vi
                           aP
                              DF
            Thank You!



76
References




                                          om
   1. Java 2: The Complete Reference, Patrick Naughton
   and Herbert Schildt, Tata McGraw Hill, 1999. Rs 395.




                                     .c
   2. Programming with Java, 2nd Edition,
   E. Balagurusamy, Tata McGraw Hill, 1998, reprint,
   2000. Rs 170.




                            DF
   3. The Java Tutorial, 2nd ed., 2 volumes,Mary
   Campione and Kathy Walrath, Addison Wesley
   Longmans, 1998. Latest version available online at
                     aP
   java.sun.com. Download free. Book: Rs 630 (Vol. 1)
   and Rs 395 (Vol. 2).

   4. Core Java 2, 2 volumes, Cay S. Horstmann, Gary
                vi

   Cornell, The Sun Microsystems Press, 1999, Indian
   reprint 2000. Rs 450 (Vol. 1) and Rs 495 (Vol. 2).
         ee


   5. Using Java 2
   Joseph L. Weber
   Prentice Hall, Eastern Economy Edition, 2000. Rs 499.
      n




   6. The Java Language Specification, 2nd ed, James
   w.




   Gosling, Bill Joy, Guy Steele & Gilad Bracha, (1st ed
   1996, 2nd ed 2000), Sun Microsystems, 2000.
ww
Notes




                                           om
     •     Basic familiarity will be assumed with
              – C and C++
              – OOP




                                       .c
              – Internet and WWW

     •     Note: Please do whatever is necessary to justify




                              DF
           these assumptions!
                      aP
                 vi
      n    ee
   w.
ww




   CKR                    Java Notes                          2
Java: Prehistory




                                           om
     •    Development 1: C++
             – C++ (or “C with Classes”) was invented
                 in 1979, and became the stock




                                      .c
                 programming language in the 90’s.
                 (Standardized in Nov. 1997.)




                             DF
             –    What were the reasons for its success?

             –    Lesson: C++ very successful, since it
                  enhanced an existing successful
                      aP
                  language like C.

             –    (instead of building an entirely new
                  programming language).
                 vi

     •    Development 2: GUI
         ee


             –    Object orientation permits reusable
                  code, hence a Graphical User interface
                  GUI (E.g. MS-Windows).
      n




             –    GUI has enormously expanded the
   w.




                  number of computer-users.

             –    Lesson: Object oriented programming
ww




                  (OOP) with GUI is the “grand consensus
                  of the computer industry”.



   CKR                   Java Notes                        3
Java: Prehistory (contd.)




                                           om
     •    Development 3: Internet

              –   Internet stared in the 1960’s as a way to




                                       .c
                  maintain communications in the event of
                  a nuclear attack.




                               DF
              –   Success of ARPANET inspired NSFNET.

              –   In 1983, TCP/IP became the official
                  protocol which connected ARPANET and
                      aP
                  NSFNET.

              –   This collection of connected networks
                  came to be called the Internet.
                  vi

              –   By 1990, 3000 networks and 200,000
                  computers were connected to the
          ee


                  Internet. By 1992, there were 1 million
                  hosts.
      n



              –   The hosts had diverse hardware and
                  operating systems like DOS/Windows,
   w.




                  UNIX, and MacOS.

              –   Problem: How to share information easily
ww




                  across different computer platforms?




   CKR                    Java Notes                        4
Java: Prehistory (contd.)




                                          om
     •    Development 4: WWW

              –   To simplify sharing of documents and




                                       .c
                  data across the Internet, WWW invented
                  in 1989 at CERN, Geneva, for
                  high-energy physicists.




                               DF
              –   WWW is an architectural framework for
                  viewing documents stored across
                  thousands of machines connected to
                      aP
                  the Internet.

              –   The scattered document seems like a
                  single document using a browser to view
                  vi

                  hypertext, which contains hyperlinks.

              –   However, this concerned passive text or
          ee


                  document files, and users on the www
                  could not share executable programs.
      n



              –   Problem: How to incorporate interactive
                  programs on the Web? How to share
   w.




                  executable programs across platforms?
ww




   CKR                    Java Notes                        5
Java: History




                                           om
     •    In 1990, Sun Microsystems started a project
          called Green.




                                       .c
             –     Objective: to develop software for
                   consumer electronics.




                              DF
             –     Sun best known for its popular Unix
                   workstation, Solaris OS, and Network
                   File System (NFS).
                      aP
             –     Project was assigned to James Gosling,
                   a veteran of classic network software
                   design.
                   vi

             –     Others included Patrick Naughton, Chris
                   Warth, Ed Frank, and Mike Sheridan.
         ee


     •    The team started writing programs in C++ for
          embedding into
      n



             –     toasters
             –     washing machines
   w.




             –     VCR’s
             –     PDA’s (Personal Digital Assistants)
ww




     •    Aim was to make these appliances more
          “intelligent”. But they soon realized...



   CKR                    Java Notes                        6
Java: History (contd.)




                                          om
      •   C++ is powerful, but also dangerous.

              –   The power and popularity of C derived




                                         .c
                  from the extensive use of pointers.

              –   However, any incorrect use of pointers




                               DF
                  can cause memory leaks, leading the
                  program to crash.

              –   In a complex program, such memory
                      aP
                  leaks are often hard to detect.

      •   Robustness is essential
                  vi

              –   Users have come to expect that
                  Windows may crash or that a program
                  running under Windows may crash.
          ee


                  (“This program has performed an illegal
                  operation and will be shut down”)
      n



              –   However, users do not expect toasters to
                  crash, or washing machines to crash.
   w.




              –   A design for consumer electronics has
                  to be robust. Replacing pointers by
ww




                  references, and automating memory
                  management was the proposed solution.



   CKR                      Java Notes                      7
Java: History (contd.)




                                           om
      •   Oak: Hence, the team built a new programming
          language called Oak, which




                                         .c
              –   avoided potentially dangerous
                  constructs in C++, such as pointers,
                  pointer arithmetic, operator overloading




                               DF
                  etc.

              –   introduced automatic memory
                  management, freeing the programmer to
                      aP
                  concentrate on other things.

      •   Architecture neutrality (Platform independence)
                  vi

              –   Many different CPU’s are used as
                  controllers. Hardware chips are evolving
                  rapidly. As better chips become
          ee


                  available, older chips become obsolete
                  and their production is stopped.
      n



              –   Manufacturers of toasters and washing
                  machines would like to use the chips
   w.




                  available off the shelf, and would not like
                  to reinvest in compiler development
                  every two-three years.
ww




              –   So, the software and programming
                  language had to be architecture neutral.


   CKR                      Java Notes                       8
Java: History (contd)




                                         om
    •    It was soon realized that these design goals of
         consumer electronics perfectly suited an ideal
         programming language for the Internet and




                                     .c
         WWW, which should be:
             – object-oriented (& support GUI)
             – robust




                            DF
             – architecture neutral

    •    Internet programming presented a BIG business
         opportunity. Much bigger than programming for
                    aP
         consumer electronics.
             – Java was “re-targeted” for the Internet

    •    The team was expanded to include Bill Joy
               vi

         (developer of Unix), Arthur van Hoff, Jonathan
         Payne, Frank Yellin, Tim Lindholm etc.
         ee


    •    In 1994, an early web browser called WebRunner
         was written in Oak. WebRunner was later
         renamed HotJava.
      n




    •    In 1995, Oak was renamed Java.
   w.




             – A common story is that the name Java
                  relates to the place from where the
                  development team got its coffee.
ww




             – The name Java survived the trade mark
                  search.



   CKR                  Java Notes                         9
Java Features




                                            om
     •   Additional features were added to make Java
            – secure
            – multithreaded (concurrent)




                                        .c
            – distributed and dynamic
            – high performance




                              DF
     •   Security: Is a key feature on the Internet. It
         should be possible to specify what system
         resources the program can access.
            – In the sandbox policy remote applets are
                      aP
                 not trusted to access any local
                 resources,

             –     while local applications are trusted to
                 vi

                   access all resources.

             –     This can be modified, by allowing
         ee


                   digitally signed applets selective access.

     •   Multiple threads: C and C++ support multiple
      n



         threads, using fork(),
             – this feature is NOT a part of the ANSI/ISO
   w.




                 standard, and is available only on UNIX.

             –     DOS support is available for the spawn...
ww




                   and exec... family of functions. These
                   features are not much used.



   CKR                     Java Notes                        10
–    But concurrency is essential on the




                                          om
                 internet, since download times are
                 uncertain, so one process should not
                 block all others.

            –    Threads also needed for e.g. animation.




                                     .c
    •    Distributed:




                            DF
             – The ultimate vision of OOP is to have
                 objects stored on different computers to
                 interact with each other. That is, a user
                 can assemble a program different parts
                    aP
                 of which are stored on different
                 computers.

    •    Dynamic:
                vi

            – Java is both compiled and interpreted.

            –    Thus, source code is compiled to
         ee


                 bytecode.

            –    The Java Virtual Machine loads and links
      n



                 parts of the code dynamically at run
                 time.
   w.




            –    Hence it carries substantial run time type
                 information on objects.
ww




            –    Hence, It supports late binding.



   CKR                  Java Notes                       11
•    High performance




                                        om
            – Though Java uses an interpreter,

            –   it also has a compiler, which generates
                machine-independent bytecodes.




                                    .c
            –   Optimization can take place at this stage
                to ensure that Java programs can match




                           DF
                the speed of programs in compiled
                languages like C++.

            –   Where speed cannot be traded off for
                   aP
                platform independence, Java provides
                “native method support”, for code
                written in languages like C/C++, and
                compiled for specific platforms.
                vi
      n  ee
   w.
ww




   CKR                 Java Notes                         12
Java Features: Summary




                                        om
     •   Simple

     •   Secure




                                        .c
     •   Portable




                              DF
     •   Object-oriented

     •   Robust
                       aP
     •   Multithreaded

     •   Architecture-neutral
               vi

     •   Interpreted

     •   High-performance
         ee


     •   Distributed
      n



     •   Dynamic
   w.
ww




   CKR                     Java Notes        13
Comparison of Java and other languages by Gosling




                                        om
                                     .c
                           DF
                    aP
               vi
      n  ee
   w.




    Fig. 1: From the Java Language Environment White
ww




   CKR                  Java Notes                     14
The JDK




                                          om
     •   The JDK is the Java Development Kit. Major
         versions are 1.1 (Java 1) and 1.2 (Java 2).
         (Version 1.3 has just been released.)




                                     .c
     •   This can be downloaded free of cost from
         http://java.sun.com




                            DF
     •   The JDK can be downloaded for different
         platforms: Windows, Unix (Solaris), MacOS.
                    aP
     •   Requires support for
            – long file names, and
            – case-sensitive file names.
                 vi

     •   Hence, will not run in DOS. (Limited platform
         independence.)
         ee


     •   Hardware and Software requirements:

             –   Win 95/Win NT4.0 or higher running on
      n



                 x86 (min. 486/8MB). Little disk space
                 (~ 40 MB).
   w.




             –   Solaris 2.4 or higher on SPARC
ww




             –   Solaris 2.5 or higher on x86.




   CKR                  Java Notes                       15
•    Comes as a self-extracting exe for Win95+, which




                                         om
         extracts to c:jdk1.2 directory.

    •    Certain environment variables, such as PATH
         and CLASSPATH need to be set/reset.




                                     .c
            –   Path must be set to include
                c:jdk1.2bin




                           DF
            –   If upgrading, if CLASSPATH set to
                classes.zip, this should be removed.
                    aP
            –   Setting the CLASSPATH variable is
                optional:
                set CLASSPATH= .;c:mydirmyclass.jar;.
                myclasses.zip
                vi

            –   There should be no space around =
         ee


            –   The preferred method is to use the
                -classpath option with each jdk tool.
      n



            –   This is preferred since applications may
                run differently depending upon the
   w.




                classpath.

            –   More about CLASSPATH when we study
ww




                packages.




   CKR                  Java Notes                      16
JDK Utilities




                                             om
      •   The following are some of the important utilities
          available under jdk.
      •   javac




                                        .c
              – The java compiler, converts source code
                  into bytecode stored in class files.




                               DF
      •   java
              –     The java interpreter that executes
                    bytecode for a java application from class
                    files.
                       aP
      •   appletviewer
             – The java interpreter that executes
                  bytecode for a java applet from class
                    vi

                  files.

      •   javadoc
          ee


              – Creates HTML documentation based on
                  java source code, and the documentation
                  comments it contains.
      n




      •   jdb
   w.




                –   The java debugger. Allows one to step
                    through the program one line at a time,
                    set breakpoints, and examine variables.
ww




      •   javah
              –     Generates C/C+ header files for
                    combining with native methods.


   CKR                     Java Notes                       17
Using the JDK: Hello World Application




                                            om
     •    Step 1: Enter the Java source code:
             – Use any non-document text editor, or a
                  simple Integrated Development




                                      .c
                  Environment, like Kawa to type the
                  following program.
    Program 1




                            DF
   /**
   * The HelloWorld class implements an
   * application that simply displays
   * “Hello World!” to the
                     aP
   * standard output (console)
   */
   public class HelloWorld
   {
                 vi

   public static void main (String args[])
       {
       //required prototype for main function
         ee


       System.out.println(“Hello world!”);
       }
   }
      n



      •   Step 2: Save the source in a file:
   w.




             –   The file MUST have the same name as
                 the public class in the source, and must
                 have a .java extension. (Hence, support
ww




                 for long filenames is required.)




   CKR                   Java Notes                     18
–    That is, the above file should be saved




                                           om
                 as
                 HelloWorld.java
                 with the case maintained.

            –    Note: A java source file cannot contain




                                      .c
                 more than one public class according to
                 the above restriction.




                             DF
    •    Step 3: Compile the source file using javac:

            –    use the following command line at the
                    aP
                 shell prompt

                 javac HelloWorld.java
                vi

            –    If the code is correct, compilation will
                 produce the file
         ee


                 HelloWorld.class

            –    if there are errors, repeat steps 1-3.
      n




            –    To see what javac does behind the
   w.




                 scenes, use the following command line

                 javac -verbose HelloWorld.java
ww




   CKR                   Java Notes                         19
Using the jdk: Hello World Application (contd.)




                                           om
     •    Step 4: Run the compiled code.
             – Invoke the java interpreter by the
                  command line




                                       .c
                  java HelloWorld




                             DF
              –   Output: Hello World!

     •    Congratulations! You have successfully run your
          first java program.
                      aP
     •    Note: 1. No file extension is needed when
          invoking the interpreter.
          2. To view execution details of the compiled
                  vi

          code, use the command line

          java    -prof HelloWorld
          ee


          This will generate a profile which shows
      n



              –   methods called in order of decreasing
                  frequency.
   w.




              –   how memory is used.
ww




              –   list of variable types and bytes
                  necessary to store them.



   CKR                    Java Notes                      20
Anatomy of the HelloWorld program




                                         om
     •   New style comments:

             –   The first line of the HelloWorld program




                                       .c
                 shows a new style comment.

             –   This is a documentation comment which




                             DF
                 begins with /** and ends with */

             –   This is in addition to the C-style
                 comments between /* and */ and the
                    aP
                 additional C++ style comments between
                 // and the end of the line.

     •   Using javadoc:
                 vi

             –   The new style comments are used to
                 generate source code documentation.
         ee


             –   To generate this documentation, use the
                 command line
      n




                 javadoc HelloWorld.java
   w.




             –   javadoc ignores old-style comments.
ww




             –   it generates four html documents:
                 packages.html, HelloWorld.html,
                 AllNames.html, tree.html.


   CKR                    Java Notes                     21
Anatomy of the HelloWorld Program




                                          om
     •   Stripped of comments, this is the HelloWorld
         program:
   public class HelloWorld




                                      .c
   {
      public static void main (String args[])
      {




                            DF
         System.out.println(“Hello world!”);
      }
   }
     •   The first line declares a class. public is an
                    aP
         access specifier for the class.

             –   Note that the main function of C/C++ is
                 put inside a class in Java.
                 vi

     •   Thus, Java is completely object oriented.
         ee


             –   All methods including the main method
                 (function) are inside classes.
      n



             –   The main method continues to be the
                 entry point.
   w.




             –   Every Java application MUST have a
                 main method declared as above.
ww




             –   This is NOT required for java applets.



   CKR                   Java Notes                       22
Anatomy of the HelloWorld program (contd)




                                        om
     •   Note the prototype of the main method

   public static void main (String args[])




                                     .c
     •   For the main method
            – public is the access specifier.




                           DF
            – static is the storage class.
            – void is the return type.
            – String args[] is an array of strings
                 similar to int argc, char *argv[] of
                    aP
                 C/C++.

     •   These declarations are mandatory.
            – Thus the following declaration will not
               vi

                work.
   public static void main()
         ee


     •  We can check this out by writing a small
        program.
   Program 2
      n




   /** class NoMain has an incorrectly defined
   w.




   * main function. This class will compile
   * correctly, but will not execute.
   * The interpreter will say
ww




   * In class NoMain: void main (String
   argv[]) is not defined*/



   CKR                  Java Notes                      23
om
   public class NoMain
   {
      public static void main()
      {
         System.out.println (“This program will not




                                     .c
   run”);
      }




                           DF
   }

     •   Why does this happen?
                   aP
            –   Several methods called main can be
                defined, in a java class.

            –   The interpreter will look for a main
                vi

                method with the prescribed signature as
                the entry point.
         ee


            –   A method named main, which has some
                other signature is of no particular
                significance. It is like any other method
      n



                in the class
   w.




            –   Therefore, if the main method is not
                declared correctly, the application will
                not execute.
ww




   CKR                  Java Notes                         24
A Java program with two main methods




                                          om
     •   The following is an example of a java program
         with two main methods with different signatures.




                                     .c
    Program 3
   public class TwoMains
   {




                           DF
   /** This class has two main methods with
   * different signatures */

   public static void main (String args[])
                    aP
      {
        //required prototype for main method
        System.out.println(“Hello world!”);
        int i;
               vi

        i = main(2);
        System.out.println (“i = ” + i );
      }
         ee


   /**This is the additional main method*/
   public static int main(int i)
      {
      n



        return i*i;
      }
   w.




   }

     •   Output:
ww




         Hello World!
         i = 4



   CKR                  Java Notes                     25
Anatomy of the Hello World Program (contd.)




                                            om
     •    The argument to the mandatory main function

   public static void main (String args[])




                                         .c
   which is
   String args []




                               DF
   can also be written as

   String [] args
                       aP
     •    Any other name can be used in place of args,
          such as argv or argument.

     •    This represents the string of command line
                    vi

          parameters, as in C/C++,

     •    But
         ee


                –   There is no need for argc, since an array
                    in Java always knows how many
                    elements it has.
      n




                – args[0] is NOT the name of the
   w.




                  program itself, but the first parameter on
                  the command line.
     •    The last line refers to the println method of the
ww




          out variable (representing the standard output
          stream) of the System class.



   CKR                      Java Notes                     26
Command line arguments




                                       om
     •    We can test the above considerations by means
          of a small program.
    Program 4




                                    .c
   public class CommandLine
   {
       public static void main (String argv [])




                            DF
       {
          int length = argv.length;
          String myString = “No. of parameters”r
                 + “ on the command line: ”;
                    aP
          System.out.println (myString + length);
          for (int i=0; i length; i++)
             {
                 myString = argv[i];
               vi

                 System.out.println
                 (i + “: ” + myString);
             }
         ee


       }
   }
      •   Input: java CommandLine Java is a good
      n



          language.
   w.




     •   Output: No of parameters on the command line: 5
         0: Java
         1: is
ww




         2: a
         3: good
         4: language.


   CKR                 Java Notes                    27
Debugging a program




                                            om
     •   Sometimes the program compiles but does not
         work as intended.




                                      .c
     •   In this situation the java debugger can be used.
             – to generate full debugging info use the
                  -g option with javac




                            DF
     •   The debugger is invoked as follows.

         jdb HelloWorld
                       aP
     •   To set a breakpoint, use the command

         stop in HelloWorld.main
                vi

         followed by
         run
         ee


     •   When the breakpoint is hit, type
         list
      n



         to see the code.
   w.




     •   Type
         clear HelloWorld.main
         followed by
ww




     •   cont



   CKR                   Java Notes                         28
ww




CKR
                w.
                   nee
                       vi
                         aP




Java Notes
                            DF
                                 .c
                                      om


29
ww




CKR
                w.
                   nee
                       vi
                         aP




Java Notes
                            DF
                                 .c
                                      om


30
Summary




                                          om
     •   We have used the following utilities of JDK

             –   javac (compiler)




                                      .c
             –   java (interpreter)
             –   javadoc (for extracting documentation
                 comments)




                            DF
             –   jdb (debugger)

     •   We have learnt to write a basic application in
         Java, to compile it, and run it.
                    aP
     •   Every java application must have a main method

             –   This main method is defined inside a
                 vi

                 class.

             –   It must have the prescribed signature.
         ee



     •   Note: A main method is NOT required for java
      n



         applets.
   w.




     •   Java is completely object oriented. No residue
         from structured programming.
            – The main method is inside a class
ww




            – class declarations need no semicolon.
            – Everything must be inside some class!



   CKR                   Java Notes                       31
Elements of Programming style:




                                          om
     •   Java is a free-form language, and white space
         may be used almost anywhere in a Java
         program.




                                      .c
            – However indentation helps humans to
                 understand the program.




                            DF
             –   Hence we will use appropriate
                 indentation.

     •   Also, object-oriented programming involves a
                     aP
         profusion of names, hence names must be
         chosen systematically.

             –   Thus, class names begin with capital
                 vi

                 letters by convention.

             –   method and variable names begin with
         ee


                 lowercase letters by convention.

     •   If the name involves more than one word,
      n



         mixed-capitalization is used to indicate the
         beginning of the word for a method, and
   w.




         underscore for a variable. E.g.
              –   myMethod
              – my_variable
ww




     •   Constants are in all capitals: e.g. PI
     •   Provide ample documentation.



   CKR                   Java Notes                      32
Program 5




                                 om
   public class FreeForm
   {
   public
      static
         void




                                 .c
            main
               (




                       DF
                 String
                   args
                    []
               )
                 aP
      { //required prototype for main method
      System
      .
      out
             vi

      .
      println
      (
         ee


      “ Java is a ”
      +
      “free-form language!”
      n



      //strings must still be terminated
      //before end of line.
   w.




      //They must be concatenated using +
      // and not merely by whitespace.
      )
ww




      ;
      }}



   CKR              Java Notes                 33
A program with three classes




                                          om
     •    There can be more than one class within a file,
          and a program may appeal to any number of
          classes.




                                      .c
    Program 6
   In file Point.java:




                             DF
   public class Point
   { float x;
      float y;
      public void setXY (float x0, float y0)
                     aP
      {
         x = x0;
         y = y0;
      }
                vi

      public float getX ()
      {
         return x;
         ee


      }
      public float getY ()
      {
      n



         return y;
      }
   w.




   }

   class Line
ww




   {
      Point a = new Point();
      Point b = new Point();


   CKR                   Java Notes                         34
public float length ()




                                        om
      {
        float temp1, temp2;
        temp1 = (a.getX()-b.getX());
        temp1 *= temp1;
        temp2 = (a.getY()- b.getY());




                                     .c
        temp2 *= temp2;
        return (float) Math.sqrt




                           DF
   ((double)temp1+temp2);
      }
   }
                    aP
     •   In file PointLine.java:
   public class PointLine
   {
      public static void main (String args[])
               vi

      {
         Line myLine = new Line();
         myLine.a.setXY (0.0f, 0.0f);
         ee


         myLine.b.setXY (1.0f, 0.0f);
         System.out.println (
         “length of myLine = ”+
      n



             myLine.length() );
      }
   w.




   }
     •   After compiling both files, use the command
         java PointLIne
ww




     •   Output: Length of myLine = 1



   CKR                  Java Notes                 35
Hello World Applet




                                             om
     •    Java programs are commonly of two types

             –    Applications




                                        .c
             –    Applets

     •    A piglet is to a pig as an applet is to an




                              DF
          application.

     •    Applications are stand-alone Java programs.
                        aP
     •    Applets are programs that require a browser to
          run. Applets are typically downloaded from the
          Internet and run in an applet window within a
          browser.
                 vi

     •    Since download times are uncertain, an applet is
          intended to be a relatively small program.
         ee


     •    But there is no inherent limitation to the size of
          an applet, and they can be as complex as one
      n



          wants.
   w.




     •    Applets get their parameters not from the
          command line but from the web page within
          which they run.
ww




   CKR                     Java Notes                          36
Hello World Applet (contd.)




                                           om
     •    Unlike applications, applets do not utilise a main
          method. Instead they use the following methods.




                                       .c
             –    public void init(): Initializes the
                  applet. Called only once.




                             DF
             –    public void start(): called when the
                  browser is ready to run the applet.

             –    public void stop(): called when the
                     aP
                  browser wishes to stop the applet, or the
                  user leaves the web page, or the browser
                  is iconified.
                 vi

             –    public void destroy(): called when
                  the browser clears the applet out of
                  memory.
         ee


             –    public void paint (Graphics g):
                  called whenever the browser needs to
      n



                  redraw the applet.
   w.




     •    Applets get their parameters using the
          String getParameter(String Param_name)
          method.
ww




   CKR                    Java Notes                      37
Hello World Applet (contd.)




                                           om
     •    Step 1: Write the source code: For the
          HelloWorld Applet, create a java source file as
          follows.




                                        .c
    Program 7
   import java.awt.*;




                             DF
   public class HelloWorldApplet extends
   java.applet.Applet
   {
      public void paint (Graphics screen)
                      aP
      {
         screen.drawString (“Hello World Applet!”,
              50, 25);
      }
                vi

   }

     •    Step 2: Compile the source file using javac.
         ee


     •    Step 3: Create a minimal html file as follows.
      n



   <applet code = “HelloWorldApplet.class”
   height = 100 width = 300> </applet>
   w.




     •    and save it as CallApp.html
ww




     •   Step 4: Viewing the applet in appletviewer: Run
         appletviewer by
   appletviewer CallApp.html


   CKR                    Java Notes                        38
HelloWorld Applet (contd.)




                                           om
     •    Step 4: Preparing to viewing the applet in a
          browser: Wrap the above html code within any
          desired html code, e.g.




                                       .c
   <HTML>
   <HEAD>




                                DF
   <TITLE>Hello World Applet</TITLE>
   </HEAD>
   <BODY>
   This is what my applet does:
                     aP
   <applet code = “HelloWorldApplet.class”
   height = 100 width = 300>
   </applet>
                 vi

   </BODY>
   </HTML>
   Save the code in a file: myfile.html
         ee


     •    Step 5: Open the above html file using any
          java-enabled browser.
      n



              – E.g. use “Open page” on Netscape
                  Navigator
   w.




             –    the applet will automatically run in the
                  assigned area.
ww




   CKR                    Java Notes                         39
Anatomy of the HelloWorldApplet applet




                                          om
     •   The first line in the HelloWorldApplet program is

   import java.awt.*;




                                      .c
     •   The import statement is an instruction to the
         compiler to help resolve class names.




                            DF
             –   An import statement helps to refer to the
                 classes in the java.awt package by their
                 short names.
                    aP
             –   Thus to refer to the Graphics class, we
                 now use the statement
                 vi

   public void paint (Graphics screen)
     •   Without the import statement, we would have to
         use the fully qualified name:
         ee


   public void paint (
        java.awt.Graphics screen           )
      n



       •   Similarly, if we used the statement
   import java.applet.Applet
   w.




       •   the second line of the program could be
           abbreviated to
   public class HelloWorldApplet extends
ww




   Applet
   i.e., we could refer to java.applet.Applet simply
   as Applet.


   CKR                   Java Notes                        40
Anatomy of the HelloWorldApplet applet (contd.)




                                          om
     •    The HelloWorldApplet does not use the init(),
          start(), stop(), or destroy() methods.
              – It uses only the paint method.




                                       .c
              – The paint method takes a Graphics
                    object as an argument.
              – The Graphics class is part of the




                             DF
                    Abstract Windows Toolkit (awt) package.

     •    The declaration
   public void paint (Graphics screen)
                     aP
   says that the Graphics object will be referred by the
   name screen within the paint method.
              – “screen” is only an identifier, and can be
                  replaced by any other identifier, such as
                  vi

                  “g”.

              –   Since the graphics class woks in the
         ee


                  graphics mode (as in classic C), the
                  preferred method is to draws strings
                  rather than perform console output.
      n




            – The instruction
   w.




   screen.drawString (“Hello World Applet!”,
   50, 25);
            – means that the string is to be drawn at
ww




               pixels x=50, y=25, relative to the applet
               window, measured from the top left hand
               corner of the applet window.


   CKR                    Java Notes                     41
Anatomy of the HelloWorldApplet applet (contd.)




                                             om
     •    As observed before, an applet cannot run on its
          own, and must run within a browser.
             – Hence the applet code must be




                                        .c
                 supplemented with HTML code.

     •   The minimum HTNL code that is needed for




                              DF
         appletviewer is the following.
   <applet code = “HelloWorldApplet.class”
   height = 100 width = 300> </applet>
                      aP
     •    The HTML syntax is self-explanatory: it says that
          the applet with the given class file name should
          be displayed in a window of the given height and
          width in pixels.
                 vi

     •    The exact positioning of the window will be
          decided by the browser and any other HTML
         ee


          commands such as ALIGN.

     •    if the applet class file is not in the same directory
      n



          as the web page, then use the syntax
   w.




          CODEBASE= URL

     •    with the URL or path of the directory where the
ww




          applet class file is located.




   CKR                     Java Notes                        42
Anatomy of the HelloWorldApplet (contd.)




                                           om
     •    Unlike applications which take command line
          parameters, applets get their parameters using
             – The <PARAM,> tag in the HTML code




                                       .c
             – The getParameter method in the applet
                  code.




                               DF
     •    The <PARAM> tag has the syntax

   <PARAM NAME="parameter-name"
   VALUE="parameter-value">
                      aP
     •   The getParameter method has the prototype
   String getParameter(String parameter_name)
                vi

     •    E.g. below shows how two parameters are
          obtained by the applet. (Note the capitalization.)
         ee


   Program 8

     •    Code in HTML file:
      n




   <applet code = GetParam.class height = 100
   w.




   width = 100>
   <param name = Name value = “Myname”>
   <param name = class value = “myclass”>
ww




   </applet>




   CKR                    Java Notes                       43
•   Code in file GetParameter.java




                                   om
   import java.awt.*;
   import java.applet.Applet;
   public class GetParam extends Applet
   {
      String s1, s2;




                                   .c
      public void init()
      {




                         DF
         s1 = getParameter (“NAme”)
         s2 = getParameter (“class”);
      }
                  aP
       public void paint(Graphics screen)
       {
          if (s1 != null)
             screen.drawString (s1, 50, 100);
              vi

          else
             screen.drawString (“No Name”, 50, 100);
          if (s2 != null)
           ee


             screen.drawString (s2, 50, 200);
          else
             screen.drawString (“No Class”, 50, 200);
      n




       }
   w.




   }
ww




   CKR                Java Notes              44
General Applets




                                         om
     •   The Hello World applet used only the paint
         method.




                                     .c
     •   The Get Parameter applet used only the init and
         the paint methods.




                            DF
     •   The other methods of an applet are always
         called, and a default implementation is provided.

     •   To see how they are called, we can use the
                     aP
         following applet code.

     •   The code also shows how applets may use the
         console, although they usually don’t for obvious
               vi

         reasons.

     •  To see the output when the applet is running in a
         ee


        browser use the Java Console window of the
        browser.
   Program 9
      n




   import java.awt.*;
   w.




   import java.applet.Applet;
   public class TestApplet extends Applet
   {
ww




      static int countInit=0;
      static int countStart=0;
      static int countStop=0;


   CKR                  Java Notes                      45
static int countPaint=0;




                                  om
     static int countDestroy=0;

     public void init()
     {
         System.out.println (“Init = ” +




                                 .c
             (++countInit));
     }




                       DF
     public void start()
     {
        System.out.println (“Start = ” +
                aP
        (++countStart));
        repaint();
     }
            vi

     public void stop()
     {
        System.out.println (“Stop = ” +
         ee


           (++countStop));
        repaint();
     }
      n




     public void paint (Graphics screen)
   w.




     {
        System.out.println (“Paint = ” +
           (++countPaint));
ww




        /*repaint();//recursive call to paint*/
     }



   CKR              Java Notes              46
public void destroy()




                                   om
       {
          System.out.println (“Destroy =” +
             (++countDestroy));
          repaint();
       }




                                   .c
   }




                         DF
                  aP
              vi
      n  ee
   w.
ww




   CKR                Java Notes              47
Summary




                                         om
     •   There are two common types of Java programs.
            – Applications
            – Applets




                                     .c
     •   Applications use the main method, applets don’t.




                            DF
     •   Applications are stand-alone, while applets run
         within a browser.

     •   Applets are inherently graphical. (However, they
                    aP
         can use console i/o).

     •   From the point of view of the language, both
         applications and applets are the same..
               vi

     •   Applications can avoid graphics and use only
         console i/o, so they are faster, and more
         ee


         convenient in a development environment.

     •   Hence, we will study the language using
      n



         primarily applications.
   w.
ww




   CKR                  Java Notes                         48
How Java works




                                           om
     •   Java is two things
            – Java Platform
            – Java language




                                      .c
     •   Computer world today has many platforms
           – MicroSoft windows




                             DF
           – Unix
           – Macintosh
           – OS/2
           – NetWare
                     aP
     •   Software must be compiled separately for each
         platform. The binary files for an application that
         runs on one platform cannot run on another
               vi

         platform, since they are machine specific.

     •   The Java Platform is a software platform that
         ee


            – sits on top of the other platforms
            – The Java compiler compiles source files
                (.java files) to bytecodes (.class files).
      n



            – these bytecodes are not specific to any
                machine.
   w.




            – they are instructions for the Java Virtual
                Machine.
            – Hence exactly the same file can run on
ww




                any machine on which the Java Platform
                is present.



   CKR                   Java Notes                           49
The Java Platform




                                          om
     •   Each underlying computer platform has its own
         implementation of the Java Virtual Machine.




                                     .c
     •   But there is only one virtual machine
         specification.




                            DF
     •   Hence Java is able to provide the “Write Once,
         Run Anywhere” capability.

             –   This capability is very important today,
                       aP
                 because of the diverse machines
                 connected to the Internet. (E.g. Adobe
                 PDF format documents.)
                 vi

             –   It is also important because of the high
                 costs of software development makes it
                 desirable to reuse code as easily as
         ee


                 possible.

     •   The Java Platform consists of
      n




             –   The Java Virtual Machine, and
   w.




             –   The java API (Application programmer
                 interface/ class files).
ww




     •   The Java Base Platform consists of the JVM and
         a minimum set of API known as Base API.



   CKR                  Java Notes                          50
The Java Virtual Machine




                                          om
     •   The Java Virtual machine is a ‘soft machine’
            – a piece of software compiled for different
                platforms.




                                      .c
     •   The JVM behaves like a real machine in that
            – it has an instruction set




                              DF
            – it manipulates various memory areas at
                run time.
            – similar to the P-Code machine of UCSD
                Pascal (which was not such a success
                     aP
                because “University people know
                nothing of marketing.”)

     •   “The Java Virtual Machine knows nothing of the
                vi

         Java Language” (Tim Lindholm and Frank Yellin
         The Java Virtual Machine Specifications)
         ee


     •   The Java Virtual Machine understands only a
         particular binary format known as the class file
         format.
      n




     •   The class file format contains
   w.




            – JVM instructions or bytecodes
            – a symbol table and other ancillary info.
ww




     •   In principle, the JVM can run the instructions
         from any language which can be compiled into
         the class file format.


   CKR                   Java Notes                         51
The Java Virtual Machine (contd.)




                                           om
     •    The Java Virtual Machine starts execution by
             – invoking the method main of some
                 specified class




                                       .c
             – passing to it a single argument which is
                 an array of strings.




                             DF
     •    This causes that class to be
             – loaded
             – linked to other types it uses, and
             – Initialised
                     aP
     •    The loading process is implemented by the class
          ClassLoader or its subclasses.
             – Different subclasses may implement
                vi

                  different loading policies, e.g. pre-fetch
                  based on expected usage, load a related
                  group of classes etc.
         ee


             – This may not be transparent to the
                  running application. E.g. a newly
                  compiled version of a class is not loaded
      n



                  because a previously compiled version
                  is cached.
   w.




             – Responsibility of class loader to reflect
                  errors only when they could have arisen
                  without prefetching or group loading.
ww




   CKR                    Java Notes                      52
The Java Virtual Machine (contd.)




                                            om
     •    Linking is the process of taking the binary form of
          a class type or an interface type, and combining
          it into the run time state of the JVM so that it can




                                       .c
          be executed.
               – A class or interface is always loaded
                    before it is linked.




                              DF
     •    Linking involves
             – verification
             – preparation, and
                      aP
             –     resolution of symbolic references

     •    Depending upon implementation, symbolic
          references may be resolved
                vi

              – individually, when needed (lazy or late
                  resolution)
              – collectively when the class is loaded
         ee


                  (static resolution)

     •    Verification ensures that the binary representation
      n



          of a class or interface is structurally correct.
              – E.g. that every instruction has a valid
   w.




                    operation code.

     •    Preparation
ww




             – involves creating the static fields and
                  intializing them to their default values.



   CKR                    Java Notes                          53
Java Virtual Machine: Limitation




                                            om
     •    Despite all the hype, the Java Virtual machine
          has certain limitations.




                                       .c
     •    The number of dimensions in an array is limited
          to 255..




                              DF
     •    The number of method parameters is limited to
          255 9with long and double counted as 2
          parameters).
                      aP
     •    The number of fields in a class is limited to 64K
          (65535). (This does not include inherited fields.)

     •    The number of methods in a class is limited to
                vi

          64K. (Does not include inherited methods. )

     •    The amount of code per (non-native,
         ee


          non-abstract) method is limited to 64K bytes.

     •    For more details: consult The JVM Specifications
      n



          by Lindholm and Yellin.
   w.
ww




   CKR                    Java Notes                       54
Java Virtual Machine limitations (Example Program)




                                          om
     •    The Java virtual Machine can also run out of
          memory. Here is an example.




                                      .c
     •    The array size may have to be adjusted for
          different machines.




                             DF
    Program 10
   class BigArray
   {
      public static void main(String args[])
                     aP
      {
         double myArray[];
         myArray = new double [256*256*256];
         for (int i=0; i<=256*256*256; i++)
                vi

         {
            myArray[i] = (double)i;
            System.out.println (i+ “th element = ” +
         ee


               myArray[i]);
         }
      }
      n



   }
   w.




     •    Expected output:
          Java.lang.OutOfMemoryError at
          BigArray.main(BigArray.java:6)
ww




   CKR                   Java Notes                      55
The Java API




                                              om
     •   The Java API provide a standard interface of
         ready made code that a programmer can rely
         upon, irrespective of the platform.




                                        .c
     •   The Base API provide the language (java.lang),
         utility (java.util), i/o (java.io), network (java.net),




                               DF
         gui (java.awt), and applet (java.applet) services.

     •   The Standard Extension API provide various
         other services.
                      aP
     •   Naturally, the classification will change with time.
                  vi
      n  ee
   w.
ww




         Fig. 2: The Java Platform is the same for all
                           systems


   CKR                     Java Notes                              56
The Java Environment




                                         om
     •   The Java development environment includes
         both Java compile time and run-time
         environment.




                                       .c
     •   The developers source code (.java files) are
         converted to bytecodes (.class files).
     •   In the case of applets the bytecodes are




                             DF
         downloaded.
     •   Once in the JVM, these are interpreted by the
         Interpreter or optionally turned into machine
         code by a Just in Time (JIT) code generator,
                    aP
         popularly called a JIT compiler.
     •   The Java Runtime Environment is provided
         separately, for those who merely wish to run
         Java applicatoins, but do not wishh to compile
               vi

         them.
      n  ee
   w.
ww




             Fig. 3: The Java Compile and Runtime
                          Environment


   CKR                    Java Notes                      57
Identifiers and Unicode




                                             om
     •    A legal identifier in Java is a finite sequence of
          characters.




                                        .c
     •    Java programs (v. 1.1.7 upwards) may use
          Unicode character encoding (v. 2.1) as specified
          in




                              DF
     •    The Unicode Standard Version 2.0
          ISBN 0-201-48345-9
                      aP
     •    Unicode only for identifiers, and the contents of
          characters and string literals, and comments.

     •    Everything else must be in ASCII.
                 vi

     •    The unicode character set uses 16 bit encoding,
          to try to represent characters from various
         ee


          languages (currently some 24 languages).

             –    Of the 65536 possible characters, 49194
      n



                  have been assigned.
   w.




             –    The first 256 of these are the standard
                  ASCII character set.
ww




             –    Supports Japanese, Greek, Russian,
                  Hebrew etc.



   CKR                     Java Notes                          58
•    Indian scripts supported include:




                                          om
             – Devnagari
             – Bengali
             – Gujarati
             – Gurmukhi
             – Malayalam




                                     .c
             – Tamil
             – Oriya




                            DF
             – Telegu
             – Kannada

    •    A unicode character may be represented within a
                    aP
         string by uhhhh, where h are the hex digits.

            –    E.g. “u0043" is the ASCII character C.
                vi

            –    For more information on Unicode consult
                 http://www.unicode.org
      n  ee
   w.
ww




   CKR                  Java Notes                         59
Data types




                                             om
     •   Three kinds of datatypes in Java.
            – primitive data types




                                         .c
                –   reference data types

                –   the special null data type, also the type




                               DF
                    of the expression null.

     •   The null reference is the only possible value of
         an expression of null type, and can always be
                       aP
         converted to any reference type.

                –   In practice, the null type can be ignored,
                    and one can pretend that null is just a
                    vi

                    special kind of literal.

                –   i.e. if(obj != null) always makes sense.
         ee


     •   Java datatypes are NOT machine-dependent.
      n



     •   The Java datatypes are defined as part of the
         language, as follows.
   w.




     •   Apart from the primitive data types, (and the null
         data type) everything else is an object or a
ww




         reference datatype in Java.




   CKR                      Java Notes                          60
Datatypes (contd.)




                                            om
     •    The primitive data types are
             – numeric data types
             – Non-numeric data types




                                       .c
     •    The non-numeric data types are




                             DF
             –    boolean (true or false)
             –    char . (16 bit unicode)

     •    The numeric data types are further divided into
                        aP
             – integer numeric types, and
             – real numeric types.

     •    The integer numeric types are as follows.
                 vi

             –    byte       8 bit     2c
             –    short      16 bit    2c
         ee


             –    int        32 bit    2c
             –    long       64 bit.   2c
      n



     •    Note: There is NO unsigned integer type in Java.
   w.




     •    2c representation means that there is wrap
          around without any notification of error.
          This feature is similar to C and C++.
ww




   CKR                    Java Notes                        61
A class which adds two integers




                                           om
   Program 11

   /** This program demonstrates how Java




                                       .c
   * adds two integers. */
   public class BigInt
   {




                             DF
      public static void main(String args[])
      {
         int a = 2000000000; //(9 zeros)
         int b = 2000000000;
                     aP
         System.out.println (
   “This is how Java adds integers”);
         System.out.println ( a + “+” + b + “ = ” +
                                     (a+b) );
                vi

      }
   }
         ee


     •    Output:

          This is how Java adds integers
      n



          2000000000 + 2000000000 = -294967296
   w.




     •    Q. Explain why this happens. What, if any, is the
          remedy to this problem?
ww




     •    This explains the difference between portable
          and architecture neutral.



   CKR                    Java Notes                      62
Portable and architecture neutral revisited




                                            om
     •    We observed earlier Gosling’s claim that C/C+
          are portable, but NOT architecture neutral.




                                       .c
     •    The above code provides an example.

     •    In C/C++, an int is defined as two bytes, but the




                              DF
          actual size in bits is implementation and
          architecture dependent.

     •    Though one can use bitsperbyte to ensure
                      aP
          architecture neutrality, this is rarely done.

     •    Thus, the following C/C+= program will give
          different results on different systems.
                 vi

   #include <stdio.h>
   main()
          ee


   {
      int a = 20000;
      int b = 20000;
      n



      int c;
      c = a+b;
   w.




      printf (“%d + %d = %d”", a, b, c);
   }
     •     Output: 20000+20000 = 40000
ww




                       (eg on Sun SPARC)
                  20000+20000 = -25536 (on x86)



   CKR                    Java Notes                          63
Primitive Datatypes (contd)




                                            om
     •    The real data types are
             – float         32 bit (23+8+1)
             – double 64 bit (52+11+1)




                                       .c
             –    roughly as per IEEE floating point 754
                  standard of 1985.




                              DF
     •    The key differences from IEEE 754 are

             –    In the handling of Nan
                      aP
             –    In the handling of division by zero.
             –    INF is denoted by Infinity.

     •    The range of representable numbers is restricted
                 vi

          by both mantissa and exponent.
             – The size of the exponent decides the
                  smallest and largest numbers that can
         ee


                  be represented.
             – the size of the mantissa decides the
                  precision or accuracy.
      n




     •    Note that use of floating point numbers means
   w.




          the failure of the usual laws of arithmetic, such as

             –    associative law
ww




             –    distributive law




   CKR                    Java Notes                       64
Significant figures and failure of associative law




                                            om
    Program 12
   public class Significant
   {




                                        .c
       public static void main (String args[])
       {
          final float PI = 3.141519265359f;




                              DF
          float radius = 1.0f;
          float area;
          area = PI * radius * radius;
          System.out.println (“The area of the
                      aP
             circle = ” + area);
       }
   }
      •   Output: area of the circle = 3.1415193
                 vi

    Program 13
   class AssocLaw
          ee


   {
       public static void main(String args[])
       {
      n



          float epsilon = (float)1.0E-7;
          float a1, a2;
   w.




          a1 = (epsilon + 1) -1;
          a2 = epsilon + (1-1);
          System.out.println (“The difference is = ”
ww




             + (a1-a2));
       } }
      •   Output: difference = 1.9209288E-8


   CKR                     Java Notes                   65
Difference from IEEE floating point representation




                                          om
    Program 14
   public class NumberTest
   {




                                       .c
      public static void main(String args[])
      {
         int a = 0, b=0;




                             DF
         float fa = 0, fb = 0;
         try
         {
            System.out.print (“(int) 0/0 = ” );
                     aP
            System.out.println (“ ”+ a/b);
         }
         catch (ArithmeticException e)
         {
                vi

            System.out.println (“Caught Arithmetic"
                                     +"Exception”);
         }
         ee


         System.out.println (“(float) 0/0 = ” +
            fa/fb);
         fa = (float) 1.0;
      n



         System.out.println (“(float) 1/0 = ” +
            fa/fb);
   w.




         fa = (float) 1E+39;
         System.out.println (“(float) 1E39 = ” +
            fa);
ww




         fb = (float) 2E+39;
         System.out.println (“(float) 1E39/2E39 = ”
               + fa/fb);


   CKR                    Java Notes                    66
fb = 0.0f;




                                     om
            System.out.println (“(float) 1E39 * 0 =” +
                fa * fb);
            double lfa = 1E+39;
            double lfb = 2E+39;
            System.out.println (“(double) 1E39/2E39 =




                                     .c
            ” + lfa/lfb);




                           DF
    }
   }

        •   Output:
                     aP
            (int) 0/0 = Caught Arithmetic Exception
            (float) 0/0 = NaN
            (float) 1/0 = Infinity
            (float) 1E39 = Infinity
                 vi

            (float) 1E39/2E39 = Nan
            (float) 1E39*0 = NaN
            (double) 1E39/2E39 = 0.5
      n     ee
   w.
ww




   CKR                  Java Notes               67
Features added by Java




                                             om
      •   Relational operators:

      •   New use of the arithmetic operator %




                                         .c
                –   The % operator now applies also to
                    floating point data types.




                               DF
                –   for real a, b, a%b returns the remainder
                    or the floating point value, a-nb, where n
                    is an int.
                       aP
      •   These follow the same conventions as in C/C++.

                –   Namely: For integers a, b, and integer
                    vi

                    division a/b, the quotient is always
                    rounded towards zero. Hence,
          ee


                –   a%b always has the same sign as a (to
                    preserve the relation between dividend,
                    divisor, quotient and remainder) . That is,
      n



                    if
   w.




   dividend = a     divisor = d
   quotient = q       remainder = r, then
ww




   a = qd + r




   CKR                      Java Notes                       68
Features added by Java (contd.)




                                           om
    Program 15
   class RemainderTest
   {




                                      .c
      public static void main(String args[])
      {
         float a=3.2f, b=4.3f, c;




                            DF
         c = b%a;
         System.out.println (“b%a = ” + c);
         b = -4.3f;
         c=b%a;
                     aP
         System.out.println (“-b%a = ” + c);
      }
   }
                 vi

     •    Output: b%a = 1.1000001
               -b%a = -1.1000001
         ee


     •    New operator >>>:
             – To compensate for the absence of the
      n



                unsigned type,
   w.




             –   and to permit better bit level
                 manipulation for graphics.
ww




             –   Java has an unsigned right shift.
                 >>>



   CKR                   Java Notes                   69
Features added by Java (contd.)




                                       om
    Program 16
   class RightShift
   {




                                       .c
      public static void main (String args[])
      {
         System.out.println (“-1>>4 = ” + (-1>>4));




                                 DF
         System.out.println (“-1>>>25 = ” +
         (-1>>>25));
         char ch = 0x43;
         System.out.println (“ ”+ch);
                      aP
         //char is promoted to int after call to
         //right shift
         System.out.println (“ch>>> 1 = ” +
                                      (ch >>> 1));
                vi

      }
   }
         ee


     •    Output: -1 >> 4 = -1
          -1>>>25 = 127
           C
      n



          ch >>>1 = 5
   w.
ww




   CKR                    Java Notes         70
Labeled loops and multi-level breaks




                                           om
     •    The goto statement was strongly opposed by
          proponents of structured programming.
             – imagine jumping into the middle of a for




                                       .c
                 loop.

     •    However, a classic study of thousands of lines of




                             DF
          computer code showed that 90% of the time, the
          goto was used to jump completely out of deeply
          nested loops.
                      aP
     •    This suggested that the anti-goto lobby had gone
          too far. C offers no other mechanism for jumping
          out of deeply nested loops.
                 vi

     •    the solution offered by Java is to eliminate goto,
          but allow jumping out of deeply nested loops
          through the use of
         ee


              – labeled breaks, and
              – labeled continue statements.
      n



     •    We recall that
             – break can be used only inside a for,
   w.




                 while, do-while, or switch statement.
             – continue can be used only inside a for,
                 while, do-while statement block.
ww




             –    continue distinguishes between for and
                  while loops.


   CKR                    Java Notes                       71
Labeled loops and Multi-Level Break




                                         om
     •    Accordingly Java provides an elegant solution to
          the goto problem
              – by restricting jump statements to loops,




                                      .c
              – using multi-level break and continue.

     •    A loop can be labeled, and the break and




                            DF
          continue statements can be followed by the label
          to permit execution to jump out of the loop.

    Program 17
                     aP
   public class MultiLevelBreak
   {
      public static void main(String args[])
      {
                vi

         Identifier1: for (int k=0;k<=2; k++)
         {
            System.out.println (“In top for loop”);
         ee


            Identifier2: for (int i=0; i<=20; i++)
            {
               System.out.println (“In next for loop”);
      n



               for (int j=0; j<=30; j++)
               {
   w.




               if (j==2) break Identifier2;
               if (i==2) continue Identifier1;
         System.out.println (“In bottom for loop”);
ww




            }
         }
      }}}


   CKR                   Java Notes                     72
Pass by value




                                          om
     •    Java passes by value means
             – value of primitive types and reference
                 value of reference types (objects, arrays




                                         .c
                 etc.) are passed by value.

     •    Therefore,




                               DF
             – A method cannot change the value of a
                 primitive type.

             –     A method cannot change an object
                      aP
                   reference which is its argument.

     •    However,
            – a method CAN change the accessible
                 vi

                variables within an object by invoking
                the objects methods or otherwise.
         ee


     •    This is demonstrated by the following program.

   Step 1: Define an object
      n




   In file: Ncomplex.java
   w.




   public class Ncomplex
      {
ww




        public float real;
        public float im;
        public Ncomplex (float real1, float im1)


   CKR                      Java Notes                   73
{




                                        om
              real = real1;
              im = im1;
          }
      }




                                        .c
   Step 2: Define methods which modify arguments, and




                              DF
   the
   instance variables of the arguments.

   In file: PrimObj.java
                      aP
   public class PrimObj
      {
                 vi

          public void passPrimitive (float real1,
             float im1, Ncomplex c)
          {
          ee


             real1 = c.real;
             im1 = c.im;
          }
      n



          public void passObject1 (float real1,
                float im1, Ncomplex c)
   w.




          {
             c.real = real1;
             c.im = im1;
ww




          }




   CKR                     Java Notes              74
public void passObject2 (Ncomplex c)




                                        om
        {
           Ncomplex c1; /*get object reference.
        Exactly like declaring a pointer to c1*/
           c1 = new Ncomplex(1.0f, 2.0f);
   /*Initialise the reference declared




                                       .c
   earlier */
           c = c1;




                               DF
        }
      }

   Step 3: Define a main method which calls the relevant
                      aP
   method, using the object and primitive data types.

   In file: PassRefTest.java
                vi

   public class PassRefTest
   {
      public static void main (String args[])
         ee


      {
         PrimObj my_PrimObj = new PrimObj ();
         Ncomplex c1 = new Ncomplex (1.0f, 0.0f);
      n



         Ncomplex c2 = new Ncomplex (0.0f, 1.0f);
         float real1 = 0.0f;
   w.




         float im1 = 0.0f;
         /*1: pass primitive and try to change it*/
         my_PrimObj.passPrimitive (real1, im1, c1);
ww




         System.out.println (“c1.real = ” +
              c1.real);
         System.out.println (“real1 = ” + real1);


   CKR                    Java Notes                  75
om
           /*2: pass reference and try to change its
              accessible members*/
           System.out.println (“Before: c1.real =” +
              c1.real);
           my_PrimObj.passObject1 (real1, im1, c1);




                                    .c
           System.out.println (“After: c1.real = ” +
              c1.real);




                          DF
           /*3: pass reference and try to change
              reference*/
           System.out.println (“Before: c2.real = ” +
                    aP
              c2.real);

           my_PrimObj.passObject2 (c2);
           System.out.println (“After: c2.real = ” +
                vi

                c2.real);
           }
           ee


   }
       •   Output:
           c1.real = 1.0
      n



           real1 = 1.0
           Before: c1.real = 1.0
   w.




           After: c1.real = 0.0
           Before c2.real = 0.0
           After c2.real = 0.0
ww




           c2.real = 0.0
           c2.im -= 1.0



   CKR                 Java Notes              76
Features removed by Java from C++




                                         om
     •    Simplicity:

          “You know when you have achieved perfection




                                      .c
          in design,
          Not When you have nothing more to add,
          But when you have nothing more to take away.”




                            DF
             –    Antoinne de Saint Exupery
                  as quoted in the Java Language
                  Environment White Paper.
                        aP
     •    No more
             – Preprocessor directives
             – # define
                 vi

     •    Keywords removed: No more
             – typedef
         ee


             – enum
             – structure
             – union
      n



   since they are all subsumed under the notion of class.
   w.




     •    No more storage class modifiers
             – auto (default, use static when needed)
             – extern (no global variables)
ww




             – register (register access not permitted)
             –
     •    Control statements: No more goto


   CKR                   Java Notes                    77
•    No more automatic coercions.




                                          om
     •    Functions: No more

             –    default arguments
             –    inline functions




                                      .c
     •    Operators




                              DF
             – No more operator overloading.

     •    No more pointers?
                     aP
             –    No more uninitialised pointers.
             –    (References can always be used.)

     •    Inheritance
                 vi

              – No more multiple inheritance.
                   Imagine DDD syndrome with dynamic
                   class binding.
         ee


                   DDD = Dreaded Diamond of Derivation
   Since, in a distributed environment, user may not
   know the entire family tree of the class, and class
      n



   designer may not know all possible end-uses of a
   class.
   w.




              – No more: virtual keyword.
              – use final in place of const
              – Unlike C++, final class members may
ww




                   and must be initialised where declared.
   final int a=2;
              –


   CKR                   Java Notes                     78
Classes




                                          om
     •   Classes in Java are similar to classes in C++. But
         the following salient differences exist.




                                      .c
     •   The class definition does NOT close with a
         semicolon.
            – Since Java is completely object oriented,




                            DF
                 there is nothing outside of classes, not
                 even a semicolon!

     •   The class itself can have access specifiers
                     aP
            – public
            – (no specifier) default

     •   A public class is visible to all other classes.
                 vi

            – There cannot be more than one public
                 class within a file.
         ee


             –   The file must have the same name as the
                 name of the public class.
      n



     •   A default class is visible only to members of its
         own package
   w.




             –   (More on packages shortly)
ww




   CKR                   Java Notes                          79
Class members




                                           om
     •   Class members: named variables or reference
         types are called fields.




                                     .c
            –   static fields are called class variables

            –   non static fields are called instance




                            DF
                variables.

     •   Class members can also have the following
         types of access specifiers
                   aP
            – public
            – private
            – protected
            – (no specifier) default
                vi

     •   Note: private protected no longer supported.
         This is not updated in the book by
         ee


         Balagurusamy.

     •   Unlike C++,
      n



            – default access is NOT private
   w.




            –   There is no colon after the access
                specifier
ww




            –   Access specifiers must be repeated on
                each line, else default access is
                assumed.


   CKR                  Java Notes                         80
– Thus,




                                          om
   public int a;
   int b;
           – means that b has default access.

     •   Members with default access CAN be accessed




                                      .c
         by other classes in the same package.




                            DF
     •   The term protected plays a similar role as it does
         in C++
             – protected members are like default
                 members, in that they cannot be
                    aP
                 accessed from outside the package.

            –    However, protected members are unlike
                 default members in that they can be
                vi

                 inherited, also by subclasses in other
                 packages.
      n  ee
   w.
ww




   CKR                   Java Notes                      81
Classes: Constructors




                                             om
      •   Classes have constructors, as in C++.
             – If no constructor is specified, then the
                 system provides a default constructor.




                                        .c
              –   if any constructor is specified, no default
                  constructor is provided.




                              DF
              –   The superclass constructor is always
                  called as the first line in a constructor. If
                  not explicitly called, then the superclass
                      aP
                  constructor with no arguments super()
                  is automatically called, and this may
                  result in a compile time error.
                  vi

      •   Unlike C++ an appropriate constructor is NOT
          automatically called when an object is declared.
          ee


      •  Memory allocation for objects is not done
         automatically: the constructor must be explicitly
         called.
      n



             – Thus, if My_Class is a class
   MyClass mc;
   w.




             – only declares an object reference.
             – To obtain the object, memory must be
                 explicitly allocated, using e.g. the default
ww




                 constructor
   mc = new MyClass()



   CKR                     Java Notes                        82
Classes: Memory Deallocation




                                           om
     •   However, unlike C++, in Java classes do NOT
         have destructors.
            – Memory deallocation is done




                                      .c
                automatically.

     •   Java does automatic garbage collection to claim




                            DF
         back memory of objects not required any more.

             –   Garbage collection is done on a low
                 priority basis. (More on threads later.)
                     aP
             –   Garbage collection strategies are
                 implementation dependent.
                 vi

     •   Garbage collection can be explicitly initiated by
         hand by calling the method gc() of the Runtime
         class. The gc() method has the signature
         ee


   void gc()
      n



     •   Note: Remote applets canNOT access the
         Runtime class without risking a security
   w.




         exception.
            – Untrusted applets will raise a security
                 exception.
ww




            – hence untrusted applets cannot initiate
                 garbage collection on demand.



   CKR                   Java Notes                          83
Memory Deallocation: finalize() method




                                            om
     •    There is also a finalize method which has the
          signature




                                       .c
   protected void finalize()
     •   The finalize method is normally called just before
         garbage collection is initiated.




                              DF
     •    However, whereas C++ destructors are called
          deterministically whenever an object goes out of
          scope, the finalize method is not.
                      aP
             – Specifically, the finalize method may or
                  may not be called even if garbage
                  collection is manually initiated.
                vi

     •    Since Applets cannot usually initiate garbage
          collection, on demand, it is even more uncertain
          when finalize will be called in Applets.
         ee


     •    Hence the finalize method should make NO
          assumptions about what objects exist and what
      n



          do not.
   w.




     •    Better procedure is to define a method, say
          cleanup, which is explicitly called just before the
          object goes out of scope.
ww




     •    These ideas are illustrated by the following
          program.


   CKR                    Java Notes                       84
Program 18




                                 om
   class MyClass
   {
      float myfloat [];
      MyClass()//define constructor
      {




                                 .c
         myfloat = new float [2000];
         System.out.println (“Constructor called”);




                       DF
      }
      protected void finalize ()
      {
         System.out.println (“Finalize called”);
                 aP
      }
   }
   public class Finalize
   {
             vi

      public static void main (String args[])
      {
         Runtime r = Runtime.getRuntime();
         ee


      //Runtime class cannot be instantiated
      //however we can get a reference to it.
      n



     long tmem, bmem, amem;
     tmem = r.totalMemory(); //returns long
   w.




     bmem = r.freeMemory();

     System.out.println (“Total Memory: ” +
ww




          tmem);
     System.out.println (“Free Memory Before: ”
          + bmem);


   CKR              Java Notes                85
if (true)




                                          om
       {
          //instantiate MyClass and invoke its
          //constructor
          MyClass myclass = new MyClass();




                                       .c
           //again check free memory
           amem = r.freeMemory();




                             DF
           System.out.println (“Free Memory After”
              +"allocation: “ + amem);
       }
                      aP
       //myclass goes out of scope;
       r.gc(); //initiate garbage collection
       amem = r.freeMemory();
       System.out.println (“Free Memory After”
                 vi

          + “garbage collection: ” + amem);
       }
   }
           ee


      •   Sample output:
   Total Memory = 1048568
      n



   Free Memory Before: 927824
   Constructor called
   w.




   Free Memory After allocation: 918608
   Free Memory After garbage collection: 923208
   Application Exit...
ww




       •   Note: Finalize method was NOT called in the
           above run.


   CKR                    Java Notes                     86
Inheritance and Polymorphism




                                          om
     •   Theoretically, Java permits only multi-level
         inheritance.
            – That is, a given class can have exactly




                                      .c
                 one superclass.

     •   Officially Java does not permit multiple




                            DF
         inheritance. But multiple inheritance creeps in
         through
             – interfaces (officially), and
             – inner classes (more on this later.).
                    aP
     •   Unlike C++
            – No colon “:” is used to indicate the base
                 class. Instead one uses the keyword
                 vi

                 extends. For example,
   public class MyApplet extends Applet
         ee


     •   The base class of C++ is called superclass in
         Java.
      n



             –   There is no scope resolution operator,
                 but one can refer to the superclass
   w.




                 members using the keyword super.

             –   This is the counterpart of the this
ww




                 pointer available in any non-static
                 method.



   CKR                   Java Notes                        87
Polymorphism: method overloading and overriding




                                         om
     •   Overloading works exactly as in C++.

     •   Overloading means that two methods




                                     .c
            – have the same name, but
            – have different parameter lists
            – so that they have different signatures.




                            DF
            – (Note: signature differences due to
                differences in return type alone are not
                permitted: the parameter lists must be
                different. )
                    aP
     •   Overriding means that two methods
            – have the same name, and
            – have the same parameter lists
               vi

            – so that they have the same signature,
            – but one method is defined in a super
                 class,
         ee


            – and the second method is defined in a
                 derived class.
      n



     •   Overriding works exactly as in C++. This
         corresponds to dynamic polymorphism.
   w.




            – the right version of the method is called
                 at run time.
ww




     •   However, instead of pointers, one uses object
         references.



   CKR                  Java Notes                         88
Program 19




                                 om
   import java.io.*;
   class Animal
   {
      void sleep ()
      {




                                 .c
         System.out.println (“Animalzzz..”);
      }




                       DF
      void sleep (int t) //overload sleep method
      {
         System.out.println (“Animalzzz... for”
            + t + “ seconds”);
                 aP
      }
   }

   class Dog extends Animal
             vi

      {
        void sleep () //override sleep method
        {
         ee


           System.out.println (“Dogzzz...”);
        }
      n



        void sleep (int t)
   //override second sleep method
   w.




        {
           System.out.println (“Dogzzz... for ” +
                                    t + “ seconds”);
ww




        }
      }



   CKR              Java Notes              89
class Mongrel extends Dog




                                 om
     {
        void sleep () //override sleep method
        {
           System.out.println (“Mongrelzzz...”);
        }




                                 .c
        void sleep (int t)




                       DF
   //override second sleep method
        {
        System.out.println (“Mongrelzzz... for ” +
                                    t + “ seconds”);
                 aP
        }
      }

     public class Polymorph
             vi

     {
        public static void main (String args[])
           throws IOException
         ee


        {
           //obtain a reference to Animal
           Animal my_Animal;
      n




           //initialise to Animal object
   w.




           my_Animal = new Animal();
           int trun;
           DataInputStream in = new
ww




   DataInputStream(System.in);
        System.out.println (“n Enter an integer”);



   CKR              Java Notes              90
String inString = in.readLine();




                                           om
              trun = Integer.parseInt (inString);

           switch (trun)
           {
              case 1:




                                       .c
   //re-initialize the reference to an
   //appropriate object




                             DF
              my_Animal = new Dog();
              break;

                case 2:
                     aP
                my_Animal = new Mongrel();
                break;

                default:
                vi

                break;
                }
          ee


              //just code the following two lines
              my_Animal.sleep();
              my_Animal.sleep(2);
      n



              //the right version of sleep is called.
          }
   w.




      }
     •    Ouptut: The right version of sleep is called.
          E.g. input trun = 1, output:
ww




          Dogzzz...
          Dogzzz... for 2 seconds



   CKR                    Java Notes                      91
Overriding (contd): abstract and final classes




                                           om
     •    Since there is no virtual keyword in Java, there
          are no pure virtual functions.




                                       .c
     •    However, a method which has no
          implementation is called an abstract method, and
          may be ddeclared as such, using the abstract




                              DF
          keyword.
          abstract ret_type method_name (args);
     •    A class containing an abstract method is not
          only known as an abstract class, it must be
                      aP
          declared as such.

     •    Though an abstract class cannot be instantiated,
          a reference to it can be created.
                 vi

              – This is essential to permit dynamic
                   polymorphism.
     •    In the preceding example, if one or both of the
          ee


          sleep methods in the Animal class is declared
          abstract, then the class cannot be instantiated,
          so its constructor cannot be called.
      n



              – However, the rest of the program will
                   work similarly.
   w.




     •    On the other hand, to prevent a method from
          being overridden one can declare the method (or
ww




          class) to be final, using the final keyword.
              – A final class cannot be subclassed.



   CKR                    Java Notes                         92
Packages and C++ namespaces




                                         om
     •   Since Java, like C++, permits both
             – method overloading, and
             – method overriding




                                     .c
   An unintended name collision can lead to unexpected
   program behaviour.




                            DF
     •   Such unintended name collision may arise, for
         example when using two libraries sourced from
         two different third-parties.
                    aP
     •   A similar problem was encountered in C++,
         where the programmers had three choices:
             – discard one of the libraries
             – get the source code for one of the
               vi

                 libraries and change the name
             – persuade the owner of the library to
                 recompile the library after changing the
         ee


                 name of the concerned function.

     •   Very often, none of these choices was feasible.
      n




     •   Hence it is desirable to have a mechanism to
   w.




         limit the scope of names.

     •   This is achieved in C++ through the use of
ww




         namespaces.

     •   Java uses packages.


   CKR                  Java Notes                         93
Packages (contd)




                                          om
     •   A package is created by the statement
   package pkg;




                                      .c
     •   A package statement always has file scope, so
         that
             – a package statement, if used, must be




                            DF
                the first statement in a file.

             –   If no package statement is used, a
                 default package is automatically
                      aP
                 provided.

     •   The use of a package limits the scope of names,
         so that the fully qualified name of a variable or
                 vi

         method is its name preceded by the package
         name.
         pkg.my_variable
         ee


             – Note that Java uses a dot, since there is
                  no scope resolution operator.
      n



     •   The fully qualified name may be abbreviated
         within the file by an import statement
   w.




   import pkg.*; //imports all classes in pkg

             –   The Java import statement is the
ww




                 counterpart of the C++ using
                 statement.



   CKR                   Java Notes                      94
Packages: Java source file structure




                                           om
     •    Thus, a java source file can have any or all of the
          following four internal parts.




                                       .c
     •    (1) A single package statement (optional)
              – this must be the first non-comment
                   statement of the program




                             DF
     •    (2) Any number of import statements (optional)

     •    (3) A single public class declaration (necessary)
                      aP
     •    (4) Any number of class declarations (optional)
              – subject to the overall limitations of the
                  JVM.
                vi

     •    If multiple import statements lead to a name
          collision, this will be flagged as an error.
         ee


     •    That is, if package pkg1 has a class called
          MyClass, and package pkg2 also has a class
      n



          called MyClass, and if one invokes MyClass,
          without specifying the package name, this will be
   w.




          flagged as an error.
ww




   CKR                    Java Notes                        95
Packages: hierarchies and CLASSPATH




                                         om
     •   Like namespaces, packages may be nested into
         a hierarchy.




                                     .c
   package pkg1.pkg2.pkg3

     •   For the benefit of the JVM Class Loader,




                           DF
            – public class names must match file
                 names, and

            –   A package hierarchy must match the
                    aP
                directory structure.

     •   CLASSPATH environment variable must be set to
         the root of this directory tree.
                vi

             – Preferably use -classpath option, instead
                  of setting the CLASSPATH variable
                  globally.
         ee


     •   In the following example, there are two packages
             – pkg1 in e:javakawapkg1 directory
             – pkg2 in e:javakawapkg2 directory
      n




     •   set CLASSPATH to include e:javakawa
   w.




             – (Java 1.1)
   set
   CLASSPATH=.;e:javalibCLASSES.ZIP;e:java
ww




   kawa
           – java 1.2
   set CLASSPATH=.;e:jdk1.2;e:javakawa


   CKR                  Java Notes                     96
Package and access: example




                                         om
   Program 20
     •  Source in file e:javakawapkg1Base.java




                                     .c
   package pkg1;

   public class Base




                           DF
   {
      public int pub; //public access
      protected int prot; //protected
      int def;//default access
                    aP
      //inconsistent declaration
      //private protected int priprot; //illegal

       private int priv;
               vi

   }

   class Derived extends Base
         ee


   {
      int deriv;
      void showPriv ()
      n



      {
      //error: private variables are not
   w.




      //inherited
      //System.out.println (“b.priv = ” + priv);
      }
ww




   }




   CKR                  Java Notes                   97
•   Source in file e:javakawapkg1InheritTest.java




                                          om
   package pkg1;
   import pkg2.*;
   public class InheritTest
   {




                                      .c
      public static void main (String args[])
      {




                            DF
         Base b = new Base();
         Derived d = new Derived();
         System.out.println (“b.pub = ” + b.pub);
         System.out.println (“d.pub = ” + d.pub);
                     aP
         System.out.println (“b.prot = ” + b.prot);
         System.out.println (“d.prot = ” + d.prot);
         System.out.println (“b.def = ” + b.def);
         System.out.println (“d.def = ” + d.def);
               vi

         //error: private variable not accessible
         //System.out.println (“b.priv = ” +
              //b.priv);
         ee


         //Now declare object from another package
      n



     Other o = new Other();
        System.out.println (“o.pub = ” + o.pub);
   w.




        System.out.println (“o.prot = ” + o.prot);
     //def variable may be accessed thus.
        System.out.println (“o.def = ” + o.def);
ww




     // o.showDef ();//error showDef not
        //accessible here
        o.showProt();}}


   CKR                   Java Notes                          98
Source in e:javakawapkg2Other.java




                                        om
   package pkg2;
   import pkg1.*;
   public class Other extends Base
   {




                                     .c
      int other;
      void showDef ()




                            DF
      {
         //error variable def not accessible here
         //System.out.println (“o.def = ” + def);
         //protected variable from other package
                      aP
         //can be accessed here.
         public void showProt () {
         System.out.println (“o.prot = ” + prot);
         }
                vi

      }
   }
     •   Output:
         ee


         b.pub = 0
         d.pub = 0
      n



         b.prot = 0
         d.prot = 0
   w.




         b.def = 0
         d.def = 0
         o.pub = 0
ww




         o.prot =0
         o.def = 0
         o.prot = 0


   CKR                  Java Notes           99
Access rules for class members




                                        om
                    Private   Default Protected   Public
     Same class        Y        Y         Y         Y
   Same package:




                                       .c
                      N          Y       Y          Y
      subclass
   Same package:
                      N          Y       Y          Y




                              DF
    nonsubclass
      Different
      package:        N          N       Y          Y
      subclass
                    aP
      Different
      package         N          N       N          Y
    non-subclass
               vi
      n  ee
   w.
ww




   CKR                    Java Notes                    100
JAR files




                                            om
     •    JAR files are Java archive files.
     •    Exactly like zip files, except that the terminology
          and usage relates to Unix, where




                                       .c
               – tape archive files are called tar files.
               – Moreover, compressed JAR files are
                    acceptable to the JVM.




                              DF
     •    Bundling and Compression: The advantage of
          zip files is that the directory structure can be
          recursed and stored in the zip file.
     •    Portability: This makes JAR files particularly
                      aP
          suitable for storing and transferring large
          packages.
               – E.g. on Mac more than 32 characters
                    were not accepted as Dir names
                vi

     •    Thus, the previous example can also be run by
          first archiving and calling the jar tool from
          E:javakawa directory (Java 1.1)
         ee


          jar -cvf0 Inherit.jar pkg1
          c= create new, v=verbose, f=filename 0= no
      n



          compression.
     •    Since the argument is a directory, it is
   w.




          automatically recursed.
     •    One now adds Inherit.jar to the classpath, and
          invokes java InheritTest, and the classloader will
ww




          locate the InheritTest class.
     •    Security: Jar files can be signed, thus providing
          a layer of security.


   CKR                    Java Notes                      101
Interfaces




                                             om
     •    Java’s first route to multiple inheritance is
          provided through interfaces.




                                         .c
     •    Usually, in multiple inheritance one is interested
          only in the methods, and not in duplicate
          inheritance of data members.




                               DF
     •    An interface contains only
             – constants (i.e., final data members), and
             – method declarations
                       aP
                –   Like a class the interface itself can have
                    default or public access.
                    vi

   access_type interface i_name
   {
   return_type method1(param_lst);
         ee


   return_type method2 (param_lst);
   type final var_name1 = value;
   ...
      n



   }
   w.




     •    However, all methods and constants in an
          interface are implicitly public.
ww




     •    A class implements an interface.
              – i.e., the class defines the methods
                  declared in the interface.


   CKR                      Java Notes                      102
–    all interface methods must be declared




                                          om
                 public in the class implementation.

     •   A class may implement more than one interface,
         by providing a comma separated list of
         interfaces.




                                      .c
   access class class_name [extends




                            DF
   superclass_name] implements
   interface_name1, interface_name 2
   {...
   ]
                    aP
     •   If a class which implements an interface, does
         not implement all the methods of that interface,
         then the class must be declared as abstract.
                vi

     •   Any subclass must either implement all the
         methods or be itself declared as abstract.
         ee


     •   Interfaces thus provide a form of multiple
         inheritance, in which a class may inherit
      n



         methods from a variety of sources.
   w.
ww




   CKR                   Java Notes                    103
Dynamic polymorphism, extending interfaces and




                                         om
   adapter classes

             –   An object reference may be declared to
                 be of interface type.




                                     .c
             –   This reference may be assigned at run
                 time to any one of various classes which




                           DF
                 implements the interface.

             –   The implemented methods of that class
                 will be called.
                    aP
     •   Inheritance of interfaces:
            – One interface can extend another
                 interface.
                 vi

   interface mine extends yours
   {
         ee


      //new methods
   ]
     •   A class which now implements interface mine
      n



         must implement all the methods in yours and
         mine.
   w.




     •   However, there are Adapter classes which enable
         one to implement only part of an interface.
ww




   CKR                  Java Notes                     104
om
    Program 21
   interface Area
   {
      final float pi = 3.14f;
      float area (float diameter);




                                 .c
   }




                       DF
   class Circle implements Area
   {
      public float area (float diameter)
      {
                 aP
         return pi*diameter;
      }
   }
             vi

   class Square implements Area
   {
      public float area (float diameter)
         ee


      {
         return diameter*diameter;
      }
      n



   }
   w.
ww




   CKR              Java Notes             105
om
   public class Interf
   {
      public static void main (String args[])
      {
         Area a;




                                      .c
         a = new Circle();
      System.out.println (“Area of circle = ” +




                             DF
               a.area (2.0f));
         a = new Square();
         System.out.println (“Area of square= ”+
            a.area (2.0f));
                     aP
      }
   }

     •   Output:
               vi

         Area of circle = 6.38
         Area of square = 4
      n  ee
   w.
ww




   CKR                   Java Notes         106
Inner classes and multiple inheritance in Java




                                            om
     •    Interfaces provide one route to multiple
          inheritance.




                                       .c
     •    Inner classes provide another route.

     •    This second route is not documented, and sun




                              DF
          documentation speaks of adapter classes.

     •    However, while inner classes may be used in that
          context, adapter classes are irrelevant to the
                      aP
          basic syntax of inner classes.

     •    One class may be defined within another.
                vi

     •    Such a class is called a nested class.

     •    A static nested class behaves like a top-level
         ee


          class (i.e., a class which is not contained in any
          class)
      n



     •    A non-static nested class is called an inner class.
   w.




     •    Such nested classes may be defined within any
          expression.
ww




   CKR                    Java Notes                      107
Nested and inner classes (contd)




                                             om
     •    Nested classes have access to all of the
          variables of the enclosing class.




                                       .c
     •    However, the enclosing class must access the
          nested class variables through an object
          reference.




                              DF
     •    The key point is that the nested class can inherit
          independently of the inheritance hierarchy of the
          enclosing class.
                      aP
     •    Thus, inner classes permit multiple inheritance in
          practice.
                vi

     •    This is illustrated by the following example.

     •    Note: Java rejects multiple inheritance in
         ee


          principle, since it permits one class to have only
          one superclass.
              – Inner classes do NOT negate this rule in
      n



                  principle.
              – However, through inner classes, one can
   w.




                  effectively subvert this principle in
                  practice.
ww




   CKR                    Java Notes                       108
om
   Program 22

     •   In file: e:javakawapkg2Base2.java
   package pkg2;
   public class Base2




                                       .c
   {
      int base2;




                              DF
      protected void base2Method()
      {
         System.out.println (“In Base 2");
      }
                      aP
   }

     •   In file: e:javakawapkg1MultipleInherit.java
   package pkg1;
                 vi

   class Base1
   {
      int base1;
          ee


      void base1Method()
      {
         System.out.println (“In Base 1");
      n



      }
   }
   w.




   class Derived extends Base1
ww




   {
       int derivInt=2;


   CKR                    Java Notes                       109
class Inner extends pkg2.Base2




                                         om
      {
         void showInner()
         {
            base1Method();
            base2Method();




                                      .c
   //access protected method from other
   //package




                            DF
            System.out.println (”Though I abused"+
   “multiple inheritance, I still use it”);
         }
      }//end of class Inner
                     aP
      void deriv()
      {
      Inner i = new Inner();
      i.showInner();
                vi

      }}
      public class MultipleInherit {
         public static void main(String args[])
         ee


         {
            Derived d = new Derived();
            d.deriv();
      n



            //Inner i = new Inner(); //illegal
            //i.showInner();
   w.




        }}
     •   Output:
         In Base 1
ww




         In Base 2
         Though I abused multiple inheritance, I still use it.



   CKR                   Java Notes                    110
Exceptions




                                         om
     •   An exception is an unusual condition in a
         program.
            – Example: an illegal mathematical




                                     .c
                operation is an exception.

            –   Eg. integer division by zero will lead to




                           DF
                an exception and to immediate program
                termination.
    Program 23
   public class DivideByZero
                    aP
   {
      public static void main (String args[])
      {
         int a=1;
                vi

         int b=0;
         System.out.println (“a/b = ” + a/b);
      }
         ee


   }

     •   output:
      n



         java.lang.ArithmeticException: / by
         zero
   w.




            at
         DivideByZero.main(DivideByZero.java:7)
         Application Exit
ww




   CKR                  Java Notes                     111
•    Though the stack trace provided by Java is




                                          om
         helpful to the programmer for debugging, such
         abrupt termination is likely to leave the user
         confused.

    •    Exceptions allow the programmer to handle such




                                      .c
         situations smoothly..




                            DF
    •    The classical C approach to exception handling
         involves two routes.
            – signal and raise
            – setjmp and longjmp
                    aP
    •    In the signal method, an exceptional condition,
         such as division by zero, is indicated by means
         of a signal SIGFPE, defined in signal.h
               vi

    •    (Alternatively, a user may raise a signal through
         raise.).
         ee


    •    When a signal is raised, a signal handler (a
         function) is called.
      n




    •    A default signal handler is provided, and the user
   w.




         may override it by registering an alternative
         signal handler (pointer to a function).
    •    A default math error handler is provided, and the
ww




         user may override it by redefining the function
         matherr.



   CKR                   Java Notes                     112
•   These considerations are illustrated by the




                                        om
         following C program (which works also in C++)
    Program 24
   #include <stdlib.h>
   #include <stdio.h>
   #include <math.h>




                                     .c
   #include <signal.h>




                           DF
   /*==trap floating point errors === */
   void float_trap(int sig)
   { fixerr(); /*do some deallocation*/
   printf(“n Encountered a floating point”,
                    aP
   “error.”);
       printf(“n Check whether the last input:,
   ”was mathematically well-posed.");
       return;
               vi

   }
   /*==signal handler for floating point
   errors====*/
         ee


   void siginst(void)r
   {
       if (signal(SIGFPE, float_trap) == SIG_ERR)
      n



       {     printf(“Error installing signal”
   “handler.n”);
   w.




          exit(3);
       }
   }
ww




   /*=user defined handler for math errors =*/
     int matherr (struct exception *a)
     {


   CKR                  Java Notes                   113
/*This user-modifiable function is called




                                 om
   automatically when a mathematical error
   is encountered. struct exception is
   defined in math.h*/
       char *s1;
      fixerr();




                                 .c
      printf (“n Encountered a mathematical
   error,”);




                       DF
    printf (“n related to the function:%s.”,
   a->name);
      switch (a->type)
      {
                 aP
      case DOMAIN: s1 = “The argument was”
   “outside the domain of the function.”;
   break;
      case SING: s1= “The argument was singular”
             vi

   “(i.e., on the domain boundary).”;break;
      case OVERFLOW: s1="The function value was"
   “too large.”; break;
         ee


      case UNDERFLOW: s1="The function value"
   “was too small.”; break;
      case TLOSS:
      n



      case PLOSS:s1="There was total or partial"
   “loss of significance.”; break;
   w.




          default: s1= “       ”;    break;
        }
        printf (“n %snn”, s1);
ww




        exit(1);
        return 1;
    }


   CKR              Java Notes              114
/*=============fixerr================*/




                                  om
         fixerr(){ }
   /* ============main=============== */
     main()
     {
        float a=1, b=0;




                                  .c
        float c;
        system(“cls”);




                        DF
        siginst (); /*install signal handler*/
        /*if (b==0)
        raise (SIGFPE);*/
        /*The commented code above is an example
                  aP
   of a user generated signal. Below the
   signal is raised by the system*/
        c=a/b;
        c = log (-a);
              vi

        return;
   }
       •   Output:
         ee


           Encountered a floating point error...
           Encountered a mathematical error
           related to the function log
      n



           The input was outside the domain of
           the function.
   w.
ww




   CKR               Java Notes              115
Exceptions (contd)




                                          om
     •   The other way to handle exceptions is through
         the functions setjmp and longjmp.




                                      .c
     •   The state of the stack at a user-determined point
         in the program is saved through a call to setjmp.




                            DF
     •   If an error is subsequently encountered, the
         stack is unwound to the previously saved state,
         i.e., the program executes a goto to the
         previously saved state by calling longjmp.
                     aP
     •   This is illustrated by the following program.
                vi
      n  ee
   w.
ww




   CKR                   Java Notes                      116
Program 25




                                  om
   #include <stdio.h>
   #include <setjmp.h>
   #include <signal.h>
   jmp_buf jumper;
   /*jmp_buf is a structure defined in




                                  .c
   setjmp.h*/
   /*==trap floating point errors ==== */




                        DF
   void float_trap(int sig)
   {
      char *s = “nn Encountered a floating
   point error”;
                 aP
      printf (“%s”, s);
      longjmp (jumper, 1);
   }
   /*===signal for floating point errors
             vi

   =========*/
   void siginst(void)
   {
         ee


        if (signal(SIGFPE, float_trap) == SIG_ERR)
      {
      printf(“Error installing signal
      n



   handler.n”);
      exit(3);
   w.




      }
   }
   /* ==============main=============== */
ww




   main()
   {
      int value;


   CKR               Java Notes             117
float a=1, b=0;




                                          om
       float c;
       siginst (); /*install signal handler*/
       value = setjmp(jumper);
       if (value != 0)
       {




                                       .c
          printf(“n Longjmp with value %dn”,
             value);




                             DF
          goto next;
       }
       c=a/b;
       next:
                      aP
          printf (“n Reached next”);
          return;
   }
                 vi

       •   Output:
                Error encountered
                Long jump with value 1
           ee


                Reached next.

       •   While this approach may be used in C++ it has
      n



           certain disadvantages.
   w.




       •   The disadvantages of this older approach of
           handling exceptions, arise from certain new
           features introduced by C++, namely classes and
ww




           objects.




   CKR                    Java Notes                   118
Exceptions (contd.)




                                          om
     •   Consider the following sort of code involving
         longjmp
   void some_function ()




                                      .c
   {
      FILE* fp = fopen (fname, “rw”);
      float *pf =




                             DF
      (float *) malloc (1000*sizeof(float);

   /* do something */
   if (error)
                     aP
      longjmp (jumper, ErrorCode);
   /*do something else*/
   fclose (fp);
   free (pf);
                vi

   }

     •    if the program encounters an exception, and
         ee


          takes a long jump to the previously saved state.

     •    Hence the file handle is not closed, and
      n



          subsequent attempts to access the same file
          would fail.
   w.




              – If a new file is opened each time, the
                  system would soon run out of file
                  handles.
ww




     •    The dynamically allocated memory would not be
          returned to the heap.



   CKR                   Java Notes                      119
Exceptions (contd)




                                           om
     •   Thus, a longjmp creates a problem when there
         are interim resources at risk.




                                      .c
     •   Since the longjmp has to be executed at the
         point where the error/exception is encountered,
         all resources must be freed.




                             DF
     •   However, unwinding the stack only frees
         automatic variables and function calls.
                     aP
     •   The manually allocated heap memory, and other
         resources must be freed manually.

     •   This is difficult to perform in C++/Java, since
                vi

         references to objects also occupy the stack.

     •   Unwinding the stack frees the references to
         ee


         these objects, but it does not free the heap
         memory occupied by the objects.
      n



     •   For that to happen, the destructor functions
         must execute, and this would be bypassed when
   w.




         a longjmp takes place.

     •   Hence, C++/Java needs an alternative method of
ww




         exception handling.




   CKR                   Java Notes                        120
Exception handling: Java specific




                                            om
     •    In Java exception handling is done through 5
          keywords
              – throw




                                       .c
              – try
              – catch
              – throws




                              DF
              – finally

     •    When an exception is thrown,
            – not only is the stack unwound to a
                      aP
                previously saved state, but
            – automatic objects are marked for
                finalization (destructors are exeecuted in
                C++)
                vi

            – if the exception is thrown from within a
                constructor, the finalizer of that object is
                not executed.
         ee


            – key resources may be manually freed
                through the use of a finally block which is
                guaranteed to execute, whether or not an
      n



                exception is thrown.
   w.




     •    The code to be monitored is put into a a try block.

     •    The action to be taken, when an exception is
ww




          thrown is put into various catch blocks.




   CKR                    Java Notes                      121
•   Each catch block decides what action is to be




                                         om
         taken when a particular exception is thrown.

   try{//try block
   }
   catch (Exception_type1 arg)




                                     .c
   { //catch block
   }




                           DF
   catch (Exceptiontype2 arg)
   { //catch block 2
   }
   ...
                    aP
                 vi

                     Object
         ee


                   Throwable
      n




         Error                 Exception
   w.




                                  RunTimeException
ww




                                        ArithmeticException


   CKR                  Java Notes                       122
Exceptions: try, throw, catch sequence




                                            om
     •    The following code is an example of a basic
          try-throw-catch sequence.




                                      .c
    Program 26
   public class CatchException
   {




                            DF
      public static void main(String args[])
      {
         int a = 1;
         int b = 0;
                     aP
         try //start try block
         {
            System.out.println (“Trying...”);
            int c = a/b; //exception is thrown
                vi

         }
         catch (ArithmeticException e)//and caught
         {
         ee


            System.out.println (“Well caught”);
         }
         System.out.println (“Normal program exit”);
      n



      }
   }
   w.




     •    Output: Trying...
          Well caught
ww




          Normal program exit.




   CKR                   Java Notes                     123
Exceptions: multiple catch blocks




                                            om
     •    Catch is not called: program execution is
          transferred to it.
              – if no exception occurs, then the catch




                                       .c
                  block will NOT execute.

     •    There may be more than one catch block.




                             DF
             – Each catch block handles one type of
                 exception .

             –    But only that catch block will be
                     aP
                  executed which matches the type of the
                  exception generated.

     •    Thus, if we rewrite the previous program, so that
                 vi

             –    there are two catch blocks:
         ee


             –    one which handles arithmetic exceptions.

             –    and one which handles i/o exceptions,
      n




             –    and if an integer is incorrectly entered,
   w.




             –    then the exception will NOT be caught,
                  and an abnormal program termination
ww




                  will occur .




   CKR                    Java Notes                      124
Program 27




                                   om
   import java.io.*;
   public class MultipleCatch
   {
      public static void main(String args[])
      { int a;




                                   .c
         int b;




                         DF
          try
          {
             System.out.println (“a = ”);
             DataInputStream in = new
                   aP
                DataInputStream(System.in);
             String inString = in.readLine();
             a = Integer.parseInt (inString);
             System.out.println (“b = ”);
               vi

             b = Integer.parseInt (in.readLine());
             int c = a/b;
          }
          ee


          catch(ArithmeticException e)
          {
             System.out.println (“Caught Arithmetic"+
      n



                “exception”);
          }
   w.




          catch (IOException i)
          {     System.out.println (“Caught i/o”+
                “exception”);
ww




          }
          System.out.println (“Program exit”);
     }}


   CKR                Java Notes             125
•    Case 1: input:




                                           om
         a=2
         b=3

    •    output: Program exit




                                       .c
    •    Case 2: Inputa=2
         b=0




                               DF
    •    Output:
         Caught Arithmetic Exception
         Program exit
                     aP
    •    Case 3: input: a= *

    •    output:
               vi

         java.lang.NumberFormatException: *
         at java.lang.Integer.parseInt(Integer.java:231)
         at java.lang.Integer.parseInt (Integer.java:278)
         ee


         at MultipleCatch.main (MultipleCatch.java:15)

    •    Case1: no catch block is executed, since no
      n



         exception is thrown.
   w.




    •    Case 2: the first catch block is executed, since
         an ArithmeticException is thrown.
ww




    •    Case 3: a NumberFormatException is thrown but
         there is no matching catch block. Hence the
         program terminates


   CKR                    Java Notes                        126
Exceptions: Throwable and checked exceptions




                                          om
     •    Unlike C++, primitive types cannot be thrown.
          Throwable types must be subclasses of
          Throwable




                                        .c
     •    In the previous example we saw that an
          uncaught exception leads to program




                              DF
          termination.
     •    Not all exceptions can be uncaught. Exceptions
          may be divided into two classes
     •    Unchecked exceptions are
                      aP
              – subclasses of Error, or
              – subclasses of RunTimeException
     •    checked exceptions: all others
                vi

   Exceptions: catch all
         ee


     •    if a method can generate checked exceptions,
          then these must be either
               – specified using a throws clause
               – or caught in a try block
      n



                   else there is a compile-time error
   w.




     •  Unchecked exceptions need not be specified.
           – hence lazy programmers tend to
              subclass RunTimeException to produce
ww




              their exceptions.
           –
   Program 28


   CKR                     Java Notes                     127
class MyException extends Exception




                                 om
   {
      int exception_num;
   }

   public class CheckedException




                                 .c
   {
   int myMethod (int a, int b) throws




                       DF
            MyException
   {
   MyException e = new MyException();
   if (a==0)
                 aP
      {
      e.exception_num = 1;
      throw e;
      }
             vi

   if (b==0)
      {
      e.exception_num=2;
         ee


      throw e;
      }
   return a/b;}
      n



   public static void main (String args[])
   {
   w.




      CheckedException e = new
            CheckedException();
      try
ww




      {
         e.myMethod (0, 1);
      }


   CKR              Java Notes               128
catch (MyException me)




                                        om
       {
          System.out.println (me.exception_num);
       }
   }
   }




                                      .c
       •   The above program will NOT compile if




                            DF
              – the throw clause is removed from
                  myMethod, or
              – the catch clause is removed from main
                  (and no throws clause is provided to
                     aP
                  main)
                vi
      n    ee
   w.
ww




   CKR                   Java Notes                  129
Catch all exception handler




                                           om
     •    Since all exceptions are subclasses of
          Exception,
             – To catch all exceptions, one uses the




                                       .c
                  catch-all exception handler with
                  Exception as the type




                             DF
                  catch (Exception e) {
                  //catch block
                  }
                     aP
     •    Since one exception is handled by at most one
          catch block,
              – if there is more than one catch block,
              – and a catch-all,
                vi

     •    then the catch-all error handler must appear last
             – for the first catch block which fits the
         ee


                  exception will be executed.

     •    Similarly, if there are two catch blocks one
      n



          involving a base type and one a derived type,
             – then the catch block with base type must
   w.




                  appear last
             – since a base type will fit a derived type,
                  but not vice versa.
ww




   CKR                    Java Notes                     130
Exceptions: Miscellaneous




                                           om
     •   Try blocks may be nested.
             – In this case, if the first try block does not
                 have an appropriate handler for the




                                      .c
                 exception, the exception will be passed
                 to the outer block, and so on.




                             DF
             –   The exception can be handled by both
                 inner and outer catch block, by making
                 the inner catch block rethrow what it has
                 caught.
                     aP
     •   A finally clause may be associated with each try
         block, and this is guaranteed to execute.
             – The JVM achieves this by checking all
                 vi

                  possible exits to the try block.
      n  ee
   w.
ww




   CKR                   Java Notes                      131
Program 29




                                 om
   import java.io.*;
   public class NestedCatch
   {
      public static void main(String args[])
      {




                                 .c
         int a;
         int b;




                       DF
         try
         {
         try
                 aP
         {

           System.out.println (“a = ”);
           DataInputStream in = new
               vi

   DataInputStream(System.in);
           String inString = in.readLine();
           a = Integer.parseInt (inString);
         ee


           System.out.println (“b = ”);
           b = Integer.parseInt (in.readLine());
           int c = a/b;
      n



        }
        catch(ArithmeticException e)
   w.




        {
           System.out.println (“Caught Arithmetic
   exception”);
ww




           throw e; //rethrow
        }



   CKR              Java Notes             132
catch (IOException i)




                                    om
        {
            System.out.println (“Caught i/o
   exception”);
        }
        finally




                                    .c
        {
            System.out.println (“Exiting inner try”);




                             DF
        }
        }
        catch(Exception e)
        {
                   aP
            System.out.println (“Caught something”);
        }
        System.out.println (“Program exit”);
      }
              vi

   }
     •   input:
         a=2
         ee


         b=2
     •   output:
         Exiting inner try
      n



         Program exit
   w.




     •   input:
         a=*
     •   output:
ww




         Exiting inner try
         Caught something
         Program exit


   CKR                 Java Notes           133
Threads




                                          om
     •   A multitasking OS, such as UNIX or Widows,
         handles several processes at the same time.




                                      .c
     •   Each process is an independently executing
         program, which may be
             – running




                            DF
             – ready, or
             – blocked (waiting for input)
     •   A thread is a subsequential flow of control within
         a single sequential program.
                    aP
             – That is, a thread is a “lightweight”
                  process (or a sub-process) that runs
                  from within a program.
     •   That is, a thread is a process, where the
               vi

         overheads involved in switching from one thread
         to another are small, since
             – a thread runs from within the program
         ee


             – a thread shares the existing memory
                  space allocated to the program
             – Inter-thread communication is easier.
      n




     •   From a logical point of view, however, threads
   w.




         are best thought of in terms of Hoare’s paradigm
         of
            – communicating sequential processes.
ww




            – since only one processor, and one
                program is involved, the operational
                overheads are small in practice.


   CKR                   Java Notes                     134
Threads (contd.)




                                           om
     •    Logically, the CSP (Communicating Sequential
          Processes) model applies to
             – parallel processing




                                      .c
             – multi-tasking
             – threads




                             DF
     •    However, the goals in each case are different.

             –    In parallel processing, the goal is to
                  improve performance at low cost, by
                      aP
                  increasing the number of processors,
                  each of which runs a separate process.

             –    In multi-tasking, the goal is to make more
                 vi

                  efficient use of a single processor (CPU),
                  by running other processes when the
                  CPU is idle because a given process is
         ee


                  either blocked or idle, or does not need
                  all the system resources.
      n



     •    Java uses threads to permit part of a program to
          execute, even when another part of the program
   w.




          is
             – blocked (waiting for input)
             – or running in an infinite loop.
ww




   CKR                   Java Notes                        135
Threads (contd)




                                          om
     •   Thus, animation typically requires an infinite
         loop.
            – if a program has only one thread, it can




                                      .c
                 perform animation, but do no other task.

             –   Typically, however, one wants an




                            DF
                 animation, as a background, while some
                 other process runs in the foreground.

     •   Similarly, GUI typically involves event driven
                     aP
         programming.
            – A particular text box (window) is in an
                 infinite loop,
            – waiting for events, or
                 vi

            – handling events.

     •   Without threads, nothing else could execute
         ee


         until a particular event handler returns.
             – With multi-threading, one thread can wait
                  for events or handle events without
      n



                  blocking other parts of the program.
   w.




     •   Finally, network download times are uncertain,
         so threads are essential for a complex program.
ww




     •   Thus, though Java is architecture-neutral it can
         run only in a multi-tasking environment!



   CKR                   Java Notes                       136
Threads




                                          om
     •   Like a process, a thread can exist in various
         states
             – running




                                      .c
             – ready
             – suspended
             – resumed




                             DF
             – blocked

     •   In any of the above states the thread is alive. A
         thread an be terminated, in which case it is no
                     aP
         longer alive.

     •   Some key concepts associated with threads are
         the following.
               vi

     •   Priority, decides how much of the process time
         the thread will consume.
         ee


     •    Synchronization:
              – if one thread updates names, and
      n



              – another updates addresses
   the two threads must be synchronized to ensure that
   w.




   names and addresses match!

     •   Deadlock:If two threads simultaneously access
ww




         the same resource, this can result in a deadlock.
             – e.g. two people speaking simultaneously
                in an international call.


   CKR                   Java Notes                      137
Threads: implementation




                                          om
     •   Every Java program has a Main thread.
            – The main thread is the first thread to start




                                      .c
             –   and it must be the last thread to finish

             –   since other threads are spawned or




                             DF
                 forked from the main thread.

     •   Threads may be implemented in two ways.
            – implement the Runnable interface
                    aP
            – extend the Thread class.

     •   The interface Runnable has the run method
         which has the prototype
                 vi

   public void run();

     •   There is no major difference between these two
         ee


         methods, since the Thread class extends Object
         and implements Runnable.
            – If the Thread object is created by
      n



                 passing it a Runnable object then the run
                 method of the Runnable object is
   w.




                 invoked.

             –   Else the run method of the thread class
ww




                 does nothing.




   CKR                   Java Notes                         138
•   Hence, in both cases, the run method must be




                                           om
         overridden.

     •   In both cases, the entry point for the thread is the
         run method.




                                      .c
     •   In both cases, one must create a Thread object.




                             DF
     •   The Thread class has several constructors.
         Some common constructors are given below.

   Thread();
                     aP
   Thread (Runnable, String);
   Thread (String)

     •   The String passed to Thread decides the name of
               vi

         the thread.
             – Two distinct threads can have the same
                 name.
         ee


             – Or a thread may not have a name
             – (the system will provide an internal name)
      n



     •   The Runnable object passed to the Thread
         decides the run method which will be invoked.
   w.




     •   After the Thread is created one must explicitly
         call its start method, upon which the JVM will call
ww




         the Thread’s run method.




   CKR                   Java Notes                      139
Program 30




                                  om
   class MyThread implements Runnable
   {
      Thread t; //instantiate Thread
      MyThread(int id)//define constructor
      {




                                  .c
         String myThreadName = new String
              (“mythread” + id);




                        DF
         t = new Thread (this, myThreadName);

     System.out.println (“Child thread"+
             “starting” + t);
                  aP
        t.start();
        //New thread must be explicitly started
        }
              vi

         public void run() //start calls run
         {
            try
         ee


            {
               for (int i=0; i<10; i++)
               {
      n



            System.out.println (“Child awake: ”+ i);
               t.sleep(100); //sleep for 100 ms
   w.




         //method sleep throws InterruptedException
               }
            } catch (InterruptedException e)
ww




            {
         System.out.println (“Child interrupted”);
            }


   CKR               Java Notes             140
om
             System.out.println (“Child thread done”);
         }
     }

     public class ThreadMain




                                   .c
     {
        public static void main (String args[])




                         DF
        {
           //get a reference to the main thread
           //currentThread is a static method of
           //the Thread class
                   aP
           Thread t = Thread.currentThread();
           System.out.println (“Started ” + t);

             //start two new threads
               vi

             MyThread n1 = new MyThread (1);
             MyThread n2 = new MyThread (2);
         ee


           try
           {
              for (int i=10; i>0; i—)
      n



   System.out.println (“Main thread going to”
                         + “sleep ” + i);
   w.




        //sleep is a static method
        //the second argument is nanosecond!
        Thread.sleep(2000, 2);
ww




        //if 2000 is changed a deadlock may result
           } catch (InterruptedException e)
           {


   CKR                Java Notes               141
System.out.println (“Main thread




                                         om
   interrupted”);
           }
           System.out.println (“Main thread done”);
        }
      }




                                     .c
                            DF
     •   Output:
         Started Thread [main, 5, main]
         Child thread starting Thread [mythread1, 5, main]
         Child thread starting Thread [mythread2, 5, main]
                    aP
         Child awake: 0
         Main thread going to sleep 10
         Main thread going to sleep 9
         Main thread going to sleep 8
               vi

         Main thread going to sleep 7
         Main thread going to sleep 6
         Main thread going to sleep 5
         ee


         Child awake: 0
         Main thread going to sleep 4
         Main thread going to sleep 3
      n



         Main thread going to sleep 2
         Main thread going to sleep 1
   w.




         Child awake: 1
         Child awake: 1
         ...
ww




         Child thread done
         Child thread done
         Main thread done


   CKR                  Java Notes                     142
Threads (contd)




                                          om
     •    In the above, the synchronization between the
          main thread and the child threads is dicey.




                                      .c
     •    This has been accomplished by putting the main
          thread to sleep for a longer time.




                             DF
     •    To ensure more reliable synchronization, we use
          the join method.

     •    The join method is the opposite of fork.
                     aP
             – the child threads were forked from the
                  main thread,
             – the thread which calls join() waits until
                  the other thread joins it (i.e., dies)
                vi

     •   To use this method, add the following code, and
         reduce the sleeping time of the main method)
         ee


   //improved synchronization
   System.out.println (
   “Main waiting for children to finish”);
      n



    try{
      n1.t.join();
   w.




      n2.t.join();
      } catch (InterruptedException e)
      { System.out.println (
ww




   “Child thread interrupted”);
      }
   System.out.println (“Main thread done”);


   CKR                   Java Notes                       143
Threaded applets




                                         om
     •   Threaded applets can be created in exactly the
         same way.




                                      .c
     •   A threaded applet will extend Applet and
         implement Runnable.




                            DF
      •  An example is given below.
    Program 31
   //A parametrized banner
                      aP
   import java.awt.*;
   import java.applet.*;

   /*
               vi

   applet code="Parmc" width = 300 height = 50
   param name=message value="Time never
   stops!"
         ee


   param name=fontName value="Times New Roman"
   param name=fontSize value="18"
   /applet
      n



   */
   w.




   public class Parmc extends Applet
   implements Runnable
   {
ww




      String msg;
      String fN;
      int fS;


   CKR                  Java Notes                    144
Font f;




                                  om
     Thread t = null;

     //Set colors and initialize thread

      public void init()




                                  .c
      {
         setBackground (Color.cyan);




                        DF
         setForeground (Color.red);
         f=new Font (“Courier”, Font.PLAIN, 12);
   //Create space for font
         setFont (f); //set new font.
                  aP
         t = new Thread (this); //create new thread
         t.start(); //start thread running
         t.suspend();
   //Suspend until applet fully initialized
              vi

   //this is the old suspend method now
   //deprecated.
      }
         ee


      public void start()
      {
      n



         String param;
         msg = getParameter (“message”);
   w.




         if (msg == null) msg = “Message not
   found.”;
         msg = “ ”+ msg + “ ”;
ww




         fN = getParameter (“fontName”);
         if (fN == null )


   CKR               Java Notes                145
fN = “Courier”;




                                   om
         param = getParameter (“fontSize”);
            try
            {
               if (param!= null )




                                   .c
                     fS = Integer.parseInt (param);
               else




                         DF
                    fS = 12;
            } catch (NumberFormatException e)
               {
                                       fS = -1;
                  aP
               }
         f = new Font (fN, Font.PLAIN, fS);
         setFont (f);
         t.resume();
              vi

     }

      //Entry point for the thread that runs the
         ee


   banner.

     public void run()
      n



     {
        char ch;
   w.




         //Displays banner until stopped
ww




         for (; ; )
         {
            try


   CKR                Java Notes             146
{




                                   om
                repaint();
                Thread.sleep (500);
                ch = msg.charAt(0);
                msg = msg.substring (1, msg.length());
                msg += ch;




                                   .c
             } catch (InterruptedException e)
             {




                         DF
             }

         }
                   aP
     }

     //Pause the Banner
                 vi

     public void stop()
     {
        t.suspend();
         ee


     }r

     //Kill thread when applet is terminated
      n




     public void destroy()
   w.




     {
        if (t != null)
        {
ww




           t.stop();
           t = null;
        }


   CKR                Java Notes             147
}




                                  om
       //Display the banner

       public void paint (Graphics screen)
       {




                                  .c
          screen.drawString (msg, 50, 30);
       }




                        DF
   }
                  aP
              vi
      n    ee
   w.
ww




   CKR               Java Notes              148
Thread priorities




                                            om
      •   Threads can have different priorities on a scale
          of 1-10.




                                       .c
      •   The average thread has a priority of 5.

      •   Technically, the priority scale ranges from




                              DF
          MIN_PRIORITY to MAX_PRIORITY, which
          numbers are currently 1 and 10 respectively.
              – The average priority is defined by the
                   number NORM_PRIORITY.
                       aP
              – These numbers are defined as final
                   variables in the Thread class
      •   When a thread is created, its priority is set equal
          to the priority of the thread which created it.
                  vi

      •   Thread priority may be determined or changed
          using the methods
          ee


   final void setPriority ( int P_level)
   final int getPriority ()
      n




              –   p_level must be an int in the priority
   w.




                  scale of 1-10.
              –   The actual priority set will the minimum
                  of p_level and the priority of the calling
ww




                  thread.




   CKR                    Java Notes                      149
Thread priorities (contd)




                                          om
      •   Thread priorities only provide a rough indication
          of how much time the thread will get.




                                       .c
      •   The same priority thread may get different
          amount of time slices from run to run.




                               DF
      •   These considerations are demonstrate by the
          following example program.

   class Ticker implements Runnable
                      aP
   {
      int tick = 0;
      Thread t;
      private volatile boolean isRunning = true;
                 vi

      //define constructor
      public Ticker (int p_level)
          ee


      {
         t = new Thread (this);
         t.setPriority(p_level);
      n



      }
   w.




      public void run()
      {
         while (isRunning)
ww




         {
            tick++;
         }


   CKR                    Java Notes                    150
}             The owner




                                      om
       Entry set void stop()
        public
                                         Wait set
        {
            isRunning = false;
        }




                                     .c
        public void start()




                           DF
        {
           t.start();
        }
   }
                     aP
   public class Priority
   {
      public static void main(String args[])
                 vi

      {
         Thread.currentThread().setPriority
            (Thread.MAX_PRIORITY);
            ee


         Ticker high = new Ticker
            (Thread.NORM_PRIORITY + 2);
         Ticker low = new Ticker
      n



            (Thread.NORM_PRIORITY - 2);
   w.




            high.start(); //call to thread.start()
            low.start(); //JVM will call run()
ww




            try
            {
               Thread.sleep (5000);


   CKR                  Java Notes              151
/*causes the thread to sleep (cease




                                           om
   execution)
           for the specified number of milliseconds*/
        } catch(InterruptedException e)
        /*Derived from Exception */
        {




                                     .c
           System.out.println("Main thread
   interrupted");




                            DF
        }
        int pLow = low.t.getPriority();
        int pHigh = high.t.getPriority();
        low.stop();
                    aP
        high.stop();

        try
        { /*wait for other threads to end*/
               vi

           high.t.join();
           low.t.join();
        } catch(InterruptedException e)
         ee


        {}
        System.out.println(pLow + " priority
   thread got: " + low.tick + " clock ticks");
      n



        System.out.println (pHigh + " priority
   thread got: " + high.tick + " clock
   w.




   ticks");
      }
   }
ww




     •   Output: varies from run to run.



   CKR                  Java Notes              152
ww




CKR
                w.
                   nee
                       vi
                         aP




Java Notes
                            DF
                                 .c
                                      om


153
Thread synchronization




                                          om
     •   Since it is not clear when the system will switch
         from executing one thread to executing another,
         various peculiarities may arise.




                                      .c
     •   Race conditions: Different threads may all
         manipulate the same object, and may race to




                            DF
         finish execution.

     •   To avoid this, Java has a synchronized
         statement.
                    aP
   synchronized (objectref) { /*Synchronized
   block*/ }
     •   Java’s synchronization model uses monitors to
         support two kinds of thread synchronization.
                 vi

             – mutual exclusion
             – cooperation
         ee


     •   Cooperation is achieved through inter-thread
         communication, using the
            – wait(), and
      n



            – notify()
            – notifyall()
   w.




   methods of Object, implemented as final methods.

             –   These methods can be called only within
ww




                 a synchronized block.
     •   Mutual exclusion is achieved through locks
         imposed by the JVM.


   CKR                   Java Notes                     154
Thread synchronization (contd)




                                           om
     •   A monitor is like
             – a building
             – which has a a special room (toilet?)




                                      .c
   Only one person can use the special room at a time.

     •   From the time the thread enters the special




                             DF
         room to the time it leaves the special room, it has
         exclusive access to the data in the room.

     •   Entering the building is called “entering the
                     aP
         monitor”.

     •   Entering the special room is called “acquiring
         the monitor”.
                vi

     •   Occupying the special room is called “owning
         the monitor”.
         ee


     •   Leaving the special room is called “releasing the
         monitor”.
      n




     •   Leaving the entire building is called “exiting the
   w.




         monitor”.

     •   A monitor is also associated with a bit of code
ww




         called a monitor region.
             – A monitor region is a code that is
                  executed as one indivisible operation.


   CKR                   Java Notes                        155
Thread synchronization (contd)




                                           om
     •   When one thread is executing a monitor region,
         associated with a given monitor, no other thread
         can execute any part of that region.




                                      .c
     •   A thread can only enter a monitor by arriving at
         the beginning of a monitor region, associated




                             DF
         with that monitor.

     •   At this point the thread is placed in the entry set
         for the associated monitor.
                     aP
     •   The only way a thread can move forward and
         execute the monitor region is by acquiring the
         monitor.
                vi

     •   If the monitor is not owned by any other thread,
         the thread can acquire the monitor, execute the
         ee


         monitor region, exit and release the monitor.

     •   If the monitor is currently owned by another
      n



         thread the given thread must wait, until that
         monitor is released.
   w.




     •   After that, it must compete with any other
         threads also waiting in the entry set.
ww




     •   Only one thread form the entry set will win the
         competition and acquire the monitor.


   CKR                   Java Notes                        156
•    While exclusion keeps threads from interfering




                                          om
         with one another, cooperation helps the threads
         to work towards a common goal.
             – e.g. a "read" thread which is reading
                 data from a buffer filled by a "write"
                 thread.




                                      .c
                            DF
                    aP
     Enter                            Release

              Acquire                 Acquire
               vi
         ee


                        Release &
                           Exit
      n




                         Waiting thread
   w.




                          Active thread
ww




   CKR                   Java Notes                   157
Thread synchronization (contd)




                                           om
     •   The JVM uses a "wait and notify" model of
         cooperation.




                                      .c
     •   A thread that currently owns a monitor
         voluntarily relinquishes it by executing a wait()
         command.




                             DF
     •   The thread will stay suspended, in the wait set,
         until after another thread executes a notify
         command.
                     aP
     •   The thread issuing the notify command
         continues to own the monitor, until it releases
         the monitor of its own accord.
                vi

     •   A waiting thread can optionally issue a timeout
         to the JVM.
         ee


     •   At the end of the timeout, even if no other thread
         notifies it, it will be automatically resurrected by
      n



         a notify message from the JVM.
   w.




     •   JVM implementers are free to make FIFO or LIFO
         queues or some more complex orderings to
         decide which of the waiting threads will acquire
ww




         the monitor.
     •   Thus, e.g. use notifyall() rather than notify() for
         there may be more than one thread waiting.


   CKR                   Java Notes                        158
Thread synchronization (contd.)




                                           om
     •    The JVM coordinates multithreaded access to
          two kinds of data:
             – Instance variables




                                       .c
             – Class variable

     •    The JVM does NOT coordinate access to local




                             DF
          variables which reside on the stack and are
          private to the thread to which the stack belongs.

     •    Every object and every class is associated with a
                     aP
          monitor.
              – For classes, the monitor protects the
                  class variables.
              – For objects, the monitor protects the
                vi

                  instance variables.
     •    To implement mutual exclusion, the JVM
          associates a lock with each object and class.
         ee


     •    A single thread is permitted to lock an object any
          number of times.
      n



              – In that case the object must be unlocked
                  as many times for it to be released.
   w.




     •    Programmers however need be concerned only
          with the synchronized statement.
ww




   CKR                    Java Notes                     159
•   These considerations are illustrated by the




                                         om
         following sample program .


   /*Aim: To illustrate the
   asynchronous operation of threads.




                                     .c
   One thread attempts to update data in
   the same object from which another thread




                            DF
   is trying to retrieve data. This may
   result in garbled output, which varies
   from run to run. */
                    aP
   class Student
   {
      String name;//class Student has two data
      int marks; //members which can be updated
               vi

              //or printed.

     Student (String n, int m)
         ee


     {
        name = n;
        marks = m;
      n



     }
   w.




     void Update (String n, int m)
     {
        name = n;
ww




        /*after doing the above suppose
        the thread is descheduled.
        To simulate this, we artificially


   CKR                  Java Notes                     160
put the thread to sleep. */




                                    om
           try
           {
              Thread.sleep (1000);
           } catch (InterruptedException e){}
           /*The thread now resumes*/




                                    .c
           marks = m;
       }




                          DF
       void Print ()
       {
          System.out.println ( name);
                    aP
          /*after doing the above suppose
          the thread is descheduled.
          To simulate this, we artificially
          put the thread to sleep. */
                vi

          try
          {
             Thread.sleep (1000);
           ee


          } catch (InterruptedException e){}
          /*The thread now resumes*/
          System.out.println (" " + marks);
      n
   w.




       }
   }
ww




   class Interact implements Runnable

   {


   CKR                 Java Notes               161
Student s;




                                 om
      Thread t;
      int iType;
      int newMarks = 0;
      String newName;
      Interact (Student std, int i) //define




                                 .c
   constructor
      {




                       DF
         s = std;
         iType = i;
         newName=" ";
         t = new Thread (this);
                 aP
         t.start();
      }

      Interact (Student std, int i, String str,
             vi

   int m)
      { //define a second construtor
         s = std;
         ee


         iType = i;
         newName = str;
         newMarks = m;
      n



        t = new Thread (this);
        t.start();
   w.




      }
ww




   CKR              Java Notes             162
public void run()




                                  om
      { //either update or print
         switch (iType)
         {
            case 1: s.Print();
               break;




                                 .c
            case 2: s.Update (newName, newMarks);
               break;




                       DF
            default: break;
         }
      }
   }
                 aP
   public class Async
   {
      public static void main(String args[])
             vi

      {
         Student s = new Student ("Ram" , 40);
         Interact i1 =new Interact (s, 2, "Shyam",
           ee


   50);
         Interact i2 = new Interact (s, 1);
         try
      n



         { //wait for threads to finish
            i1.t.join();
   w.




            i2.t.join();
         } catch (InterruptedException e){}
ww




       }
   }



   CKR              Java Notes              163
/*Possible output: Shyam




                                          om
        40
   Note: Output may vary from run to run
   */
      •  Only two changes are needed in the preceding
         program.




                                      .c
     •   The method run should be synchronized on the




                            DF
         student object, as follows.

     •   1. Change the run function
                    aP
   public void run()
   {
        synchronized (s)                            {
               switch (iType)
               vi

               { //...
               }
        }
         ee


          }
     •   2. Change the name of the class to SyncAsync
      n



     •   In this case the output is not jumbled up.
   w.




     •   3. To experiment further, change the thread
         priorities, as in the following sample program.
     •
ww




   /*Aim: To illustrate how threads may be
   synchronized. In the earlier code
   Async.java


   CKR                   Java Notes                        164
one thread attempted to update data in




                                 om
   the same object from which another thread
   was trying to retrieve data. This sometimes
   resulted in garbled output, which varied
   from run to run. The present code changes
   this by using synchronization. The earlier




                                 .c
   code
   is changed in just two places*/




                       DF
   class Student
   {
      String name;//class Student has two data
                 aP
      int marks; //members which can be updated
           //or printed.

     Student (String n, int m)
             vi

     {
        name = n;
        marks = m;
         ee


     }

     void Update (String n, int m)
      n



     {
        name = n;
   w.




        /*after doing the above suppose
        the thread is descheduled.
        To simulate this, we artificially
ww




        put the thread to sleep. */
        try
        {


   CKR              Java Notes              165
Thread.sleep (1000);




                                    om
           } catch (InterruptedException e){}
           /*The thread now resumes*/
           marks = m;
       }




                                    .c
       void Print ()
       {




                          DF
          System.out.println ( name);
          /*after doing the above suppose
          the thread is descheduled.
          To simulate this, we artificially
                    aP
          put the thread to sleep. */
          try
          {
             Thread.sleep (1000);
                vi

          } catch (InterruptedException e){}
          /*The thread now resumes*/
          System.out.println (" " + marks);
           ee



       }
      n



   }
   w.




   class Interact implements Runnable

   {
ww




       Student s;
       Thread t;
       int iType;


   CKR                 Java Notes               166
int newMarks = 0;




                                 om
      String newName;
      Interact (Student std, int i) //define
   constructor
      {
         s = std;




                                 .c
         iType = i;
         newName=" ";




                       DF
         t = new Thread (this);
         t.setPriority (4);
         t.start();
      }
                 aP
      Interact (Student std, int i, String str,
   int m)
      { //define a second construtor
             vi

         s = std;
         iType = i;
         newName = str;
         ee


         newMarks = m;
        t = new Thread (this);
        t.setPriority(1);
      n



        t.start();
      }
   w.




      public void run()
ww




      { //either update or print
      synchronized (s) /*1. operation on s is
   synchronized*/


   CKR              Java Notes             167
{




                                    om
           switch (iType)
           {
              case 1: s.Print();
                 break;
              case 2: s.Update (newName, newMarks);




                                    .c
                 break;
              default: break;




                          DF
           }
       }
       }
   }
                    aP
   public class SyncAsync /*2. Name of the
   class is changed*/
   {
                vi

      public static void main(String args[])
      {
         Student s = new Student ("Ram" , 40);
           ee


         Interact i1 =new Interact (s, 2, "Shyam",
   50);
         Interact i2 = new Interact (s, 1);
      n



         try
         { //wait for threads to finish
   w.




            i1.t.join();
            i2.t.join();
         } catch (InterruptedException e){}
ww




      }
   }



   CKR                 Java Notes             168
•    Output: Ram




                                         om
            40
    •    Note: Output may vary from run to run, and with
         thread priorities, but the output will be either
         Ram 40 or Shyam 50.




                                     .c
                            DF
                    aP
               vi
      n  ee
   w.
ww




   CKR                  Java Notes                     169
i/0: Streams and Files in C




                                           om
      •   We recollect that C uses the two abstractions
             – streams, and
             – files




                                       .c
      •   C was developed in the context of Unix, and in
          Unix everything is a file: console, keyboard, disk




                                 DF
          files, tape drives etc.

      •   A stream provides a level of abstraction between
          the programmer and the physical device, viz. file.
                      aP
          (i.e., represented by the file abstraction).

      •   There are two kinds of streams
             – text streams
                  vi

             – binary streams

      •   A text stream is a sequence of characters.
          ee


              – text streams are organized into lines
                   separated by the newline character.
      n



              –   in a text stream certain character
                  translations may occur as required by
   w.




                  the host environment, e.g.

              –   a newline may be converted to a carriage
ww




                  return/linefeed pair on a printer.




   CKR                    Java Notes                      170
–    Thus, there is NOT a on-to-one




                                          om
                 relationship between the characters that
                 are read (or written) to a text stream, and
                 the characters stored on the external
                 device.




                                      .c
    •    A binary stream is a sequence of bytes
             – no character translations are permitted




                                DF
                 in a binary stream.

    •    Hence in a binary stream there is a one to one
         correspondence between
                     aP
            – the characters written to the stream, and

            –    the characters stored in the external
                 device.
                vi

            –    However, an implementation dependent
                 number of null bytes may be appended
         ee


                 to the end of a binary stream, to fill up
                 the sectors on a disk, for example.
      n



    •    Correspondingly there are two types of files
   w.




            –    text files, and

            –    binary files
ww




   CKR                   Java Notes                      171
•    A file may be any device




                                            om
              – a terminal
              – a keyboard
              – a printer

    •    Streams are associated with files by performing




                                      .c
         an open operation.




                             DF
    •    Streams are dissociated with files by performing
         a close operation.

    •    While all streams are the same, all files are not.
                     aP
            – A disk file can support random access.
            – A printer typically cannot.

    •    Certain types of files (e.g. disk files) may support
               vi

         position requests
            – Opening such a file also initializes the
                 file position indicator to the beginning of
         ee


                 the file.

    •    Files are represented in a C program by a FILE
      n



         structure.
               – A FILE * variable is called a file pointer.
   w.




    •    Streams may contain a buffer, which stores
         characters before they are actually written to a
         file.
ww




               – Such buffers improve execution speed.
               – writing the buffer is called flushing.



   CKR                   Java Notes                       172
C-style i/o: standard streams




                                           om
     •    Whenever a program starts, it usually needs to
          be able to
              – input data from the keyboard




                                       .c
              – output data to the screen
              – inform the user of some error conditions.




                             DF
     •    Accordingly, three predefined streams are
          available, to any program
             – stdin (keyboard)
             – stdout (screen)
                      aP
             – stderr (screen)

     •    stdin is the standard input device, usually
          connected to the keyboard.
                  vi

              – remember this is a file which has to be
                   opened.
         ee


              –   The availability of this predefined stream
                  means that the programmer does not
                  have to do this manually,.
      n




              –however, input may be redirected and
   w.




               taken from a disk file, using <
   myprogram < myfile
           – This may be achieved since the
ww




               programmer is dealing with an
               abstraction.



   CKR                    Java Notes                     173
C-style i/o (contd)




                                            om
      •  stdout is the standard output device, usually the
         screen
            – however, output may be redirected to a




                                       .c
                 disk file using >
   myprogram > myfile




                              DF
      •   stderr is usually the screen.

      •   File i/o is not fundamentally different from
          console i/o.
                         aP
      •   The only difference is that a file pointer must be
          available for file i/o.
                 vi

      •   This file pointer can be obtained by means of a
          file open call as in the program above, using the
          open function, and
          ee


               – supplying a file name
               – supplying an open mode
      n



   FILE * DataFile = fopen(szFileName,
   szMode);
   w.




      •   The open mode can be
             – r (read)
ww




             – w (write)
             – a (append)
             – rb (open binary file for reading) etc.


   CKR                    Java Notes                      174
C file i/o




                                             om
      •     One difference between console i/o and file i/o is
            that diskfiles support random access i/o, and
            hence indicate position in the file.




                                         .c
      •     This is accomplished by using the function fseek
            which has the prototype




                               DF
   int fseek (FILE *fp, long numbytes, int
   whence);
                        aP
      •     The fseek function takes three parameters
               – FILE *fp (the file pointer returned by the
                    call to fopen
                    vi

                –   numbytes indicates the number of bytes
                    to move
           ee


                –   whence is the position indicator, and
                    could be
                –   SEEK_SET (0) Beginning of file
      n



                –   SEEK_CUR (1) Current position
                –   SEEK_END (2) End of file.
   w.




      •  To seek the nth item of a data which set
         numbytes to n*sizeof(datatype) in a binary file.
ww




     •   stdout can be internally redirected by using
    freopen(const char* filename, , const
   char* mode, FILE *stream)


   CKR                      Java Notes                      175
om
      •    if one is at the end of the file, one should use
   rewind()
   to return to the beginning of the file.

      •  To know one’s current position in the file, one




                                          .c
         uses the function ftell(), which has the prototype
   long ftell (FILE *fp);




                                DF
      •   For formatted file i/o one uses the functions
             –    fprintf()
             –    fscanf()
                       aP
      •   In addition to
              – console i/o, and
              – file i/o
                  vi

   C supports a third form of i/o
      •  character array based i/o
          ee


              –    where reading and writing can be done
                   to a character array in memory.
      n




              –    this uses the family of functions
   w.




                   beginning with s, e.g.

              –    sprintf
ww




              –    sscanf
              –    etc.



   CKR                       Java Notes                       176
i/o (contd.) : Difference between text and binary streams




                                           om
     •    The following example demonstrates some of
          these concepts.
    Program 32




                                       .c
   /* TXTFILE.c
     * This program demonstrates how text and
   *    binary files




                              DF
     * differ
     */

   #include <stdio.h>
                      aP
   #include <string.h>
   /* For string functions */
   #include <conio.h>
   /* For console getch(), getche(), etc. */
                 vi

   #include <ctype.h>   /*For
   character-conversion functions tolower() */
          ee


   #define MAX_LINES         25
   #define MAX_LENGTH        80
      n



   char     szSaying[MAX_LINES][MAX_LENGTH] =
        { /*ALL strings below should be coded to fit into
   w.




   one line AND padded to cover 64 characters*/
   “nFirestone’s Law of Forecasting:                 n",
   “n Chicken Little has to be right only once.      n”,
   “n
ww




   nn”,
   “nManly’s Maxim:
   n”,
   “n Logic is a systematic method of coming to      n”,


   CKR                    Java Notes                     177
“n the wrong conclusion with confidence.         n”,




                                         om
   “n
   nn”,

   “nMoer’s truism:
   n”,
   “n The trouble with most jobs is the job holder’sn”,




                                      .c
   “n resemblance to being one of a sled dog team. No
   one         n”,
   “n gets a change of scenery except the lead dog.




                            DF
   n”,
   “n
   nn”,
   “nCannon’s Comment:
   n”,
   “n If you tell the boss you were late for work
                     aP
   because you     n”,
   “n had a flat tire, the next morning you will have a
   flat tire.n”,
   “n
   nn”,
                vi

       };
          ee


   int main(void);
      n



   int main()
   w.




   {

   FILE      *DataFile = NULL;
ww




   char    szFileName[25];
      /*string to hold filename*/


   CKR                   Java Notes                   178
char    szMode[5] = “w00";




                                   om
      /*to hold file mode*/

   int       i;
   int       nNumberRecords = 0;
   int       nRecord = 0;




                                   .c
   int       nResult = 0;r




                         DF
   long      lNewPosition = 0;
   long      lOldPosition = 0;

   /* Prompt the user to supply the mode,
                   aP
     * either lowercase t
     * for a text file or lowercase b for a
     * binary file.
   */
               vi

         while (DataFile == NULL)
         {
          ee


        while(szMode[1] != ’b’ && szMode[1] != ’t’)
             {
        printf(”nEnter ’t’ for text file,
      n



                "’b’ for binary: “);
        szMode[1] = tolower(getche());
   w.




             }

      printf(
ww




   ”nEnter the name of file to write: “);
           gets(szFileName);
      if ((DataFile = fopen(szFileName,


   CKR                Java Notes             179
szMode))==NULL)




                                      om
           {
   printf(”n ERROR: opening file ’%s’.n",
              szFileName);
           }
       }




                                      .c
    printf(“n”);




                            DF
   switch(szMode[1])
       {
            case ’t’:
         printf(“This is a text filenn”);
                      aP
               break;

                case ’b’:
             printf(“This is a binary filenn”);
                  vi

                   break;
         }
             ee


      for (i = 0; strlen(szSaying[i]); i++)
      {
     lOldPosition = ftell(DataFile);
      n



        /*store current file position*/
   w.




      fwrite(szSaying[i],
      /*Saying number to write*/
         strlen(szSaying[i]),
ww




   /*size (in bytes) to write*/
         1, /*No of items of above size to write*/
         DataFile); /*where to write*/


   CKR                   Java Notes             180
lNewPosition = ftell(DataFile);




                                      om
   /*get new file position*/

            printf(
                “Start position %5ld ”
                “end %5ld, ”




                                      .c
                “strlen(...) %d but ”
                “wrote %5ld bytes’n”,




                            DF
         lOldPosition, /*start position*/
         lNewPosition, /*end position*/
         strlen(szSaying[i]), /*string length*/
         (long)lNewPosition - lOldPosition); /*file
                   aP
   position change*/
       }

         fclose(DataFile);
               vi

         printf(“n”);
          ee


         switch(szMode[1])
         {
              case ’t’:
      n



           printf(“Note the bytes written do NOT”
           “ equal the string lengthnn”);
   w.




                                       break;

             case ’b’:
ww




          printf(“Note the bytes written DO”
          “ equal the string lengthnn”);
                                      break;


   CKR                   Java Notes            181
}




                                           om
       getch();
        return (0);
   }
       •   Input: t
       •   output: Bytes written do not match string length




                                       .c
       •   Input b




                              DF
       •   Output: Bytes written match string length
                      aP
                 vi
      n    ee
   w.
ww




   CKR                    Java Notes                     182
Java i/o




                                             om
      •   Java i/o resembles C i/o.

      •   The key difference is that Java is designed to be




                                        .c
          completely object-oriented, so that
             – Java i/o is object oriented.




                              DF
      •   This is achieved through wrapper classes.

      •   Wrapper classes have been created for
             – streams
                      aP
             – files
             – data types

      •   This has the effect of making Java i/o somewhat
                vi

          complicated.
             – This complication may be unavoidable, if
                  the aim is to have platform
          ee


                  independence rather than merely
                  portability.
      n



      •   Java i/o is internally byte-oriented.
   w.




      •   However, classes are provided to support
          character streams.
ww




   CKR                     Java Notes                    183
Predefined Streams




                                            om
     •   The three standard predefined streams of C
            – stdin
            – stdout




                                       .c
            – stderr

     •   are available in Java as the three members of the




                             DF
         static System class
             – in
             – out
             – err
                     aP
     •   The System class cannot be instantiated since it
         has a private constructor.
                vi

     •   However, it is a static class, so we can refer to its
         members simply by using the class name.
         ee


     •   Thus, instead of stdin, stdout, stderr we
         respectively use
      n



            –    System.in
            –    System.out
   w.




            –    System.err
ww




   CKR                    Java Notes                       184
Byte and Character i/o




                                          om
     •    In C there are two types of streams
              – binary
              – character




                                         .c
     •    Correspondingly, Java has two types of i/o
          classes




                               DF
              – byte oriented i/o classes
              – character-oriented i/o classes

     •    Additional complications are introduced by the
                     aP
          need for
             – Unicode characters
             – platform independence
                 vi

     •    The byte-stream oriented class hierarchy begins
          with two abstract classes
         ee


             –    InputStream
             –    OutputStream
      n



     •    The character-stream oriented class hierarchy
          also begins with two abstract classes
   w.




             –    Reader
             –    Writer
ww




     •    These classes define basic methods such as
          read() and write().


   CKR                      Java Notes                    185
Java Character i/o: Input




                                           om
     •    Since Reader and Writer are abstract classes, we
          need to use subclasses which implement all their
          methods.




                                       .c
     •   To Read a character we need to use the class
   InputStreamReader




                               DF
     •    The InputStreamReader class converts bytes to
          characters.
                      aP
     •   However, since i/o access is time-consuming, to
         improve efficiency, we should use the
         InputStreamReader class in combination with a
         class which provides a buffer. Such a class is
                 vi

         the class
   BufferedReader
          ee


     •   The BufferedReader class is a direct subclass of
         Reader. It has two constructors
   BufferedReader (Reader in)
      n



   BufferedReader (Reader in, int buff_size)
   w.




     •    Since Reader is an abstract class, we cannot
          instantiate it. So how do we get a reference to a
          Reader type ?
ww




   CKR                    Java Notes                     186
•   To get a reference to a Reader type, we use, the




                                          om
         InputStreamReader, which is also a direct
         subclass of the class Reader.
             – Hence an object of type
                 InputStreamReader can be used as a
                 reference to a Reader type.




                                      .c
     •   The InputStreamReader has two constructors:




                            DF
   InputStreamReader (InputStream in)
   InputStreamReader (InputStream in,
               String encoding)
                    aP
     •   The second construtor specifies the name of the
         character encoding to be used.

     •   For the default encoding, we use only the first
               vi

         constructor.

     •   Since InputStream is also an abstract class, how
         ee


         do we get a reference to an InputStream type?

     •   For this we can use
      n



            –      either a concrete subclass of
                  InputStream, or
   w.




            – System.in (which is a reference of type
                  InputStream)
ww




   CKR                   Java Notes                        187
Reading a character




                                             om
     •    With all this wrapping, we can finally read a
          single character using Java!




                                        .c
     •    Step 1: Create a new BufferedReader

   BufferedReader br = new BufferedReader




                              DF
   (new InputStreamReader (System.in) );

     •    Step 2: Read a character using the newly created
          br object and the read() method of the
                      aP
          BufferedReader class.
              – One form of read() reads a single
                  character, and returns an int.
              – This int must be typecast to char.
                 vi

   char c = (char) br.read();
         ee


     •   We can check the input, by printing it, using a
         call to the println() method of the System class.
   System.out.println(c);
      n




     •    Note: Unlike the getch() function, and like the
   w.




          getchar() function, since System.in is line
          buffered, no input is actually passed to it, until a
          carriage return is pressed. The call to println()
ww




          places a carriage return and flushes the buffers.




   CKR                     Java Notes                       188
Reading a string




                                            om
      •   To read an entire string, use the readln() method
          of the BufferedReader class.
              – The readln() method throws an




                                       .c
                  IOException (which is a checked
                  exception).




                              DF
      •  To adjust the efficiency manually, we can
         explicitly specify the size of the buffer, by using
         the second form of the constructor
   BufferedReader(Reader in , int buff_size);
                       aP
   Output to console

      •   For output to console, we have been using the
                 vi

          out member of the System class.
          ee


      •   The out and err members are of type
          PrintStream.
             – PrintStream is a character-based output
                 class.
      n



             – It converts its byte- arguments to 8-bit
                 ASCII Representations.
   w.




             – The constructor for this class is
                 deprecated in JDK 1.2
             – Thus, one should avoid constructing
ww




                 new PrintStream objects.




   CKR                    Java Notes                      189
Output to Console




                                             om
     •   The alternative is to use the PrintWriter class,
         which directly subclasses Writer, and converts
         its arguments to 16-bit Unicode representation.




                                       .c
     •   The Printwriter class supports output for all
         primitive data types (and even Object), and it can




                              DF
         be used exactly like System.out.

     •   The constructor for Printwriter requires a
         reference to either
                       aP
             – OutputStream, or
             – Writer
     •   In addition, a second boolean parameter may be
         supplied . If set to true, this will flush buffers on a
                vi

         call to a println() method.

     •   E.g.
         ee


   PrintWriter (OutputStream out, boolean
   flush);
     •   Since PrintStream is a subclass of
      n



         OutputStream, we can use the System.out for
         a reference to OutputStream.
   w.




     •   Note: In PrintWriter, unlike PrintStream, the
         buffer will NOT be flushed on newline, but only
ww




         on use of a println method.
             – Error in Java 2 Complete Reference, p
                 323.


   CKR                    Java Notes                        190
•  These considerations are illustrated by the




                                         om
        following program.
   Program 33

   //java i/o supports both byte and char
   //streams, though the i/o is primarily




                                     .c
   //byte based.
   //character streams are supported by the




                            DF
   //abstract Reader class
   //which has a concrete subclass
   //InputStreamReader
   //and BufferedReader
                    aP
   //Output is preferably done via the
   //PrintWriter class rather than a
   //call to System
               vi

   import java.io.*;
   public class TestIO
   {
         ee


      public static void main (String args[])
            throws IOException
      {     //Creating a BufferedReader object
      n



         BufferedReader br = new BufferedReader
            (new InputStreamReader (System.in));
   w.




         //Creating a PrintWriter object
         //The second parameter indicates whether
   line     //is to be flushed on encountering n
ww




         PrintWriter pw = new PrintWriter
   (System.out, true);
         pw.println ("Enter a character: ’q’ to


   CKR                  Java Notes                    191
quit");




                                         om
        char c;
        do {
        c = (char) br.read();
        pw.println (c);
        } while (c !=’q’);




                                     .c
        //Reading a string
        String str;




                            DF
        pw.println (
   "Enter a line of text or data");
        pw.println ("Enter ’end’ to quit");
              do {
                    aP
           str = br.readLine();
           pw.println (str);
           } while (!str.equals ("end"));
      }
               vi

      }

     •   Input: abcdq
         ee


     •   Output:
         a
         b
      n



         c
         d
   w.




     •   Input: The quick brown fox ... end
     •   Output:
         The quick brown fox ...
ww




   CKR                  Java Notes            192
File i/o




                                                om
      •   We see that the Java philosophy is to separate
              – byte streams and
              – character streams




                                           .c
   into two separate class hierarchies, starting from
              – InputStream, OutputSream
              – Reader, Writer




                                  DF
      •       Similarly, for stream-based file i/o, Java provides
              two sets of classes.
                 – FileInputStream, FileOutputStream
                          aP
                 – FileReader, FileWriter

      •  All these classes have constructors which take
         the filename (inclusive of full path) as a String
                    vi

   FileInputStream(String fileName)
   FileoutputStream (String fileName)
   FileReader (String fileName)
              ee


   FileWriter (String fileName)

      •  All the above constructors throw a FileNotFound
      n



         Exception, if the input file cannot be found or the
         output file cannot be created.
   w.




     •   If the output file exists it is overwritten. To avoid
         this one can use the alternative constructors
   FileOutputStream (String fileName, boolean
ww




   append)
   FileWriter (String fileName, boolean
   append)


   CKR                        Java Notes                      193
File i/o (contd)




                                   om
   Program 34

   /*Java file i/o may be done using the




                                   .c
   classes
   FileInputStream (String filename)
   FileOutputStream (String filename)




                         DF
   FileOutputStream (String filename, boolean
   append)
   all of which constructors throw a
   FileNotFoundException
                      aP
   */


   import java.io.*;
                  vi

   public class TestFileIO
   {
      public static void main(String args[])
          ee


         //throws IOException
      {
         if (args.length <= 1)
      n



         { System.out.println (
         "Usage: java TestFileIO fromFileName
   w.




   toFileName");
         return;
         }
ww




          FileInputStream fin;
          FileOutputStream fout;


   CKR                Java Notes            194
try




                                  om
         {
            fin = new FileInputStream (args[0]);
         } catch (FileNotFoundException e)
         {
         System.out.println ("Input file not" +




                                  .c
            "found");
         return;




                        DF
         }

         try
         {
                  aP
            fout = new FileOutputStream (args[1]);
         } catch (FileNotFoundException e)
         {
         System.out.println ("Error opening " +
              vi

            "output file");
         return;
         }
         ee


         catch (IOException e)
         {
            System.out.println ("Error opening "
      n



               "output file");
            return;
   w.




         }
         int i;
         try
ww




         {
            do
            {


   CKR               Java Notes             195
i = fin.read();




                                    om
                if (i!=-1) //if not end of file
                fout.write (i);
           /*Note: Only low-order 8 bits are written
           Thus above code works for text or binary.*/




                                    .c
           /* Print the same text to screen.*/
                  } while (i!= -1);




                          DF
           } catch (IOException e)
           {
               System.out.println ("Error reading or" +
                  "writing file");
                    aP
               //No return call here
             }
           finally {
               try
                vi

               {
               fin.close();
           ee


              fout.close();
              }
              catch (IOException e)
      n



              {
           System.out.println ("Error closing files");
   w.




              }
           }
       }
ww




   }




   CKR                 Java Notes              196
File i/o : Filename separators




                                            om
      •   In the above example program, the filenames
          were taken as parameters passed to the main
          method.




                                       .c
      •   What if one wants to specify the filename
          internally.




                              DF
      •   At this point the issue of platform independence
          again crops up.
              – Unix uses / as a file name separator
                      aP
              – DOS/Win use  as a file name separator
              – C uses  for escape characters (to
                   escape the ordinary meaning of a
                   character, e.g. n = newline)
                 vi

              – To print  one must use  in C.

      •   Thus, the preferred method is to use / or use  to
          ee


          specify the path.

      •   Java resolves this correctly, depending on the
      n



          system.
   w.




     •   E.g.
   FileReader = new FileReader
   ("C:mydirmyfile.ext");
ww




   FileWriter = new FileWriter
   ("C:mydiryourfile.ext", true);


   CKR                    Java Notes                       197
File i/o : Random Access Files




                                          om
     •    Finally, Java distinguishes completely between
          streams and random access files which support
          position requests.




                                      .c
     •    Thus, Java defines a class called
          RandomAccessFile




                             DF
             – which is NOT derived from
                  InputStream or OutputStream,
             – but is derived directly from Object
                     aP
   public class RandomAccessFile extends
   Object implements DataOutput DataInput

     •    DataInput and DataOutput are abstract interfaces
                vi

          which have methods to convert all of Java
          primitive data types from/to a sequence of bytes,
          and to read/write these to a binary stream .
         ee


     •   One constructor for this class is
   RandomAccessFile (String fileName, String
      n



           mode)
   w.




     •    Here mode must be either
             – "r" (for reading only) or
             – "rw" (both reading and writing)
ww




     •    The constructor throws a FileNotFound
          Exception, which is a subclass of IOException.


   CKR                   Java Notes                     198
File i/o: Random Access Files (contd.)




                                            om
     •    Additionally, the RandomAccessFile
          constructors may throw the following Exceptions




                                       .c
     •    IllegalArgumentException if the mode is
          anything other than "r" or "rw".




                              DF
     •    SecurityException if read/write permission for
          the file is not available (e.g. in Unix systems)

     •    These exceptions are unchecked exceptions, so
                      aP
          the programmer is not obliged to bother about
          them.

     •    A random access file is implicitly a large array of
                  vi

          bytes.
              – The position in this implicit array is given
                 by the file pointer.
          ee


              – To get the current position use the
                method (instead of tell)
      n



   long   getFilePointer();
   w.




              –    To set the current position use the
                   method
   void seek      (long pos);
ww




     •    As already stated, various methods are available
          for reading and writing the primitive data types.


   CKR                    Java Notes                     199
Program 35




                                    om
   import java.io.*;

   public class CompareFile
   {
      public static void main (String args [])




                                    .c
         throws IOException
      {




                          DF
         String s1 = "Files differ in size by : ";
         String s2 = "Files differ at offset: : ";
   /*Prepare initial string table */
                  aP
         if (args.length < 2)
         {
            System.out.println (
         "Usage: java CompareFile fromFileName "
              vi

               + "toFileName");
         return;
         }
         ee


         RandomAccessFile fFrom = new
            RandomAccessFile (args[0], "r");
      n



         RandomAccessFile fTo = new
            RandomAccessFile (args [1], "r");
   w.




         RandomAccessFile fRes = new
            RandomAccessFile ("c:kawaresult",
               "rw");
ww




         long fsize1 = fFrom.length();
         long fsize2 = fTo.length();


   CKR                 Java Notes           200
om
         int bufsize = (int) Math.min (fsize1,
               fsize2);
         int fmaxsize = (int) Math.max (fsize1,
            fsize2);




                                  .c
         System.out.println ("bufsize = " +
            bufsize);




                        DF
         System.out.println ("fmaxsize = " +
            fmaxsize);
         if (fsize1 != fsize2)
         {
                  aP
            fRes.writeChars (s1);
            fRes.writeInt ((fmaxsize - bufsize));
         }
              vi

         byte buf1 [] = new byte [bufsize];
         byte buf2 [] = new byte [bufsize];
         ee


      /*allocate buffers to hold files as
   byte-arrays in memory */
      n



         fFrom.readFully (buf1, 0, bufsize);
         fTo.readFully (buf2, 0, bufsize);
   w.




     /*args to readFully are buf, from, to */
ww




   CKR               Java Notes                201
for (int i=0; i bufsize; i++)




                                            om
           {
              if (buf1 [i] != buf2 [i])
              {
                 fRes.writeChars (s2);
                 fRes.writeInt (i);




                                        .c
                 //fRes.writeChars (s3);
              }




                              DF
           }
           fFrom.close();
           fTo.close();
                      aP
           long fp = fRes.getFilePointer();
           System.out.println ("Length of result = "
                + fp);
           /*1*/fRes.seek((long)2*s1.length());
                 vi

           fp = fRes.getFilePointer();
           System.out.println ("Currently at: "
                + fp);
           ee


           int i = fRes.readInt ();
           System.out.println (s1 + i);
      n



           fRes.close();
       }
   w.




   }

       •   Note: /*1*/ : s1.length() returns the number of
ww




           characters in the string s, but for position we
           need the number of bytes into the file, hence the
           factor of 2.


   CKR                     Java Notes                     202
File i/o: the File class




                                             om
      •    Somewhat like the File structure in C, Java has a
           File class.




                                           .c
      •    However, in Java, this class is used exclusively
             – to create files and directories,
             – to query and change their properties




                                 DF
      •    The File class does NOT incorporate any
           read/write methods.
                        aP
      •    As in Unix, a directory is simply a special type of
           file.

      •    The key issue is platform independence and the
                  vi

           matter of the separator character: / or 

      •    To achieve this, Java uses the notion of an
          ee


           abstract pathname. While pathname strings are
           system dependent, abstract pathnames are not.
      n



      •    An abstract pathname consists of
              – An optional prefix (such as / for root dir in
   w.




                   Unix or a drive specification
              – A sequence of zero or more String
                   names.
ww




      •    Each name, except the last must be a directory.
      •    The last can be either a directory or a file.



   CKR                        Java Notes                   203
File i/o: File class (contd)




                                             om
      •    The File class has three constructors:

   File (String pathname)




                                         .c
   File (File parent, String child)
   File (String parent, String child)




                                  DF
      •    It defines a variety of methods. All the following
           return a boolean value.
               – exists()
               – canRead()
                        aP
               – canWrite()
               – isDirectory()
               – isFile()
               – isHidden()
                  vi

               – isAbsolute()
               – delete()
               – setReadOnly
          ee


               – mkdir()
      •    The following method returns a URL
               – toURL() throws
      n



                    MalformedURLException
   w.




      •    For various other methods consult the
           documentation.
ww




      •    An example follows.




   CKR                      Java Notes                     204
Program 36




                                         om
   import java.io.*;

   public class FileDemo
   {
      public static void main (String args[])




                                         .c
      {
         if (args.length < 1)




                               DF
         {
         System.out.println
         ("Usage: FileDemo pathname/filename");
         return;
                        aP
         }
         File f = new File (args[0]);

          String   s1   =   f.exists() ? "Yes" : "No";
                vi

          String   s2   =   f.isFile() ? "Yes" : "No";
          String   s3   =   f.isDirectory ()? "yes" : "No";
          String   s4   =   f.canRead() ? "Yes" : "No";
          ee


          String   s5   =   f.isAbsolute() ? "Yes" : "No";

          System.out.println ("Exists            : "+s1);
      n



          System.out.println("Is File           : " + s2);
          System.out.println("Is Directory      : " + s3);
   w.




          System.out.println("Can Read          : " + s4);
          System.out.println("Is Absolute       : " + s5);
     }}
ww




     •    Input: experiment



   CKR                      Java Notes             205
Numeric i/o:Type Wrapper classes




                                          om
     •    apart from
             – character i/o and
             – byte i/o




                                      .c
   Java implements a third type of
             – object i/o
   which we shall not, however, examine here.




                            DF
     •   The above i/o techniques still do not tell us how
         to read a numeric value, such as an int or float.
                     aP
     •   For a language which claims to be simple,
         numeric i/o in Java is remarkably complex.

     •   Java follows the old C-method of doing things:
               vi

         to read and write numbers one must first convert
         them to strings.
         ee


     •   The programmer is expected to carry out these
         conversions explicitly.
      n



     •   To write a numeric value, we must first convert it
         to a string by concatenating using +
   w.




     •   To read a numeric value we must first read in a
         string and convert it to a numeric value by going
ww




         via type-wrapper classes.




   CKR                   Java Notes                     206
Numeric i/o and type-wrapper classes (contd)




                                         om
     •    The type wrapper classes wrap the primitive type
          into classes, so that they can be treated as
          objects.




                                      .c
     •    Some of the type wrapper classes are the
          following (note the capitals)




                            DF
              – Byte
              – Short
              – Integer
              – Long
                     aP
              – Float
              – Double

     •   All the above are derived by subclassing the
                vi

         abstract class
              – Number
   which subclasses Object.
         ee


     •    All the above types have constructors which take
          a string and return the wrapped object.
      n




     •    Alternatively, one may use the static member
   w.




          function
              – valueOf(String str) for Float etc.
              – parseInt(String str) for Integer.
ww




     •    Both the above methods may throw a
          NumberFormatException (which is derived from


   CKR                   Java Notes                      207
RunTimeException and so is unchecked).




                                            om
      •   All the above types have member functions
               – byteValue(), intValue(), floatValue() etc.
   which return the equivalent primitive type.




                                        .c
      •   These considerations are illustrated by the
          following program.




                              DF
   Program 37

   /*This program illustrates how data types
                      aP
   may be converted to and from strings
   this is a pre-requisite for i/o involving
   primitive datatypes.
                 vi

   For a language which claims to be simple
   i/o involving primitive data types
   is remarkably complex in Java.
          ee


   To convert from data type to string,
   use valueOf
      n



   (double/float/int/long/char/char[]/boolean/
   Object/...) .of the String class
   w.




   Note that the valueOf function of the
   Float class (or Number class) is
ww




   different.
   it returns a Float object. */



   CKR                     Java Notes                     208
/* Summary:




                                 om
   To read in an int, float etc. read in a
   string, convert the string to a wrapper
   class, and then extract the data type from
   the wrapper class.




                                 .c
   Step 1: Read in a string




                       DF
   Step 2: (String to Wrapper class)
   convert the string to a
   wrapper class by
   (a) passing the string to the
                 aP
   constructor of that wrapper class
   or
   (b) use the
   valueOf
             vi

   static member function
   of the corresponding class, for Float etc.
   and
         ee


   parseInt()
   for Integer.
      n



   Step 3: (Wrapper class to DataType)
   Extract the data type from
   w.




   the wrapper class by converting the wrapper
   class to the data type using
ww




   intValue()/floatValue()




   CKR              Java Notes             209
etc. member functions (abstract functions




                                   om
   of the
   Number class).
   There is also a

   booleanValue()




                                 .c
   function of




                        DF
   the Boolean class which subclasses Object.

   II. Datatype to String. For the reverse
   process use either
                    aP
   (a) concatenation with a string, using +,
    as in println
   or
   (b) convert datatype to a string, using
             vi

   the

   valueOf (datatype)
         ee


   function of the STRING class.
      n



   III. To convert Datatype to Wrapper class
   pass the datatype to the
   w.




   appropriate constructor of the Wrapper
   class.
ww




   IV. Wrapper class to String: e.g.
   go via datatype */



   CKR              Java Notes             210
import java.io.*;




                                  om
   public class Convert
   {
      public static void main (String args[])
            throws IOException
      {




                                  .c
         int myInt = 2;
         long myLong = 40000;




                        DF
         float myFloat = 2.01f;
         double myDouble = 2.01;
         byte myByte = 1;
         boolean myBoolean = true;
                  aP
         BufferedReader br = new BufferedReader
               (new InputStreamReader (System.in));
         String str;
               vi

        System.out.println ("Enter a line of text"
   + "or data");
        System.out.println ("Enter ’stop’ to" +
         ee


   "quit");

         do {
      n



         //Step 1: Read in string.
            str = br.readLine();
   w.




         // System.out.println (str);

         //Step 2: Convert the String to a
ww




         //wrapper class.

         try


   CKR               Java Notes              211
{




                                   om
           Integer myInteger = new Integer (str);
        /*Or
   Integer myInteger = Integer.parseInt
   (str); */
        //Step 3: Convert the wrapper class to int




                                   .c
           myInt = myInteger.intValue();




                         DF
   //Step 4: Convert the int to a string to
   //print

           System.out.println (" " + myInt);
                   aP
        } catch (NumberFormatException e)
        {
           System.out.println ("Could not convert
   string to Integer");
               vi

        }

             } while (!str.equals ("stop"));
         ee


     }
     }
      n
   w.
ww




   CKR                Java Notes               212
Servlets




                                            om
     •    A servlet is to a server what an applet is to a
          browser.




                                       .c
              –   A servlet may be almost thought of as
                  an applet which runs on a web server.




                              DF
     •    Formally, a servlet is a body of Java code that
          runs inside a network service, such as a web
          server.
                      aP
     •    A servlet helps to build interactive web based
          applications

              –   by receiving and responding to requests
                  vi

                  from clients.

     •    For example, a servlet may do the following
         ee


          tasks.

     •    A servlet may process data POSTed by an HTTP
      n



          client, using an HTML form.
   w.




              –   Such a servlet might work together with
                  a database and an online payment
                  system.
ww




     •    A servlet can also forward requests to other
          servers, to balance load between servers.


   CKR                    Java Notes                        213
Servles (contd)




                                              om
     •    Since a servlet can handle multiple requests
          concurrently, i.e., it is multi-threaded, it can
          support systems like online conferencing/chat.




                                         .c
     •    Since a servlet can dynamically generate HTTP
          responses




                                DF
             –       servlets serves as a replacement for CGI
                     (Common Gateway Interface)scripts
                     (server side scripting) used to generate
                        aP
                     web pages dynamically.

     •    Servlets have some advantages over CGI
                 vi

             –       CGI uses the process model: with CGI a
                     separate process is created for each
                     client request.
         ee


             –       Servlets handle multiple client requests
                     using a thread model: so performance is
      n



                     faster.
   w.




             –       Full functionality of Java is available,
                     including the security manager used to
                     protect resources on the server.
ww




   CKR                      Java Notes                     214
•    Servlets work with the Servlet API.




                                            om
            –    This is a standard Java extension API .

            –    Hence, unlike CGI, servlets may be run
                 on different servers (which support




                                      .c
                 servlets) in a platform independent way.




                             DF
            –    Many webservers support the servlet
                 API.

            –    These include Apache, iPlanet, and
                    aP
                 Microsoft IIS.

            –    For a full list of third party products that
                 run servlets, see
                vi

                 http://java.sun.com/
                 products/servlets/
         ee


            –    For examples of real life servlet
                 implementations try
      n



            –    ecampus.com, SiliconInvestor.com etc.
   w.




    •    Java has enhanced Servlet technology through
         Java Server Pages: JSP, which serves as a
         substitute for the proprietary ASP..
ww




   CKR                   Java Notes                        215
Servlets: initial preparations




                                            om
      •   Preparations: To test and run servlets, one needs

              –    The Java servlet development kit, which




                                        .c
                   contains the requisite class libraries.

              –    The servletrunner utility, which can be




                               DF
                   used to test servlets.

      •   Step 1: Download and install the Java servlet
          development kit.
                       aP
      •   Step 2: Update the CLASSPATH variable, to
          include the path where the servlet class libraries
          are installed. E.g.
                  vi

   set
   CLASSPATH=.;d:jdk1.2.2servletslibjsdk.jar
          ee


      •   Step 3: Update the PATH variable to include the
          path in which the servletrunner utility is located.
      n



          E.g.
   w.




   set PATH=%path%;d:jdk1.2.2servletsbin

      •   We can now start writing the first servlet
          program.
ww




   CKR                     Java Notes                        216
Servlet Lifecycle




                                          om
      •   Servlet lifecycle: A servlet is
             – initialised
             – provides service




                                      .c
             – is destroyed (depending upon server on
                   which it is running)




                             DF
      •   Correspondingly,writing a servlet involves
          writing three key methods.
              – init
              – service
                       aP
              – destroy

      •   The init method is invoked exactly once for
          each servlet.
                  vi

      •   The service method is MULTITHREADED.
             – It is typically expected to concurrently
          ee


                 handle requests from multiple clients.

      •   The destroy method should
      n



             – typically undo whatever initialization has
                 been performed, by closing files and
   w.




                 database connections.

              –   ensure that all service threads are
ww




                  complete before the servlet is destroyed.




   CKR                   Java Notes                     217
Hello Servlet




                                           om
     •    All servlets must implement the servlet interface
              – either directly
              – or by extending a class which




                                       .c
                   implements the interface.

     •    The HelloServlet class extends GenericServlet,




                             DF
          which is a class which implements the Servlet
          interface.

   Program 38
                     aP
   import java.io.*;
   import javax.servlet.*;
                   vi

   public class HelloServlet extends
   GenericServlet
   {
          ee


      public void service (ServletRequest rq,
   ServletResponse rp)
         throws ServletException, IOException
      n



         {
            rp.setContentType ("text/html");
   w.




            PrintWriter pw = rp.getWriter();
            pw.println ("<B>Hello Servlet");
            pw.close();
ww




         }
   }



   CKR                    Java Notes                    218
HelloServlet: Analysis of code




                                             om
     •    The HelloServlet class implements only the
          service method.




                                       .c
     •    The service method has the prototype

   public void service (




                             DF
        ServletRequest rq,
        ServletResponse rp);

     •    involving the public interfaces,
                      aP
             –    Servlet Request and
             –    ServletResponse
                 vi

     •    These interfaces incorporate a number of
          methods for handling MIME (Multipurpose
          Internet Mail Extension) bodies.
         ee


     •    MIME bodies are either
             – text, or
      n



             – binary data
   w.




     •    Correspondingly, one must
             – first get/set contentType
ww




             –    then get an Input/OutputStream or
                  Reader and Writer



   CKR                    Java Notes                   219
MIME types




                                             om
    S.
                MIME type                      Origin
   No.
    1    application/octet-stream      Generic byte stream




                                       .c
                                     Adobe Acrobat portable
    2.       application/pdf
                                      document format files




                                DF
   3.     application/postscript              Postscript
   4.        application/rtf               Rich text format
   5.       application/x-tex                     TeX
    6.          text/plain          .txt, .c, .cpp, .java, .h etc,
                      aP
    7.           text/html                    .htm, .html
   8.           image/gif                          .gif
    9.         image/jpeg                        JPEG
                vi

   10.          image/tiff                        TIFF
   11.         video/mpeg                        .mpg
         ee


                                          .mov or .qt Apple
   12.       video/quicktime
                                           QuickTime files
   13.      video/x-sgi-movie        .movie Silicon Graphics
      n



   14.         audio/basic            .snd or .au sound clip
   15.         audio/x-wav                     .wav file
   w.




     •    More info: RFC 2045/2046. (RFC = Request for
ww




          Comments. Many Internet standards are evolved
          in this way. MIME is an evolving standard.



   CKR                    Java Notes                          220
Hello Servlet: Analysis of code (contd)




                                             om
     •    Thus, the HelloServlet class

              –   first set the MIME type to text/html, since




                                       .c
                  we want to output HTML, and

              –   then gets a PrntWriter, using the




                             DF
                  getWriter method provided by the
                  ServletResponse Interface

     •    The page to be generated can is now written in
                      aP
          standard HTML

           – More Info on HTML1.1: RFC2068
   http://infor.internet.isi.edu:80/in-notes/
                  vi

   rfc/files/rfc2068.txt

     •    The HTML code to be generated can be as
          ee


          complex or as simple as we want.

              –   To generate this code we simply use the
      n



                  various methods available with
                  PrintWriter, such as the println method.
   w.




              –   After completing the write, we close the
                  stream through a call to the close
ww




                  method of PrintWriter.




   CKR                    Java Notes                      221
HelloServlet: Testing the code




                                            om
     •    Step 1: Compile the code as usual.

     •    (The javax package must be located so that it




                                       .c
          can be found using the set CLASSPATH. The
          default installation will put javax in the right
          directory. )




                              DF
     •    Step 2: Start servletrunner.
             – PATH and CLASSPATH should have
                  been set as described earlier.
                      aP
              –   servletrunner invoked with -h will
                  provide help.
                  vi

              –servletrunner invoked with -d will set the
               servlet directory
   servletrunner -d c:javakawa
         ee


     •    Step 3: Start a webbrowser.
      n



     •    Step 4: Request the servlet using the following
          URL
   w.




   http://localhost:80/servlet/HelloServlet
   or
ww




   http://127.0.0.1:8080/servlet/HelloServlet

     •    Output:Helloservlet in the browser.


   CKR                    Java Notes                         222
Servlets (contd)




                                           om
     •    An IOException may be thrown by the call to the
          getWriter method.




                                       .c
     •    The ServletException indicates a servlet
          problem.




                             DF
     •    The above servlet did not use the init or destroy
          methods.

     •    The destroy method has the prototype
                      aP
   public void destroy();

     •    The init method has the prototype
                vi

   public void init (ServletConfig cfg)
   throws ServletException
         ee


     •   ServletConfig is a public interface, which defines
         various abstract methods like
      n



   getInitParameters( String name)
    getInitParameterNames()
   w.




   ServletContext getServletContext()

     •    ServletContext is an interface with various
ww




          useful methods, which enable one to get the
          MIME type, server name, real path etc,, for which
          check the documentation.


   CKR                    Java Notes                     223
Servlet architecture (summary)




                                           om
     •    Thus, servlets involve the following interfaces

     •    Servlet Interface




                                       .c
             – implemented by all servlets, directly or
                indirectly
             – defines the three key public methods




                             DF
             – void init (ServletConfig cfg)
             – void service (ServletRequest
                rq, ServletResponse rp)
             – void destroy()
                     aP
     •    ServletRequest Interface
             – passed as an argument to the service
                method.
                 vi

             – defines the

                  getInputStream() and
         ee


                  getReader()

                  methods which return
      n




             –    ServletInputStream, and
   w.




                  BufferedReader
                  objects, respectively.
ww




             –    ServletInputStream extends
                  InputStream, and is used to handle
                  binary data.


   CKR                    Java Notes                        224
•    ServletResponse Interface




                                        om
            – passed as an argument to the service
               method

            –   defines the




                                     .c
                getOutputStream(), and
                getWriter()




                           DF
            –   methods which return
                ServletOutputStream, and
                PrintWriter
                    aP
                objects, respectively.

            –   ServletOutputStream extends
                OutputStream, and is used to handle
                vi

                binary data.

    •    ServletConfig Interface and ServletContext
         ee


         Interface used to get various parameters
         associated with the servlet.
      n



    •    SingleThreadModel Interface
            – This interface has no constants or
   w.




               methods.
            – A servlet implements this interface only
               to indicate that the service method of the
ww




               servlet can handle only one client at a
               time.



   CKR                  Java Notes                    225
Servlets: initialization




                                            om
      •    A servlet may be named, and initialization
           parameters may be provided for the servlet, in
           the




                                           .c
               – servlet.properties file

      •    The default location for this file is in




                                 DF
              –     servletsexamples,
              – i.e., in .examples relative to the directory
                   in which servletrunner starts
              – to set it some other location, use the -p
                        aP
                   option with servletrunner

      •    The sample servlet.properties file, provided by
           Sun, as part of the JDK, looks as follows (next
                   vi

           page):
              – This is self-explanatory.
              – # is used for comments
          ee


              – The name of the servlet may be
                   optionally set to something other than its
                   class name through the line
      n




   servlet.<name>.code=codename (foo or
   w.




   foo.class)

               –    the initial arguments may be provided by
ww




   servlet.name.initArgs=pname1=pvalue1,pname
   2=pvalue2


   CKR                        Java Notes                    226
Sun’s sample servlet properties file




                                          om
   # @(#)servlets.properties        1.86 97/11/14
   #
   # Servlets Properties




                                       .c
   #
   # servlet.<name>.code=class name (foo or
   #foo.class)




                              DF
   # servlet.<name>.initArgs=comma-delimited
   #list of {name, value} pairs
   #         that can be accessed by the servlet
   #using the
                      aP
   #         servlet API calls
   #

   # session servlet
                 vi

   servlet.session.code=SessionServlet
          ee


   # simple servlet
   servlet.simpleservlet.code=SimpleServlet
      n



   # snoop servlet
   servlet.snoop.code=SnoopServlet
   w.




   # survey servlet
   servlet.survey.code=SurveyServlet
ww




   servlet.survey.initArgs=
      resultsDir=/tmp



   CKR                    Java Notes           227
Servlet initialization example




                                          om
      •  These considerations are illustrated by the
         following sample code.
    Program 39




                                        .c
   import java.io.*;
   import javax.servlet.*;




                              DF
   public class GetProps extends
   GenericServlet
   {
      public void service (ServletRequest rq,
                      aP
            ServletResponse rp)
            throws ServletException, IOException
      {
         ServletConfig sc = getServletConfig();
                 vi

           //first set content type
           rp.setContentType ("text/html");
           ee


           //then get i/o stream
           PrintWriter pw = rp.getWriter();
      n



           pw.println ("<B>State = </B"> +
              sc.getInitParameter("State") ) ;
   w.




           pw.println ("
              <BR><B>City = </B>" +
              sc.getInitParameter("City") );
ww




           pw.close();
      }}



   CKR                     Java Notes                  228
•    Compile the code




                                             om
     •   Add the following lines to the servlet.properties
         file
   #props servlet
    servlet.props.code=GetProps




                                        .c
   servlet.props.initArgs=
      State=M.P.,




                              DF
      City=Bhopal

     •    Start servletrunner utility (remember -d for the
          servlet source files, and -p for the properties file)
                      aP
     •    Open a webbrowser, and request the URL

   http://localhost:8080/servlet/props
                 vi

     •    Output:
          State=M.P.
         ee


          City=Bhopal
      n
   w.
ww




   CKR                     Java Notes                       229
Servlets: More examples




                                          om
     •   Instead of overriding the GenericServlet class, it
         is often more useful to override the HttpServlet
         class, which is specially adapted to http actions,




                                      .c
         with methods like
             – doGet         HTTP Get
             – doPost        HTTP Post




                             DF
             – doPut         HTTP Put
             – doDelete HTTP Delete
             – doTrace HTTP Trace
             – doOptions HTTP Options
                     aP
             – and
             – getLastModified

     •   In this case, the service method has the
               vi

         prototype

   void service (HttpServletRequest rq,
         ee


   HttpServletResponse rp);

     •   The use of these functions is illustrated by the
      n



         sample code given by Sun along with servlets.
   w.




     •   The following code reads a form, and writes the
         results to file.
ww




     •   The key issue is the question of synchronization:
         hence the method implements the single thread
         model.


   CKR                   Java Notes                     230
•   code in file JDcSurvey.html




                                       om
   <!DOCTYPE HTML PUBLIC "-//IETF//DTD
   HTML//EN">r
   <html>
     <head>




                                       .c
       <title>JdcSurvey</title>
     </head>




                           DF
     <body>
       <form
   action=http://localhost:8080/servlet/survey
                    aP
   method=POST>
         <input type=hidden name=survey
   value=Survey01Results>
         <BR><BR>How Many Employees in your
               vi

   Company?<BR>
            <BR>1-100<input type=radio
   name=employee value=1-100>
         ee


            <BR>100-200<input type=radio
   name=employee value=100-200>
            <BR>200-300<input type=radio
      n



   name=employee value=200-300>
            <BR>300-400<input type=radio
   w.




   name=employee value=300-400>
            <BR>500-more<input type=radio
   name=employee value=500-more>
ww




         <BR><BR>General Comments?<BR>
            <BR><input type=text name=comment>
         <BR><BR>What IDEs do you use?<BR>


   CKR                  Java Notes          231
<BR>JavaWorkShop<input




                                 om
   type=checkbox name=ide value=JavaWorkShop>
           <BR>J++<input type=checkbox
   name=ide value=J++>
           <BR>Cafe’<input type=checkbox
   name=ide value=Cafe’>




                                 .c
         <BR><BR><input type=submit><input
   type=reset>




                       DF
       </form>
     </body>
   </html>
                 aP
             vi
      n  ee
   w.
ww




   CKR              Java Notes             232
/*




                                  om
   * @(#)SurveyServlet.java
   *
   * Copyright (c) 1995-1997 Sun
   Microsystems, Inc. All Rights Reserved.
   *




                                 .c
   */
   import java.io.*;




                       DF
   import java.util.*;

   import javax.servlet.*;
   import javax.servlet.http.*;
                 aP
   /**
    * A sample single-threaded servlet that
   takes input from a form
             vi

    * and writes it out to a file. It is
   single threaded to serialize
    * access to the file. After the results
         ee


   are written to the file,
    * the servlet returns a "thank you" to
   the user.
      n



    *
    * <p>You can run the servlet as provided,
   w.




   and only one thread will run
    * a service method at a time. There are
   no thread synchronization
ww




    * issues with this type of servlet, even
   though the service method
    * writes to a file. (Writing to a file


   CKR              Java Notes               233
within a service method




                                 om
    * requires synchronization in a typical
   servlet.)
    *
    * <p>You can also run the servlet without
   using the single thread




                                 .c
    * model by removing the
   <tt>implements</tt> statement. Because the




                       DF
    * service method does not synchronize
   access to the file, multiple
    * threads can write to it at the same
   time. When multiple threads try
                 aP
    * to write to the file concurrently, the
   data from one survey does not
    * follow the data from another survey in
   an orderly fashion.
             vi

    *
    * <p>To see interaction (or lack of
   interaction) between threads, use
         ee


    * at least two browser windows and have
   them access the servlet as
    * close to simultaneously as possible.
      n



   Expect correct results (that
    * is, expect no interference between
   w.




   threads) only when the servlet
    * implements the
   <code>SingleThreadedModel</code> interface.
ww




    */




   CKR              Java Notes             234
om
   public class SurveyServlet extends
   HttpServlet
       implements SingleThreadModel
   {
       String resultsDir;




                                  .c
        public void init(ServletConfig config)




                        DF
      throws ServletException
        {
      super.init(config);
             resultsDir =
                 aP
   getInitParameter("resultsDir");
      if (resultsDir == null) {
           Enumeration initParams =
   getInitParameterNames();
             vi

           System.err.println("The init
   parameters were: ");
           while (initParams.hasMoreElements()) {
         ee


          System.err.println(initParams.nextElement())
   ;
           }
      n



           System.err.println("Should have seen
   one parameter name");
   w.




           throw new UnavailableException (this,
          "Not given a directory to write survey
   results!");
ww




      }
        }



   CKR               Java Notes              235
/**




                                  om
         * Write survey results to output file
   in response to the POSTed
         * form. Write a "thank you" to the
   client.
         */




                                 .c
       public void doPost(HttpServletRequest
   req, HttpServletResponse res)




                       DF
      throws ServletException, IOException
       {
            // first, set the "content type"
   header of the response
                 aP
      res.setContentType("text/html");

      //Get the response’s PrintWriter to return
   text to the client.
             vi

           PrintWriter toClient =
   res.getWriter();
         ee


           try {
                //Open the file for writing
   the survey results.
      n



                String surveyName =
   req.getParameterValues("survey")[0];
   w.




                FileWriter resultsFile = new
   FileWriter(resultsDir
              +
ww




   System.getProperty("file.separator")
              + surveyName + ".txt", true);
                PrintWriter toFile = new


   CKR              Java Notes                 236
PrintWriter(resultsFile);




                                 om
          // Get client’s form data & store it
   in the file
               toFile.println("<BEGIN>");
               Enumeration values =




                                 .c
   req.getParameterNames();




                       DF
   while(values.hasMoreElements()) {
                   String name =
   (String)values.nextElement();
        String value =
                 aP
   req.getParameterValues(name)[0];

   if(name.compareTo("submit") != 0) {
                       toFile.println(name +
             vi

   ": " + value);
                   }
               }
         ee


               toFile.println("<END>");

         //Close the file.
      n



              resultsFile.close();
   w.




          // Respond to client with a thank you
          toClient.println("<html>");
          toClient.println("<title>Thank
ww




   you!</title>");
               toClient.println("Thank you
   for participating");


   CKR              Java Notes             237
toClient.println("</html>");




                                 om
           } catch(IOException e) {
               e.printStackTrace();
               toClient.println(
        "A problem occured while recording your




                                 .c
   answers. "
        + "Please try again.");




                       DF
           }

           // Close the writer; the response
   is done.
                 aP
      toClient.close();
       }
   }
             vi
      n  ee
   w.
ww




   CKR              Java Notes             238
Elements of Java GUI




                                          om
     •   GUI programmingn is event-based.

     •   An event is a change of state in a source.




                                       .c
     •   A source of events can be
            – keyboard




                             DF
            – mouse
            – internal state of the machine, such as a
                clock,
            – a programme, when it completes some
                     aP
                job.

     •   Hence, GUI programming needs an event model .
               vi

     •   Java 1.0, 1.1 and 1.2 have used somewhat
         different approaches.
         ee


     •   It is necessary to understand the earlier
         approach, since
              – most of the programmer’s time is spent
      n



                  in maintaining code, rather than in
                  developing code.
   w.




     •   Legacy code uses the Java 1.0 model.
ww




   CKR                    Java Notes                  239
Java GUI elements




                                          om
     •   The GUI elements such as
            – buttons
            – lists




                                      .c
            – icons
            – scroll panes
            – menus




                            DF
     •   are all Windows.

     •   Java’s problem is to model these Windows in a
                       aP
         platform independent way.

     •   Java being object oriented, all these elements
         are modeled using classes and objects.
               vi

     •   These elements are intuitively seen as
         components put within a container.
         ee


            – However, in Java the Component class is
                at the top of the awt hierarchy, and
                Container is a subclass.
      n




     •   Also, intuitively one tends to think of a Frame as
   w.




         a rectangular box, with nothing in it, and one
         thinks of a Window as something which has a
         title, can be resized etc.
ww




     •   This terminology is reversed in Java, with
         Window being the rectangular box, and Frame


   CKR                   Java Notes                       240
being a subclass with title bar etc.




                                            om
    •     Applets are an important aspect of Java.

    •     Applets are subclasses of Panel, which is a
          concrete implementation of the abstract




                                       .c
          Container class.




                              DF
                      Component
                      aP
                        Container
                 vi

            Window
          ee


                                                 Panel
      n



         Frame
   w.
ww




   CKR                    Java Notes                     241
Java event models




                                          om
     •   The key difference between the two event
         models is this.




                                      .c
     •   In the 1.0 event model, the GUI elements were
         stacked hierarchically, and




                            DF
            –    any event was despatched to all
                 elements.

     •   A GUI element could handle the event if it so
                       aP
         desired, or it could ignore it.

     •   This method was found to be inefficient and
         time-consuming.
                vi

     •   Accordingly, the 1.1 model adopts the usual
         MS-Windows technique:
         ee


     •   A GUI must notify all event sources, by
         registering an event handler.
      n




     •   Events are then despatched only to registered
   w.




         handlers.

     •   Such event handlers are called listeners
ww




     •   The model is known as the Delegation Event
         Model.


   CKR                   Java Notes                      242
–    a user interface element is able to




                                         om
                 delegate the processing of events to a
                 separate piece of code.

    •    The source which generates the event sends to
         each registered listener,




                                     .c
    •    Some events may not be handled by more than a




                            DF
         specified number of listeners.
            – In this case registering an additional
                 listener leads to an exception.
                    aP
    •    Like UI elements, Events too are modeled by
         classes and objects.

    •    EventObject is the superclass of all events
                vi

    •    AWTEvent is the superclass of all AWT events.
         ee


    •    Various types of events are defined

            –    ActionEvent (when a button is pressed,
      n



                 or a list or menu item is selected)
   w.




            –    ItemEvent (when a checkbox or list item
                 is clicked, or a choice is made etc.)
ww




            –    AdjustmentEvent (when a scroll bar is
                 manipulated)



   CKR                  Java Notes                       243
–    ComponentEvent (when a component




                                          om
                 changes its state and becomes visible or
                 is hidden or moved or resized etc.)

            –    ContainerEvent (when a component is
                 added or removed from a container)




                                     .c
            –    KeyEvent (when input is received from




                            DF
                 the keyboard)

            –    MouseEvent (when the mouse is moved,
                 or clicked, or dragged etc.)
                    aP
            –    TextEvent (when the text in a TextField or
                 TextArea is changed)
                vi

            –    WindowEvent (when a Window is closed,
                 minimised etc.)
         ee


    •    Corresponding to this there are listener
         interfaces.
             – ActionListener for ActionEvents
      n



             – ItemListener for ItemEvents
             – AdjustmentListener for
   w.




                 AdjustmentEvents
             – ComponentLIstener
             – ContainerListener
ww




             – KeyListener
             – MouseListener
             – TextListener, etc.


   CKR                  Java Notes                      244
Java GUI (contd)




                                          om
     •    These considerations are illustrated by the
          following examples.




                                      .c
    Program 40
   /*An applet illustrating the 1.0 event
   model */




                             DF
   import java.applet.*;
   import java.awt.*;
                      aP
   public class SillyButton extends Applet
   {
      public void init()
      {
                vi

      //add two buttons labeled red and blue
         add (new Button ("Red"));
         add (new Button ("Blue"));
         ee


      }

      //older action method is deprecated
      n




      public boolean action (Event evt, Object
   w.




   act)
      {
         //check nature of event
ww




         if (!(evt.target instanceof Button))
         {
            return false;


   CKR                   Java Notes                     245
}




                                    om
           String btLabel = (String)act;
           if (btLabel == "Red")
           {
              setBackground (Color.red);




                                    .c
           }
           else if (btLabel == "Blue")




                          DF
           {
              setBackground (Color.blue);
           }
                    aP
           repaint(); //show changed background
           return true;
       }
   }
                vi
      n    ee
   w.
ww




   CKR                 Java Notes             246
Program 41




                                   om
   /*This applet illustrates the revised Java
   1.1 event model which has been carried
   over into Java 1.2 */

   import java.applet.*;




                                   .c
   import java.awt.*;
   import java.awt.event.*;




                         DF
   class BackSet
      extends Object
      implements ActionListener
                   aP
   {
      Component cmp;
      Color clr;
      //define constructor
               vi

      BackSet(Component cmp, Color clr)
      {
           this.cmp = cmp;
         ee


           this.clr = clr;
      }
      n



       public void actionPerformed
          (ActionEvent evt)
   w.




       {
             cmp.setBackground (clr);
             cmp.repaint();
ww




       }
   }



   CKR                Java Notes           247
public class SillyButton2




                                 om
      extends Applet
   {
      public void init()
         {
              Button red = new Button ("Red");




                                 .c
              add (red);
              red.addActionListener




                       DF
              (new BackSet (this, Color.red));

             Button blue = new Button ("Blue");
             add (blue);
                 aP
             blue.addActionListener
             (new BackSet (this, Color.blue));

         }
             vi

     }
      n  ee
   w.
ww




   CKR              Java Notes              248
Choice




                                        om
     •   The following program illustrates an applet
         which uses a choice. The choices are grouped to
         make them mutually exclusive.




                                     .c
    Program 42
   import java.applet.*;
   import java.awt.*;




                           DF
   import java.awt.event.*;

   public class SillyChoice
      extends Applet
                    aP
   {
         static char ch=’B’;
         public void init()
         {
               vi

            //create a choice menu
            Choice c = new Choice();
         ee


            //add items to menu
            c.addItem ("Red");
            c.addItem ("Blue");
      n



            c.addItem ("Green");
   w.




            //mark one item as selected
            c.select ("Blue");
ww




            //add choice to applet
            add (c);



   CKR                  Java Notes                   249
om
            //create an ItemListener object

            ItemListener l = new chkItemListener();

            //add a listener interface to each




                                   .c
            //checkbox




                         DF
            c.addItemListener(l);

       }
                   aP
       public void paint(Graphics g)
       {
          switch (ch)
          {
               vi

              case ’R’: setBackground (Color.red);
                                       break;
              case ’B’: setBackground (Color.blue);
           ee


                                       break;
              case ’G’: setBackground (Color.green);
                                       break;
      n



              default: break;
            }
   w.




            repaint();
       }
ww




   }

   //define an item listener


   CKR                Java Notes              250
//ItemListener is an abstract interface




                                 om
   //to implement which, one method must be
   //defined.
   //This method decides what is done when
   //a certain checkbox is selected
   class chkItemListener




                                 .c
      implements ItemListener
   {




                       DF
     public void itemStateChanged
        (ItemEvent evt)
     {
                 aP
        if (evt.getStateChange() ==
              ItemEvent.SELECTED)
        {
             vi

           Choice cb = (Choice)
   evt.getItemSelectable();
           String sb = new String
         ee


   (cb.getSelectedItem());
           SillyChoice.ch = sb.charAt (0);
           /*alternatively use int ch in place of
      n



   char ch
           and use
   w.




           SillyChoice.ch=cb.getSelectedIndex()
              0=Red, 1=Blue, 2=Green etc.
           */
ww




        }
      } }



   CKR              Java Notes                251
Check boxes and Radio buttons




                                    om
   /* Grouping checkboxes makes them
   radio buttons */




                                    .c
   import java.applet.*;
   import java.awt.*;




                          DF
   import java.awt.event.*;


   public class SillyRadio
                    aP
      extends Applet
   {
         static char ch=’B’;
         public void init()
               vi

         {
            //create a group
            CheckboxGroup cbg = new CheckboxGroup();
           ee


            //create checkboxes, state, to group
            Checkbox cb1 = new Checkbox ("Red", false,
      n



   cbg);
            Checkbox cb2 = new Checkbox ("Blue", true,
   w.




   cbg);
           Checkbox cb3 = new Checkbox ("Green",
   false, cbg);
ww




            //add checkboxes to applet



   CKR                 Java Notes           252
add (cb1);




                                 om
          add (cb2);
          add (cb3);

          //create an ItemListener object




                                 .c
          ItemListener l = new chkItemListener();




                       DF
          //add a listener interface to each
          //checkbox

          cb1.addItemListener(l);
                 aP
          cb2.addItemListener (l);
          cb3.addItemListener (l);
     }
             vi

     public void paint(Graphics g)
     {
        switch (ch)
         ee


        {
            case ’R’: setBackground (Color.red);
                                     break;
      n



            case ’B’: setBackground (Color.blue);
                                     break;
   w.




            case ’G’: setBackground (Color.green);
                                     break;
            default: break;
ww




          }
          repaint();
     }


   CKR              Java Notes              253
}




                                 om
      //define an item listener
   //ItemListener is an abstract interface
   //to implement which, one method must be
   //defined.




                                 .c
   //This method decides what is done when
   //a certain checkbox is selected




                       DF
   class chkItemListener
      implements ItemListener
   {
                 aP
     public void itemStateChanged
        (ItemEvent evt)
     {
             vi

        if (evt.getStateChange() ==
              ItemEvent.SELECTED)
        {
         ee


           Checkbox cb = (Checkbox)
   evt.getItemSelectable();
           String sb = new String (cb.getLabel());
      n



           SillyRadio.ch = sb.charAt (0);
        }
   w.




      }
   }
ww




   CKR              Java Notes                254
Lists as applications




                                        om
    Program 43
   /*This runs as both an
   application and an applet*/




                                        .c
   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;




                              DF
   class SillyList
      extends Applet
                      aP
   {
         static int ti;
         static int [] si = new int[3];
         List l;
                 vi

         public void init()
         {
            //create a List with 3 elements
          ee


            //permitting multiple selections
            //the default constructor does
            //not permit multiple selections
      n




             l = new List(3, true);
   w.




             //add items to list
             //note that the function is add
ww




             //not addItem
             //The addItem function still exists
             //but is deprecated


   CKR                     Java Notes          255
om
         l.add ("Red");
         l.add ("Blue");
         l.add ("Green");

         //mark two items as selected




                                 .c
         l.select (1);
         l.select (0);




                       DF
         //if the list does not permit
         //multiple selections
         //then the second call
               aP
         //will de-select

         //make a selected item visible
           vi

          l.makeVisible (1);

         //add list to applet
         ee


         add (l);
      n




         //create an ItemListener object
   w.




         ItemListener ls = new chkItemListener();
ww




         //add a listener interface to each
         //checkbox



   CKR              Java Notes             256
l.addItemListener(ls);




                                     om
       }

      public void paint (Graphics g)
      {




                                  .c
         for (int i=0; i<= 3; i++)
            if (l.isIndexSelected(i) )




                        DF
               g.drawString ("Selected " + i, 10,
   30+20*i);
         //repaint(); //don’t call this
         //resize the applet to force
                  aP
         //repaint()

       }
   }
              vi
           ee


      //define an item listener
   //ItemListener is an abstract interface
   //to implement which, one method must be
      n



   //defined.
   //This method decides what is done when
   w.




   //a certain list box item is selected
   class chkItemListener
      implements ItemListener
ww




   {

       public void itemStateChanged


   CKR               Java Notes               257
(ItemEvent evt)




                                    om
       {

        if (evt.getStateChange() ==
           p ItemEvent.SELECTED)
        {




                                    .c
           List lb = (List) evt.getItemSelectable();
           //Note the plural in the next line




                          DF
           SillyList.si = lb.getSelectedIndexes();
           SillyList.ti =
   lb.getSelectedIndexes().length;
                    aP
           }
       }
   }
                vi

   public class SillyListApplication
   {
      public static void main (String args[])
           ee


      {
         //create a Frame object
         Frame f = new Frame ("Applet as an
      n



   application");
   w.




           //create an applet object
           SillyList sl = new SillyList();
ww




           //add applet to frame
           f.add (sl);



   CKR                 Java Notes            258
//set size of frame and




                                     om
           f.setSize (100, 120);

           //make frame visible
           f.show();




                                    .c
           //call the applets methods
           sl.init();




                          DF
           sl.start();

           //add a listener to make the
           //windows close work
                    aP
           //using an inner class

           f.addWindowListener (
           /*WindowListener is an abstract interface
                vi

   which
           extends EventListener. However we do not
   want
           ee


        to implement all methods in this
   interface. Hence
        we choose an Adapter class with empty
      n



   methods
        and override the method of interest*/
   w.




              new WindowAdapter()
              {
              public void windowClosing
ww




              (WindowEvent wevt)
              {
              System.exit(0);


   CKR                 Java Notes             259
} //end of method def




                                    om
             }//end of inner class def
             ); //end of listener def

      } //end of main
   } //end of SillyList class def




                                 .c
                       DF
                 aP
             vi
      n  ee
   w.
ww




   CKR              Java Notes           260
Networking




                                         om
     •   The key networking classes are in the package
         java.net




                                      .c
     •   The package aims to facilitate communication
         across the network using
            – HTTP




                            DF
            – TCP/IP
            – UDP (Datagrams)

     •   Corresponding classes are provided.
                     aP
            – InetAddress
            – URL
            – Socket (client socket)
            – ServerSocket
                vi

            – DatagramSocket
            – DatagramPacket
         ee


     •   The following programs demonstrate the use of
         these classes.
      n



   Getting an Internet address: Factory methods
   w.




     •   To get an IP address we use the InetAddress
         class.
ww




     •   The InetAddress class has no visible
         constructors.



   CKR                   Java Notes                     261
•   An object of the class must be constructed using




                                        om
         one of the so-called "factory methods"
            – A factory method is merely a convention
                 where a static method in a class returns
                 an instance of the class.




                                     .c
            –   Factory methods are substitutes for
                overloaded constructors.




                           DF
            –   In the case of InetAddress, factory
                methods are more appropriate than
                constructors: one gets an address.
                    aP
     •   Some of these factory methods are

            –   getLocalHost()
                vi

            –   getByName()
            –   getAllByName()
         ee


     •   These methods have the prototypes

   static InetAddress getLocalHost() throws
      n



   UnknownHostException
   w.




   static InetAddress getByName (String
   hostName) throws Unknown HostException
ww




   static InetAddress[]getAllByName (String
   hostName) throws UnknownHostException



   CKR                  Java Notes                    262
•    The following program demonstrates the use of




                                     om
          these factory methods.
    Program 44
   import java.net.* ;
   class InetTest {
       public static void main(String args[])




                                   .c
          throws UnknownHostException {
          InetAddress Address =




                         DF
   InetAddress.getLocalHost();
   System.out.println("local host: " +
   Address);
          Address =
                   aP
   InetAddress.getByName("msn.com");
          System.out.println ("msn.com" + Address);
          InetAddress MSN[] =
   InetAddress.getAllByName ("www.msn.com");
              vi

          for (int i=0; i MSN.length; i++)
          System.out.println ("www.msn.com" +
   MSN[i]);
         ee


       } }
      •   output: localhost: 127.0.0.1
          msn.com: 207.46.176.152
      n



          www.msn.com: 207.46.185.138
          www.msn.com: 207.46.185.140
   w.




          www.msn.com: 207.46.209.218
          www.msn.com: 207.46.209.243
          www.msn.com: 207.46.179.134
ww




          www.msn.com: 207.46.179.143
          www.msn.com: 207.46.179.71
          Application Exit...


   CKR                Java Notes                263
Getting a URL




                                          om
     •    A URL is a Uniform Resource Locator: a pointer
          to a resource on the web.




                                      .c
     •    A "resource" may be
              – a file
              – a directory,




                             DF
              – a query to a database
              – or other information generated on the fly.

     •    The public final class URL encapsulates a URL.
                     aP
     •    To get a URL, we use the URL class.

     •    The URL class has several constructors
                vi

     •    The simplest constructor uses a URL specified
          by means of a string.
         ee


   URL (String urlSpecifier);
      n



     •    We can also break up the URL into its
          components, and specify
   w.




              – the protocol
              – the host name
              – the port name (optional)
ww




              – path
   to obtain a URL object.



   CKR                   Java Notes                    264
•   That is, we can also use the following two




                                         om
         constructors.

   URL (String protocolName,
        String hostName,
        int portNumber,




                                     .c
        String path)




                            DF
   URL (String protocolName,
        String hostName,
        String path)
                    aP
     •   The following program builds a URL object from
         the string form of the URL
               vi
      n  ee
   w.
ww




   CKR                  Java Notes                    265
Program 45




                                             om
   import java.net.*;
    class URLTest { public static void main
   (String args[])
      throws MalformedURLException {
      URL url = new URL




                                       .c
   ("http://www.hotmail.com");
      System.out.println("Protocol: " +




                              DF
          url.getProtocol());
      System.out.println ("Port: "
         + url.getPort());
      System.out.println ("Host: " +
                      aP
         url.getHost());
      System.out.println ("File: " +
          url.getFile());
      System.out.println ("String: " +
                vi

          url.toString());
      }
    }
         ee


     •   Output:
             Protocol: http
      n



             Port: -1 (getPort returns - 1 if port not explicitly
                     set)
   w.




         Host: www.hotmail.com
         File: /
         String: http: //www.hotmail.com/
ww




   CKR                    Java Notes                         266
Connecting to a URL




                                       om
     •   Once we have created a URL object we can
         connect to it using the
            – openConnection method.




                                      .c
     •   This method returns an object of the
            – URLConnection class




                            DF
     •   Once we have connected to a URL, we can query
         its properties, using methods (of the
         URLConenction class) such as
              – getDate()
                    aP
              – getLastModified()
              – getContentType()
              – getContentLength()
               vi

     •   A URL connection can be used for input and
         output.
         ee


     •    Having connected to a URL we can also read
          from it, using
             – getInputeStream method
      n



   which returns an InputStream object from which we
   can read and write using standard i/o techniques.
   w.




     •    We can also write to the URL, using the
              – getOutputStream method
ww




   and standard i/o techniques to the OutputStream
   object that it returns.



   CKR                   Java Notes                   267
Connecting to a URL and transferring a file




                                           om
   import java.net.*; import java.io.*;
   import java.util.Date;
   class UConnect {




                                       .c
      public static void main (String args[])
         throws Exception
         //so declared, to avoid




                             DF
      //exception handling logic
      {
         int c=0;
         URL url = new
                      aP
      /*URL("http://www.ncsa.uiuc.edu/demoweb/url-
   primer.html"); */
    //no more accessible
     URL(
                vi

   "http://www.w3.org/Addressing/URL/url-spec.t
   xt");
         URLConnection urlCon =
         ee


             url.openConnection();
         System.out.println ("Date: " +
            new Date (urlCon.getDate() ));
      n



         System.out.println ("Content type: " +
          urlCon.getContentType());
   w.




         System.out.println ("Last Modified: " +
   new Date (urlCon.getLastModified()) );
         int len = urlCon.getContentLength();
ww




         System.out.println ("Content length: " +
               len);



   CKR                    Java Notes             268
if (len == 0 )




                                       om
           {
              System.out.println ("No content to
   transfer");
              return;
           }




                                    .c
        if (len == -1)
           {




                          DF
              System.out.println ("Content length not
   known");
           }
        InputStream in =
                   aP
   urlCon.getInputStream();
        FileOutputStream fout = new
           FileOutputStream
   ("c:kawaurl-spec.txt");
               vi

        while ( ((c=in.read()) != -1) )
        { fout.write(c);}
         ee


   in.close();
        fout.close();
        } }
      n




     •   Output
   w.




         Date: Wed Jun 13 06:34:31 GMT+05:30 2001
         Content type: text.plain;
         Last Modified: Thu Mar 31 20:18:08 GMT+05:30
ww




         1994
         Content length: 46204



   CKR                 Java Notes                  269
Sockets




                                         om
     •   A URL is for relatively high-level communication.

     •   Sometimes one must communicate with another




                                       .c
         machine at a lower level.

     •   For this, one uses sockets.




                            DF
     •   The socket concept was evolved with BSD Unix.

     •   The purpose of sockets is to permit
                    aP
         inter-process communication.

     •   A socket is one end of such an inter-process
         communication.
               vi

     •   Thus, a socket is like a telephone instrument
         which permits two persons to talk to each other.
         ee


     •   A socket may concurrently handle several
         processes.
      n




     •   Thus, a more precise analogy is that a socket is
   w.




         like an EPABX:
             –    there is only one telephone number
             – But there are several lines, so that
ww




             – several people can simultaneously
                  converse using that one number.



   CKR                  Java Notes                      270
Sockets (contd)




                                          om
     •   More precisely, a socket is one endpoint of a
         two-way communication link between two
         processes (running on a computer or a network).




                                      .c
             –   A socket is tied to a port number (to
                 enable the TCP layer to identify the




                            DF
                 application with which data is being
                 exchanged).

     •   From the user point of view, to create a socket,
                     aP
         or communicate with a socket one needs

             –   the IP address
                 vi

             –   the port number

             –   An InputStream/OutputStream object or
         ee


                 BufferedReader/PrintWriter object.

             –   Communication is subsequently like
      n



                 normal i/o via the i/o object.
   w.




     •   The IP address must be specified by the
         programmer or the user.
ww




   CKR                   Java Notes                      271
•    The port number depends upon the service.




                                         om
    •    For example:

            –    FTP: 21
            –    Telnet: 23




                                     .c
            –    SMTP: 25 (Simple Mail Transfer Protocol)
            –    Timeserver: 37




                            DF
            –    Nameserver: 42
            –    Whois: 43
            –    MTP: 57
            –    HTTP: 80
                    aP
            –    Servlets: 8080

    •    For more details on Port Numbers, see RFC
         1700.
                vi

    •    The java.net package contains various classes
         encapsulating sockets in a platform independent
         ee


         way.

    •    A key class which the programmer will use is the
      n



         class Socket, which implements client sockets.
   w.




    •    (For serverside-sockets there is a separate class
         called ServerSockets)
ww




   CKR                  Java Notes                     272
Sockets (contd)




                                        om
     •   The Socket class has several constructors, one
         of which has the following prototype:




                                     .c
   public Socket (InetAddress address, int
   Portno) throws IOException




                           DF
     •   The uses of this constructor are demonstrated in
         the following example which sends email, using
         SMTP.
                     aP
     •   (For more details on SMTP see RFC 821.)

    Program 46
   /*Program EMail.java
                vi

   Function: to send email across a socket*/

   import java.net.*;
         ee


   import java.io.*;

   public class EMail
      n



   {
      public static void main (String args[])
   w.




         throws Exception
      {
         Socket s;
ww




         //InetAddress Address =
   InetAddress.getByName ("mail.hotmail.com");
         InetAddress Address =


   CKR                  Java Notes                    273
InetAddress.getByName ("mail.vsnl.net");




                                 om
        System.out.println ("Address: " + Address);
        try {
        s = new Socket (Address, 25);
        //Port 25 is for SMTP: Simple Mail
   Transfer Protocol




                                 .c
        }




                       DF
        catch (Exception e)
        {
           System.out.println ("Error opening
   socket");
                 aP
           return;
        }
        System.out.println ("Opened socket");
        if (s==null) { return; }
                vi

         try{
         ee


           PrintWriter out = new
              PrintWriter (
   new OutputStreamWriter (s
      n



        .getOutputStream()), true);
        BufferedReader in = new
   w.




           BufferedReader ( new
              InputStreamReader ( s.
   getInputStream() ));
ww




        if (out==null || in==null)
        {System.out.println ("Failed to open
   stream to socket");


   CKR              Java Notes             274
return;




                                    om
         }

        String hostName =
   InetAddress.getLocalHost().getHostName();
        //String hostName = "Ghost";




                                    .c
        System.out.println ("Obtained i/o stream");
        String initID = in.readLine();




                          DF
        System.out.println (initID);

         out.println ("HELO " + hostName);
         System.out.println ("HELO " + hostName);
                   aP
         String resp = in.readLine();
         System.out.println (resp);
               vi

        out.println ("MAIL FROM:<"+
   "c_k_raju@hotmail.com"+">");
         ee


         String senderOK = in.readLine();
         System.out.println (senderOK);
      n



        out.println ("RCPT TO:<" +
   "c_k_raju@vsnl.net"+">");
   w.




         String recptOK = in.readLine();
         System.out.println (recptOK);
ww




         out.println ("DATA");
         out.println ("The quick brown fox has sent


   CKR                 Java Notes           275
you mail");




                                 om
        out.println (".");
        out.flush();
        s.close();
        }
        catch (IOException ex)




                                 .c
        {
           System.out.println ("IO Exception");




                       DF
        }

       }
   }
                 aP
     •   Output:
   Address: mail.vsnl.net/203.197.12.5
             vi

   Opened socket
   Obtained i/o stream
   220 mail02.vsnl.net ESMTP service
           ee


   (Netscape Messaging Server 4.15 Patch 2
   (built May 30 2000))
   HELO c
      n



   250 mail02.vsnl.net
   250 Sender <c_k_raju@hotmail.com> Ok
   w.




   250 Recipient <c_k_raju@vsnl.net> Ok
   Application Exit...
ww




   CKR              Java Notes               276
JDBC




                                           om
     •    JDBC stands for Java Data Base Connectivity.

     •    JDBC is different from ODBC in that




                                      .c
             – JDBC is written in Java (hence is
                 platform independent, object oriented
                 robust etc.), while




                             DF
             –    ODBC is written in C, is not object
                  oriented.
                     aP
     •    However, both JDBC and ODBC are based on the
          X/Open SQL Command Level Interface (CLI).

     •    Sun provides a JDBC ODBC bridge, which
                 vi

          enables one to connect painlessly to ODBC data
          sources.
          ee


     •    The following steps are involved.

     •    Step 1: Set up a Data Source Name, using the
      n



          ODBC administrator.
             – It is assumed that you already know how
   w.




                  to do this.

             –    The following example used Oracle 8
ww




                  Personal Edition, setting up a Data
                  Source Name called Test on the local
                  computer.


   CKR                   Java Notes                      277
–    But this would work just as well with




                                         om
                 Access or DBase or FoxPro.

     •   Step 2: Load and Register the JDBC driver.

            –    The following example supposes that




                                     .c
                 one is using the jdbc-odbc bridge driver
                 supplied by sun.




                            DF
            –    Loading and registering the driver is
                 done using the single statement.
                    aP
   Class.forName
   ("sun.jdbc.odbc.JdbcOdbcDriver");

     •   java.lang.Class is a public final class which
                vi

         descends directly from java.lang.Object (and
         implements Serializable)
         ee


     •   The forName method of class Class has the
         following prototype
      n



   public static Class forName (String
   className) throws ClassNotFoundException
   w.




     •   The exception is thrown if the class representing
         the driver is not found.
ww




     •   For the class name of other drivers, check the
         driver documentation.


   CKR                  Java Notes                        278
JDBC (contd)




                                          om
     •    Step 3: Connect to the database. Once the driver
          has been loaded, one must connect to the
          database (specified in the DSN)




                                      .c
     •   This is again achieved using a single statement
   DriverManager.getConnection(




                            DF
      url,
      user_login,
      user_password)
                     aP
     •    DriverManager is a public class which extends
          Object.
             – This class is located in the java.sql
                package.
                  vi

     •    getConnection is a public static method of the
          DriverManager class, with the following prototype
         ee


   public static Connection getConnection
   (String url, String user, String password)
      n



   throws SQLException
   w.




     •    This method is appropriately overloaded.
             – example one overloaded version will
                 take only the url, for databases which do
ww




                 not have a user login or user password
                 (such as DBaseIII)



   CKR                   Java Notes                    279
•   The meaning of user_login and user_password




                                           om
          is obvious.

     •   String url is specified as follows:
   "jdbc:subprotocol:DSN"




                                       .c
      •   For the present case of ODBC, if the Data Source
          Name is Test, the url would be specified as




                              DF
   "jdbc:odbc:Test"

      •   Connection is an interface defined in the
                      aP
          java.sql package.

      •   Step 4: Create an SQL statement.
                 vi

      •   This is done using the createStatement
          method of the Connection object returned by
          the getConnection method of Step 3.
          ee


      •  The createStatement method (appropriately
         overloaded) has a prototype
      n



   public Statement createStatement ()
      throws SQLException()
   w.




      •   Statement is an interface defined in the java.sql
          package:
ww




             – it is intended to represent an SQL
                 statement.



   CKR                    Java Notes                    280
JDBC (contd)




                                         om
     •   Step 5: Execute a given SQL statement
            – using the executeUpdate method of the
                 Statement object




                                     .c
            – returned by createStatement method
                 in Step 4.




                           DF
     •   Step 6: Close
            – the statement, and
            – the connection.
            – using the respective close methods.
                    aP
     •   This is demonstrated by the following example,
         which sets up a connection to a DSN called Test,
         and uses a simple SQL statement to create a
                  vi

         table called TEAS.

   Program 47
         ee


   import java.sql.*;
   public class JDBCMakeTea {
      n



   public static void main (String args[])
   {
   w.




      String myDriverName =
   "sun.jdbc.odbc.JdbcOdbcDriver";
      //the above is the fully qualified name of
ww




   the sun
      //jdbc-odbc bridge driver class.



   CKR                  Java Notes                    281
String url = "jdbc:odbc:test";




                                  om
     //the above string has the form
     //protocol:subprotocol:datasourcename
     //Thus test is the user DSN specified
     //in the ODBC administrator




                                  .c
     String myLogin = "DEMO"; //user name
     String myPassword = "demo"; //password




                        DF
     String sqlString =
        "create table TEAS " +
        "(TEA_NAME VARCHAR (32), " +
                  aP
        "SUP_ID INTEGER, " +
        "PRICE FLOAT, " +
        "SALES INTEGER, " +
        "TOTAL INTEGER)";
              vi

         try
         {
         ee


            Class.forName (myDriverName);
            //the forName method of java.lang.Class
            //will load and register the driver.
      n




         }
   w.




        catch (ClassNotFoundException e)
        {
ww




           System.err.println ("Error loading
   driver");
           return;


   CKR               Java Notes              282
}




                                          om
       try
       {
          Connection con =
             DriverManager.getConnection




                                       .c
              (url, myLogin, myPassword);
          //connect to database




                             DF
           Statement stmt =
              con.createStatement();
           stmt.executeUpdate (sqlString);
                      aP
           stmt.close();
           con.close();
       }
                 vi

       catch (SQLException ex)
       {
           ee


          System.err.println ("SQLException " +
             ex.getMessage());
       }
      n



   }
   }
   w.




       •   Output: if no error messages
              – a table called teas is created under the
ww




                   database connection called Test.




   CKR                    Java Notes                   283
JDBC: Executing a query




                                         om
     •   To summarise: the basic procedure is

             –   set up a DSN




                                     .c
             –   Load and Register the JDBC driver
             –   Connect to the DSN
             –   Create a SQL statement




                             DF
             –   execute the SQL statement
             –   close the statement and the connection.

     •   To execute a query a change is required only in
                    aP
         Step 5.

             –   Instead of the executeUpdate method
                 used to execute a SQL statement, we will
                 vi

                 use the executeQuery method of the
                 statement object.
         ee


             –   The executeUpdate method, returns an
                 int, and so is restricted to INSERT,
                 UPDATE and DELETE statements,
      n




             –   or SQL statements that return nothing
   w.




                 such as SQL DDL (Data Definition
                 Language) statements, such as CREATE,
                 ALTER, DROP
ww




   CKR                  Java Notes                    284
•   A query however, returns a result set.




                                             om
            –    A result set is encapsulated in the
                 interface ResultSet of the java.sql
                 package.




                                       .c
     •   A ResultSet object maintains a cursor pointing
         to the current row of data.




                              DF
            –    It is initially set to point before the first
                 row.
                     aP
     •   The next method of the ResultSet object
         moves the cursor to the next row.

     •   Various getXXX methods return the values of the
                vi

         columns in the ResultSet.

     •   These considerations are illustrated by the
         ee


         following program.

   Program 48
      n




   import java.sql.*;
   w.




   public class JDBCAddTea
   {
      public static void main (String args[])
ww




      {
         String myDriverName =
   "sun.jdbc.odbc.JdbcOdbcDriver";


   CKR                    Java Notes                         285
//the above is the fully qualified name of




                                  om
   the sun
      //jdbc-odbc bridge driver class.

     String url = "jdbc:odbc:test";
     //the above string has the form




                                  .c
     //protocol:subprotocol:datasourcename6
     //Thus test is the user DSN specified




                        DF
     //in the ODBC administrator

     String myLogin = "DEMO"; //user name
     String myPassword = "demo"; //password6
                  aP
      String sqlString;
      Connection con; //Connection is an
   interface
              vi

      Statement stmt; //Statement is an interface

         try
         ee


         {
            Class.forName (myDriverName);
            //the forName method of java.lang.Class
      n



            //will load and register the driver.
   w.




         }

        catch (ClassNotFoundException e)
ww




        {
           System.err.println ("Error loading
   driver");


   CKR               Java Notes             286
return;




                                    om
         }

     try
     {
        con =




                                    .c
           DriverManager.getConnection
            (url, myLogin, myPassword);




                          DF
        //connect to database
        stmt =
           con.createStatement();
        //so far this is standard for any
                   aP
        //JDBC program.
        //we now change the sql command.
        sqlString =
        "insert into TEAS " +
               vi

        "values (’Darjeeling’, 201, 400.5, 0, 0)";

         stmt.executeUpdate (sqlString);
         ee


            sqlString =
         "insert into TEAS " +
      n



         "values (’Assam’, 202, 56.3, 0, 0)";
   w.




         stmt.executeUpdate (sqlString);

            sqlString =
ww




         "insert into TEAS " +
         "values (’Nilgiri’, 203, 100.5, 0, 0)";



   CKR                 Java Notes           287
stmt.executeUpdate (sqlString);




                                    om
            sqlString =
         "insert into TEAS " +
         "values (’Sri Lanka’, 501, 200.4, 0, 0)";




                                  .c
         stmt.executeUpdate (sqlString);




                        DF
         //We now execute a query

         String query =
         "select TEA_NAME, PRICE from TEAS";
                  aP
         //The results of the query are put into
         //an object of type result set.
         //ResultSet is an interface in java.sql
              vi

         ResultSet rs = stmt.executeQuery (query);
         ee


         System.out.println
         ("Tea Break: Teas and their prices: ");
      n



         while
         (rs.next())
   w.




         {
            String s = rs.getString ("TEA_NAME");
            float f = rs.getFloat ("PRICE");
ww




            System.out.println (s + " " + f);
         }



   CKR               Java Notes                288
//now put in the standard JDBC




                                    om
           //closing process.

           stmt.close();
           con.close();
       }




                                    .c
       catch (SQLException ex)
       {




                           DF
         System.err.println ("SQLException " +
             ex.getMessage());
       }
   }
                     aP
   }


       •   Output:
                vi

   Tea Break: Teas and their prices:
   Darjeeling 400.5
           ee


   Assam 56.3
   Nilgiri 100.5
   Sri Lanka 200.4
      n
   w.
ww




   CKR                 Java Notes            289
JDBC: New Features of the Java 2.0 API




                                            om
     •   Certain new features are incorporated in the
         JDBC API available with JDK1.2




                                      .c
     •   ResultSets are scrollable both backward and
         forward.




                            DF
             –   In JDK 1.0 one could only move forward
                 using the next() method.
             –   We now have the
                 previous()
                     aP
                 absolute(int)
                 relative (int)
                 methods, along with other methods.
                 vi

             –   One can now declare the ResultSet to be
                 of type
                 TYPE_FORWARD_ONLY
         ee


                 TYPE_SCROLL_INSENSITIVE (changes
                 are not reflected while the result set is
                 open)
      n



                 TYPE_SCROLL_SENSITIVE (changes
                 are reflected immediately)
   w.




     •   Updates can be made to database tables using
         Java API methods instead of using SQL
ww




         commands.




   CKR                   Java Notes                     290
–   For example insertRow() method will




                                        om
                insert a row in the present location.

    •    Multiple SQL statements can be sent to the
         database, as a unit or a batch.




                                     .c
    •    The new SQL3 datatypes can be used as column
         values.




                           DF
             – These include
                 BLOB (Binary Large Object)
                 CLOB (Character Large Object)
                 Array
                    aP
                 Struct to map SQL user defined types.


    •    For further information on using these methods,
                vi

         consult the API documentation.
      n  ee
   w.
ww




   CKR                  Java Notes                      291
Remote Method Invocation




                                           om
     •   So far, all applications have been running on one
         (local) Java Virtual Machine.




                                      .c
     •   The RMI technology makes it possible to have an
         object distributed across JVM’s.




                             DF
     •   RMI applications typically take the form of
         client-server applications.

     •   When combined with the standard polymorphic
                     aP
         features, this can lead to a situation where
             – a fast server executes a task
             – which it does not know about at compile
                 time.
               vi

     •   The following program provides an example of
         how this "RMI magic" is achieved.
         ee


     •   Basically, the server downloads from the client,
         the byte code of the class to be executed.
      n




     •   After completing execution, it uploads the code
   w.




         back again.

     •   This is done in a platform independent way.
ww




     •   It is also done in a secure way, as follows.



   CKR                   Java Notes                     292
RMI: Security




                                            om
     •    Due attention has to be paid to the security
          aspects.




                                       .c
     •    An RMI program will NOT run, until a security
          manager has been installed,
             – and a policy file has been created




                              DF
             – with the appropriate permissions.

     •    A security manager is installed through a single
          line of code:
                      aP
   System.setSecurityManager (new
   RMISecurityManager());
                   vi

     •    The policy file typically has the name
             – java.policy
             – and is located in the C:windows file
         ee


             – but could be located anywhere.

     •    A sample file is provided in JRElibjava.policy.
      n




     •    This file may be edited with the policytool
   w.




          which is a part of the JDK.

             –     and the appropriate permissions must
ww




                   be granted.




   CKR                    Java Notes                      293
RMI: Stubs and Skeletons




                                           om
     •    Classes capable of being invoked remotely have
          stubs and skeletons.




                                       .c
     •   Stubs and Skeletons are surrogates (proxies)
             – Stubs are client side, and
             – Skeletons are server side




                              DF
   surrogates (proxies) for RMI capable classes.

     •    From Java 1.2 onwards, Skeletons are no longer
          used. Related methods are fully deprecated, with
                     aP
          no substitute.

     •    However, stubs and skeletons must still be
          generated,
                vi

             – for backward compatibility with Java 1.1,
                 which may be running on the remote
                 machine.
         ee


     •    Stubs and skeletons are generated from the
          compiled classes by using the Java rmi
      n



          compiler tool
             – rmic
   w.




   which is part of the JDK toolkit.

     •    (This tool is to be used after javac has been used
ww




          to compile the program and create the relevant
          classes. )



   CKR                    Java Notes                     294
RMI: registration




                                          om
     •    Before an RMI class can be invoked, it must be
             – (a) started
             – (b) registered in a special registry called




                                      .c
                  the RMI registry.

     •    This is achieved through




                             DF
             – API calls, and
             – the rmiregistry tool

   The foregoing considerations are illustrated by the
                       aP
   following example.
                 vi
      n   ee
   w.
ww




   CKR                   Java Notes                      295
RMI: Example




                                           om
     •   This example creates a server process which
            – accepts tasks from clients
            – returns the results to the clients.




                                      .c
     •   The server process involves three pieces of
         code.




                             DF
     •   (1) an interface definition
             – interface RMIdoTask
             – in package rmitask
                     aP
     •   (2) a second interface used in the first interface
             – interface Task
             – in package rmitask.
                vi

     •   (3) an implementation of the interface defined in
         the code in (1) above.
         ee


            –     class MyRMI
            –     in package rmiclass.
      n



     •   The client process involves two pieces of code.
   w.




     •   (4) A class Pi which implements the interface
         Task
             – and knows how (has a method ) to
ww




                  calculate the value of Pi.
     •   (5) A class CalcPI which invokes the remote
         method.


   CKR                   Java Notes                       296
RMI Example (contd): RMIDoTask.java




                                           om
     •    Step 1: Define the first remote interface
         .
     •   The key idea is that a remotely accessible object




                                      .c
         must extend the interface java.rmi.Remote.

     •   The code is as follows.




                             DF
     •   File: rmitask/RMIDoTask.java

   package rmitask;
                     aP
   import java.rmi.Remote;
    import java.rmi.RemoteException;

   //all remotely accessible interfaces must
               vi

   //have the above two import statements.
   //An object declares itself as Remote
   //by extending java.rmi.Remote.
         ee


   public interface RMIDoTask
      extends Remote
      n



      {    Object doTask (Task t)
           throws RemoteException;
   w.




      }

     •   java.rmi.RemoteException is a subclass of
ww




         IOException, and is, hence, a checked exception.

     •   Task is an interface to be defined.


   CKR                   Java Notes                    297
RMI Example (contd): Interface Task




                                            om
     •    The interface Task used in the previous piece of
          code is defined as follows.




                                       .c
     •    The key idea is that RMi uses Serialization to
          transport the object from one Java Virtual
          Machine to another.




                              DF
              – by converting the object into a byte
                 stream, and reconverting the stream
                 back into an object.
              – Hence RemoteException is a kind of
                      aP
                 IOException.

     •    Serialization or object persistence is achieved
          through extending the interface Serializable.
                vi

     •    The Serializable interface has no methods,
          and this is mainly a matter of the object
         ee


          semantics to declare that the object is persistent.

     •    This interface must be defined in a separate file,
      n



          since all remote interfaces have to be public.
   w.




   package rmitask;
   import java.io.Serializable;
   public interface Task extends Serializable
ww




   {
      Object execute();
   }


   CKR                    Java Notes                       298
RMI Example (contd): Class MyRMI




                                             om
     •   To make a remote object, one simply implements
         a remote interface.




                                     .c
     •   This is done in the file MyRMI.java, which is put
         into a separate package rmiclass, to separate the
         interface definition from its implementation.




                            DF
     •   The public class MyRMI

             –   implements the interface RMIDoTask.
                    aP
             –   It also extends the class
                 UnicastRemoteObject
                 vi

     •   Extending this class is NOT mandatory. (Error in
         Java 2 Complete Reference, p 834) .
         ee


             –   However, this is a convenience class
                 which provides appropriate rmi
                 implementations of the methods
      n




             –   which override the methods of the object
   w.




                 class.

             –   A class which does not extend
ww




                 UnicastRemoteObject, e.g. it simply
                 extends RemoteObject



   CKR                  Java Notes                      299
–   must provide its own implementation of




                                         om
                the methods in the Object class.

     •   Additionally, this class must
            – (i) construct at least one instance of the
                 remote object




                                     .c
            – (ii) register it
            – (iii) declare a security policy.




                            DF
     •   The code in rmiclass/MyRMI.java is as follows.

   package rmiclass;
                    aP
   import java.rmi.*;
   import java.rmi.server.*;
                vi

   import rmitask.*;

   public class MyRMI extends
         ee


      UnicastRemoteObject
      implements RMIDoTask
      n



     {
         //define a constructor
   w.




         public MyRMI () throws
            RemoteException
            {
ww




               super();
               //optionally a port no. can
               //be specified.


   CKR                  Java Notes                    300
//call to super also "exports’ the




                                   om
               //rmi object: i.e., makes it listen
               //to remote calls on port 1099.

           }




                                   .c
         //implement the remote interface




                         DF
         public Object doTask (Task t)
         {
            return t.execute();
         }
                  aP
         //start at least one instance
         //of the remote object
         //register it
               vi

         //and declare a security policy.

         public static void main (String args[])
         ee


         {
            //install a standard rmi security manager
            //if none is installed.
      n




           if (System.getSecurityManager()==null)
   w.




           {
              System.setSecurityManager(
              new RMISecurityManager ());
ww




           }
           try
           {


   CKR                Java Notes             301
//declare an instance of the remote object




                                  om
              RMIDoTask rm = new MyRMI();

              //decide a name for it

              String name = " RMITask";




                                  .c
           //name must have the above form




                        DF
           //optionally a port no. may be specified
           //host:porno.
              //if no port number is specified
              //port 1099 is used.
                  aP
   //register (bind) the name in the
   //rmiRegistry
              vi

              Naming.rebind (name, rm);

   //we use rebind instead of bind to
         ee


   //avoid exceptions, if name is already
   //bound
   //report success
      n




         System.out.println ("RMITask registered");
   w.




               }
               catch (Exception e)
               {
ww




            System.err.println ("MyRMI exception:" +
                                     e.getMessage());
               }}}


   CKR               Java Notes             302
RMIExample (contd): The client class CalcPI




                                            om
     •    The RMI Client must also set up a security
          manager.




                                       .c
     •    It simply looks up the name of the rmi object in
          the rmiregistry.




                              DF
     •    and passes the task to it.

     •    The task in this case is to calculate pi to an
          arbitrary number of decimal places.
                      aP
     •    Hence the class java.math.BigDecimal is used to
          permit arbitrary precision arithmetic.
                vi

     •   The code for the RMI client CalcPI (main method)
         is as follows.
   package rmiclient;
         ee


   import java.rmi.*;
   import java.math.*;
      n



   import rmitask.*;
   w.




   public class CalcPi
   { public static void main (String args[])
      {
ww




        //load rmisecurity manager
        //else rmi call will fail.



   CKR                    Java Notes                       303
if (System.getSecurityManager()==null)




                                  om
            System.setSecurityManager
            (new RMISecurityManager() );
          try
          {
            String name = "//"+args[0]+"/RMITask";




                                  .c
            //args[0] is the host name: portno
            //if nothing is specified




                        DF
            //local host is used on port 1099.

           RMIDoTask rm1 = ((RMIDoTask)
   Naming.lookup (name));
                  aP
           Pi myPi = new Pi (Integer.parseInt
   (args[1]));
      //The class Pi is defined elsewhere.
              vi

      //args[1] is the number of decimal places
      //to which the value of Pi should be
      //computed.
         ee


         BigDecimal pivalue = (BigDecimal)
            (rm1.doTask (myPi));
      n



         System.out.println (pivalue);
         }
   w.




         catch (Exception e)
         {
            System.err.println ("CalcPi exception: "
ww




               + e.getMessage() ) ;
               e.printStackTrace();
            } }}


   CKR               Java Notes             304
RMIExample (contd): the client class Pi




                                             om
     •    The last piece of code is the class Pi, which
          actually calculates the value of Pi.




                                       .c
     •    This is done using the power series expansion
          for the arctangent function.




                             DF
     •    This expansion was first put forward by Madhava
          of Sangamagrama, and is found in the MSS of
          Neelkantha Somayajulu’s TantraSangraha, and
          Jyeshtadeva’s Yuktibhasa.
                      aP
     •    This class implements the task interface.

     •    The rest of the code for this class is
                vi

          straightforward, and does not require much
          explanation.
         ee


     •
   package rmiclient;
      n



   import rmitask.*;
   import java.math.*;
   w.




   public class Pi
     implements Task
ww




   {
       private static final BigDecimal ZERO =
          BigDecimal.valueOf(0);


   CKR                    Java Notes                      305
//class BigDecimal implements




                                 om
     //arbitrary precision arithmetic.

     private static final BigDecimal ONE =
           BigDecimal.valueOf(1);
     private static final BigDecimal FOUR =




                                 .c
        BigDecimal.valueOf(4);




                       DF
     private static final int roundingMode
     = BigDecimal.ROUND_HALF_EVEN;

      //specifies rounding mode
                 aP
      //The above mode rounds to nearest
   neighbour
      //or the even number if both neighbours
      //are equidistant.
             vi

     private int precision;
         ee


     public Pi (int precision)
     {
        this.precision = precision;
      n



     }
     //define the execute method
   w.




     //of the Task interface

     public Object execute()
ww




     {
        return findPi (precision);
     }


   CKR              Java Notes               306
om
     /*
     find the value of pi using the formula
     so called "Machin’s formula"
     pi/4 = 4*arctan (1/5) - arctan (1/239)
     and the power series expansion for




                                  .c
     arctan
     */




                        DF
      public static BigDecimal findPi (int
   precision)
                  aP
     {
        int scale = precision + 5;
        BigDecimal arctan_1by5 = arctani (5,
   scale);
              vi

        BigDecimal arctan_1by239 = arctani (239,
   scale);
         ee


         BigDecimal pivalue =
            arctan_1by5.multiply (FOUR).
               subtract( arctan_1by239).multiply(FOUR);
      n




         return pivalue.setScale (precision,
   w.




            BigDecimal.ROUND_HALF_UP);
         }
ww




         /*The power series for the arctangent is
         arctan (x) = x - (x^3)/3
              + (x^5)/5


   CKR               Java Notes                307
- (x^7)/7




                                    om
                + (x^9)/9
                - ...
         */

         public static BigDecimal arctani




                                    .c
            (int inverseX, int scale)
         //calculates arctan of the inverse of




                            DF
         //inverseX
         //to precision scale.

         {
                    aP
           BigDecimal result, numerator, term;
           BigDecimal invX = BigDecimal.valueOf
   (inverseX);
           BigDecimal invX2 =
                vi

   BigDecimal.valueOf(inverseX * inverseX);
           numerator = ONE.divide(invX, scale,
   roundingMode);
         ee


              result = numerator;
      n



           int i=1;
           do
   w.




           {
              numerator =
              numerator.divide (invX2, scale,
ww




   roundingMode);
              int denominator = 2*i+1;
              term =


   CKR                 Java Notes           308
numerator.divide(BigDecimal.valueOf




                                 om
   (denominator), scale, roundingMode);
              if ((i%2) == 0)
              {
              result = result.add(term);
              }




                                 .c
              else
              {




                       DF
              result = result.subtract(term);
              }
              i++;
              } while (term.compareTo(ZERO) != 0 ) ;
                 aP
              return result;
           }
        }
             vi
      n  ee
   w.
ww




   CKR              Java Notes             309
RMI example: Compiling and running the code




                                             om
     •    Step 1: Compile all the .java files into classes.

     •    This must be done in the following order.




                                       .c
              – rmitask/Task.java
              – rmitask/RMIDoTask.java
     •    The resulting classes should be available in the




                              DF
          classpath before the following is compiled.
              – rmiclass/MyRMI.java.

     •    Step 2: To make the classes available, put them
                      aP
          in a jar file, by using the command

   jar cvf rmitask.jar rmitask/*.class
                vi

     •   and add the file rmitask.jar in the CLASSPATH.
   set
   CLASSPATH=C:KAWArmitask.jar;%CLASSPATH%
         ee


     •    now the file rmiclass/MyRMI.java can be
          compiled.
      n




     •    Step 3: Create the stub and skeleton class by
   w.




          using the following command.

   rmic -d . rmiclass rmiclass.MyRmi
ww




     •    The -d option will place the resulting classes in
          the rmiclass directory.


   CKR                    Java Notes                          310
RMI Example: Compiling and running (contd)




                                           om
     •   Step 4: Build the client classes, using the above
         set CLASSPATH.




                                      .c
     •   Step 5: Declare a security policy.

             –   a sample security policy file exists in the




                             DF
                 jdk1.2.2/jre/lib/security/java.policy file.

             –   This file could be copied to any
                 convenient location, such as
                     aP
                 c:windows.

     •   invoke policytool
                 vi

             –   Open the c:windowsjava.policy file.
             –   choose codebase <ALL>
             –   Add permission: SocketPermission
         ee


             –   Target: *:1024-65535
             –   Actions: accept, connect, listen, resolve
      n



             –   Add permission: File permissions
             –   Target: c:kawa-
   w.




             –   Actions: read

             –   Add permission: File Permission
ww




             –   Target: c:kawarmitask.jar
             –   Actions: read



   CKR                   Java Notes                      311
•   This will add the following lines of code in the




                                           om
         policy file.

   grant
   {
      permission java.net.SocketPermission




                                      .c
   "*:1024-655535, "accept, connect, listen,
   resolve";




                             DF
   /* This grants permission to processes
   using non-privileged ports above 1024.
   Recall that rmi uses port 1099 by default*/
                     aP
     permission java.io.FilePermission
   "c:kawa-", "read";
   }
               vi

     •   The above lines could be added by hand as well.
         ee


     •   Basically, the first line grants permission to
         processes to use non-privileged ports (with port
      n



         numbers above 1024.
   w.




     •   The second line grants permission to processes
         to read all files in the c:kawa directory.
ww




   CKR                   Java Notes                         312
RMI Example: compiling and running the code (contd)




                                          om
     •   Step 6:
            – (a) Unset the classpath, and
            – (b) start the rmiregistry.




                                      .c
     •   This is achieved through the following
         commands.




                            DF
   set CLASSPATH=
   start rmiregistry
                    aP
     •   Step 7: Next one must start the server process.

     •   This may be done using a batch file (since the
         command line buffer may not contain the entire
                vi

         command)

     •   The batch file rmstart.bat has the following
         ee


         contents.

   set
      n



   CLASSPATH=.;C:kawa;c:kawarmitask.jar
   java
   w.




   -Djava.rmi.server.codebase=file:c:kawa/
      -Djava.rmi.server.hostname=127.0.0.1
      -Djava.security.policy=
ww




         c:windowsjava.policy
      rmiclass.MyRMI 127.0.0.1 10



   CKR                   Java Notes                     313
•   Step 8: Finally start the client process, and




                                           om
         request a value of pi correct to 10 decimal
         places.

     •   This may be done through the batch file
         rmicli.bat which has the following contents.




                                      .c
   set CLASSPATH=.;C:KAWA;C:KAWArmitask.jar




                             DF
   java
   -Djava.rmi.server.codebase=file:c:kawa/
   -Djava.security.policy=
        c:windowsjava.policy
                     aP
   rmiclient.CalcPi 127.0.0.1 10

     •   Output: 3.1415926536
               vi
      n  ee
   w.
ww




   CKR                   Java Notes                      314
JFC and Swing




                                              om
     •   Since java aims to be platform independent.

     •   And, since the behaviour of windows is different




                                       .c
         on different platforms (Mac, X, MSWindows)

            –      this presents a problem.




                             DF
     •   The AWT (abstract Windows toolkit) was the first
         answer to this problem.
                      aP
     •   The Swing API is the second answer to this
         problem.

     •   Swing API are "lightweight" since they are
                vi

         written entirely in Java.

     •   Nevertheless, they offer many of the GUI
         ee


         features of, say, MS-Windows programming.

     •   In this respect, Java Foundation Classes are like
      n



         Microsoft Foundation classes:
             – They make windowed programs much
   w.




                  easier to write.

     •   Before proceeding further, let us take a few
ww




         examples.




   CKR                    Java Notes                    315
Java Swing: Hello World




                                     om
   /*First JFC program */

   import java.awt.*;




                                     .c
   import java.awt.event.*;
   import javax.swing.*;




                             DF
   public class JHelloWorld extends
      JPanel
   {
      static JFrame jf;
                    aP
      public JHelloWorld ()
      {
           JLabel lb = new JLabel
              ("Hello JFC World");
               vi

           add (lb);
      }
         ee


   public static void main
      ( String args[] )
   {
      n



   jf = new JFrame ("Hello JFC World");
   JHelloWorld jHello = new JHelloWorld();
   w.




   jf.getContentPane().add("Center", jHello);
   jf.setSize (250, 150);
   jf.addWindowListener
ww




        (new WindowAdapter()
           {
              public void windowClosing


   CKR                  Java Notes         316
(WindowEvent e)




                                          om
                   {
                   System.exit(0);
                   }
               }
          );




                                       .c
       jf.setVisible (true);
       }




                             DF
   }

       •   This program has the following output.
                      aP
                                                    •
                   vi
      n    ee
   w.
ww




   CKR                    Java Notes                317
More Swing




                                           om
     •   To get a better feel for some of the features of
         Swing, try the following program.
   import java.awt.*;




                                       .c
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.event.*;




                              DF
   import javax.swing.border.*;

   public class JSwingStart extends Frame {
    public static int WIDTH = 450;
                      aP
    public static int HEIGHT = 450;
    public static String TITLE = "SwingStart";

    // Swing components
                 vi

    JTabbedPane tabbedPane = new
   JTabbedPane();
    JPanel buttonPanel = new JPanel();
          ee


    JPanel barPanel = new JPanel();
    JPanel listPanel = new JPanel();
    JPanel tablePanel = new JPanel();
      n



    JPanel[] panels =
   {buttonPanel,barPanel,listPanel,tablePanel};
   w.




    Icon worldIcon = new
   ImageIcon("world.gif");
ww




    Icon printerIcon = new
   ImageIcon("printer.gif");
    Icon leaf1Icon = new


   CKR                    Java Notes                        318
ImageIcon("leaf1.gif");




                                 om
    Icon leaf2Icon = new
   ImageIcon("leaf2.gif");
    Icon leaf3Icon = new
   ImageIcon("leaf3.gif");
    Icon[] leaves = {leaf1Icon, leaf2Icon,




                                 .c
   leaf3Icon};
    JButton printerButton = new




                       DF
   JButton("Print",printerIcon);
    JToggleButton worldButton = new
   JToggleButton("Connect",worldIcon,true);
    JList leafList = new JList(leaves);
                 aP
    JSlider slider = new
   JSlider(JSlider.VERTICAL, 0, 100, 60);
    JProgressBar progressBar = new
   JProgressBar();
             vi

    String[] columns = {"Product
   ID","Description","Price"};
    Object[][] cells =
         ee


   {columns,{"zvga-1234","Video Card","$50"},
     {"56m-11","56K Modem","$315"},
     {"dc-10","Net Card","$499"}};
      n



    JTable table = new JTable(cells,columns);
   w.




    public JSwingStart() {
     super(TITLE);
     addWindowListener(new WindowHandler());
ww




     buildGUI();
     setSize(WIDTH,HEIGHT);
     setBackground(Color.darkGray);


   CKR              Java Notes             319
show();




                                   om
   }

    void buildGUI() {
     // Set up tabbed pane
     String[] tabs =




                                 .c
   {"Buttons","Bars","Lists","Table"};
     String[] tabTips = {"A Button and a




                       DF
   Toggle Button",
      "A Slider and a Progress Bar",
      "An Icon List",
      "A Cost Table"};
                 aP
     for(int i=0;iabs.length;++i) {

   panels[i].setBackground(Color.lightGray);
      panels[i].setBorder(new
               vi

   TitledBorder(tabTips[i]));

   tabbedPane.addTab(tabs[i],null,panels[i],tab
         ee


   Tips[i]);
      }
      addComponentsToTabs();
      n



      add("Center",tabbedPane);
    }
   w.




    void addComponentsToTabs() {
     setupButtonPanel();
ww




     setupBarPanel();
     setupListPanel();
     setupTablePanel();


   CKR              Java Notes             320
}




                                    om
    void setupButtonPanel() {
      printerButton.setBackground(Color.white);
      worldButton.setBackground(Color.white);
      buttonPanel.add(printerButton);




                                    .c
      buttonPanel.add(worldButton);
    }




                          DF
    void setupBarPanel() {
     slider.setMajorTickSpacing(10);
     slider.setMinorTickSpacing(5);
                    aP
     slider.setPaintTicks(true);
     slider.addChangeListener(new
   SliderHandler());
                vi

   progressBar.setOrientation(JProgressBar.HORI
   ZONTAL);
     progressBar.setMinimum(0);
           ee


     progressBar.setMaximum(100);
     progressBar.setValue(60);
     progressBar.setBorderPainted(true);
      n



     barPanel.add(new JLabel("Slider"));
     barPanel.add(slider);
   w.




     barPanel.add(new JLabel("Progress Bar"));
     barPanel.add(progressBar);
   }
ww




       void setupListPanel() {
        leafList.setFixedCellHeight(123);


   CKR                 Java Notes           321
listPanel.add(leafList);




                                           om
    }

    void setupTablePanel() {
      tablePanel.add(table);
    }




                                        .c
     public static void main(String[] args) {




                              DF
         JSwingStart app = new JSwingStart();
     }
     public class WindowHandler extends
   WindowAdapter {
                       aP
       public void windowClosing(WindowEvent e)
   {
         System.exit(0);
       }
                  vi

     }
     public class SliderHandler implements
   ChangeListener {
            ee


       public void stateChanged(ChangeEvent e) {
         progressBar.setValue(slider.getValue());
       }
      n



     }
   }
   w.




        •   This program has the following output.
ww




   CKR                     Java Notes                322
ww




CKR
                w.
                   nee
                       vi
                         aP




Java Notes
                            DF
                                 .c
                                      om


323
DF
         aP
        vi
       ee
       Packages and
   .n

        Class path
   w
ww




                      1
DF
                What are Packages?




                      aP
 ●   A package is a grouping of related types providing


                  vi
     access protection and name space management
         Note that types refers to classes, interfaces,
     –
            ee
         enumerations, and annotation types.
     –   Types are often referred to simply as classes and
         .n

         interfaces since enumerations and annotation types are
         special kinds of classes and interfaces, respectively, so
   w


         types are often referred to simply as classes and
         interfaces.
ww




                                                                     2
DF
             Benefits of Packaging




                    aP
 ●   You and other programmers can easily determine that


                vi
     these classes and interfaces are related.
           ee
 ●   You and other programmers know where to find
     classes and interfaces that can provide graphics-
     related functions.
       .n

 ●   The names of your classes and interfaces won't conflict
     with the names in other packages because the
   w


     package creates a new namespace.
ww



 ●   You can allow classes within the package to have
     unrestricted access to one another yet still restrict
     access for types outside the package.

                                                               3
DF
        aP
        vi
       ee
   .n
   w


  Creating a Package
ww




                       4
DF
                 Creating a Package




                     aP
 ●   To create a package, you choose a name for the


                  vi
     package and put a package statement with that name
     at the top of every source file that contains the types
             ee
     (classes, interfaces, enumerations, and annotation
     types) that you want to include in the package
          .n
 ●   If you do not use a package statement, your type ends
     up in an unnamed package
   w


      –   Use an unnamed package only for small or temporary
ww



          applications




                                                               5
DF
       Placing a Class in a Package




                   aP
 ●   To place a class in a package, we write the following as


                vi
     the first line of the code (except comments)
           ee
     package <packageName>;
     package myownpackage;
   w   .n
ww




                                                                6
DF
                            Example Package




                                  aP
 ●   Suppose you write a group of classes that represent



                          vi
     graphic objects, such as circles, rectangles, lines, and
     points     ee
 ●   You also write an interface, Draggable, that classes
     implement if they can be dragged with the mouse
        .n
      //in the Draggable.java file
      public interface Draggable {}

      //in the Graphic.java file
   w

      public abstract class Graphic {}

      //in the Circle.java file
ww



      public class Circle extends Graphic implements Draggable {}

      //in the Rectangle.java file
      public class Rectangle extends Graphic implements Draggable { }

      //in the Point.java file
      public class Point extends Graphic implements Draggable {}

      //in the Line.java file
      public class Line extends Graphic implements Draggable {}
                                                                        7
DF
  Example: Placing StudentRecord




               aP
  class in SchoolClasses pacakge
  package SchoolClasses;




           vi
  public class StudentRecord {
         ee
     private String   name;
     private String   address;
   .n
     private int      age;
     :
   w
ww




                                   8
DF
        aP
        vi
       ee
   .n

  Importing and Using
   w


   classes from other
ww




       Packages
                        9
DF
           Using Classes from Other




                      aP
                  Packages
 ●   To use a public package member (classes and


                  vi
     interfaces) from outside its package, you must do one
     of the following
            ee
     –   Import the package member using import statement
     –   Import the member's entire package using import
         .n

         statement
   w

     –   Refer to the member by its fully qualified name (without
         using import statement)
ww




                                                                    10
DF
               Importing Packages




                     aP
 ●   To be able to use classes outside of the package you are


                 vi
     currently working in, you need to import the package of
     those classes.
           ee
 ●   By default, all your Java programs import the java.lang.*
     package, that is why you can use classes like String and
       .n
     Integers inside the program even though you haven't
     imported any packages.
   w


 ●   The syntax for importing packages is as follows:
         import <nameOfPackage>;
ww




                                                                 11
DF
  Example: Importing a Class or a




             aP
             Package
  // Importing a class



          vi
  import java.util.Date;
       ee
  // Importing all classes in the
   .n
  // java.util package
  import java.util.*;
   w
ww




                                    12
DF
  Using Classes of other packages




                  aP
       via fully qualified path


              vi
  public static void main(String[] args) {
         ee
      java.util.Date x = new java.util.Date();
  }
   w  .n
ww




                                                 13
DF
      Package & Directory Structure




                   aP
 ●   Packages can also be nested. In this case, the Java


               vi
     interpreter expects the directory structure containing
     the executable classes to match the package hierarchy.
           ee
 ●   There should have same directory structure,
     ./myowndir/myownsubdir/myownpackage directory for
       .n
     the following package statement
     package myowndir.myownsubdir.myownpackage;
   w
ww




                                                              14
DF
        aP
        vi
       ee
   .n
   w


   Managing Sources
ww




     & Class files
                      15
DF
 Managing Source and Class Files




                       aP
 ●   Create a *.java file for the class you want to create


                   vi
      // in the Rectangle.java file
      package graphics;
             ee
      public class Rectangle() {
         ...
          .n
      }
 ●   Place the source file in a directory whose name reflects
   w


     the name of the package to which the class belongs
      –   .....graphicsRectangle.java
ww




                                                                16
DF
 Directory Structure of Java Source




                     aP
                Files
 ●   The qualified name of the class file and the path name


                 vi
     to the Java source file are parallel
           ee
 ●   Like the .java source files, the compiled .class files
     should be in a series of directories that reflect the
     package name
       .n

 ●   Example
   w


      class name:              graphics.Rectangle
      pathname to source file: graphics/Rectangle.java
ww



      pathname to the class file: graphics/Rectangle.class



                                                              17
DF
 Directory Structure of Java Source




                    aP
                Files
 ●   However, the path to the .class files does not have to


                vi
     be the same as the path to the .java source files. You
     can arrange your source and class directories
           ee
     separately, as:
      <path_one>sourcescomexamplegraphicsRectangle.java
      .n
      <path_two>classescomexamplegraphicsRectangle.class
 ●   By doing this, you can give the classes directory to
   w


     other programmers without revealing your sources
ww



 ●   You also need to manage source and class files in this
     manner so that the compiler and the Java Virtual
     Machine (JVM) can find all the types your program
     uses
                                                                18
ww
        w          .n
                     ee
                          vi
                            aP
                               DF
      Class path

19
DF
              What is a class path?




                     aP
 ●   It is a set of directories where Java class files are


                 vi
     located
           ee
 ●   Java runtime searches for class files in the directories
     specified in the class path in the order specified
   w   .n
ww




                                                                20
DF
           Setting the CLASSPATH




                    aP
 ●   Now, suppose we place the package schoolClasses


                vi
     under the C: directory.
           ee
 ●   We need to set the classpath to point to that directory
     so that when we try to run it, the JVM will be able to see
       .n

     where our classes are stored.
   w


     Before we discuss how to set the classpath, let us take
ww



 ●

     a look at an example on what will happen if we don't set
     the classpath.

                                                                  21
DF
             Setting the CLASSPATH




                        aP
   ●   Suppose we compile and then run the StudentRecord


                   vi
       class we wrote in the last section,
             ee
C:schoolClasses>javac StudentRecord.java

C:schoolClasses>java StudentRecord
Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecord
         .n
(wrong name: schoolClasses/StudentRecord)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
   w

        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
ww



        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
                                                                           22
DF
            Setting the CLASSPATH




                     aP
 ●   To set the classpath in Windows, we type this at the


                 vi
     command prompt,
            ee
     C:schoolClasses> set classpath=C:
     –   assuming C: is the directory in which we have placed the
         packages meaning there is a directory C:schoolClasses
         .n

         and there is a C:schoolClassesStudentRecord.class
   w


 ●   After setting the classpath, we can now run our
ww



     program anywhere by typing,
     C:schoolClasses> java
       schoolClasses.StudentRecord

                                                                     23
DF
          Setting the CLASSPATH




                  aP
 ●   For Unix base systems, suppose we have our classes


               vi
     in the directory /usr/local/myClasses, we write,
          ee
     export classpath=/usr/local/myClasses
   w   .n
ww




                                                          24
DF
           Setting the CLASSPATH




                   aP
 ●   Take note that you can set the classpath anywhere.


                vi
     You can also set more than one classpath, we just
     have to separate them by ;(for windows) and : (for Unix
           ee
     based systems). For example,
     set classpath=C:myClasses;D:;E:MyProgramsJava
       .n

 ●   and for Unix based systems,
   w


     export classpath=/usr/local/java:/usr/myClasses
ww




                                                               25
DF
         aP
        vi
       ee
       Java Threads
   .n
   w
ww




                      1
DF
                          Topics




                    aP
  ●   What is a thread?


                vi
  ●   Thread states
  ●   Thread priorities
            ee
  ●   Thread class
      Two ways of creating Java threads
      .n
  ●


      –   Extending Thread class
   w


      –   Implementing Runnable interface
      ThreadGroup
ww



  ●


  ●   Synchronization
  ●   Inter-thread communication
  ●   Scheduling a task via Timer and TimerTask
                                                  2
DF
        aP
        vi
       ee
   .n
   w


   What is a Thread?
ww




                       3
DF
                            Threads




                       aP
 ●   Why threads?


                   vi
     –   Need to handle concurrent processes
              ee
 ●   Definition
     –   Single sequential flow of control within a program
         .n
     –   For simplicity, think of threads as processes executed by
         a program
   w


     –   Example:
          ●   Operating System
ww



          ●   HotJava web browser




                                                                     4
ww
       w.n
           ee
                vi
                  aP
                        DF
                     Threads




5
DF
      Multi-threading in Java Platform




                  aP
  ●   Every application has at least one thread — or
      several, if you count "system" threads that do

               vi
      things like memory management and signal
          ee
      handling
  ●   But from the application programmer's point of
       .n
      view, you start with just one thread, called the main
      thread. This thread has the ability to create
   w


      additional threads
ww




                                                              6
DF
         aP
        vi
       ee
   .n
   w


       Thread States
ww




                       7
DF
                       Thread States




                      aP
 ●   A thread can in one of several possible states:
     1. Running


                  vi
         ●   Currently running
             In control of CPU
         ●
             ee
     2. Ready to run
         ●   Can run but not yet given the chance
      .n
     3. Resumed
         ●   Ready to run after being suspended or block
   w


     4. Suspended
ww



         ●   Voluntarily allowed other threads to run
     5. Blocked
         ●   Waiting for some resource or event to occur

                                                           8
DF
        aP
        vi
       ee
   .n
   w


   Thread Priorities
ww




                       9
DF
                      Thread Priorities




                        aP
 ●   Why priorities?


                    vi
     –   Determine which thread receives CPU control and gets
         to be executed first
              ee
 ●   Definition:
     –   Integer value ranging from 1 to 10
         .n

     –   Higher the thread priority → larger chance of being
         executed first
   w


     –   Example:
ww



          ●   Two threads are ready to run
          ●   First thread: priority of 5, already running
          ●   Second thread = priority of 10, comes in while first thread
              is running
                                                                            10
DF
                     Thread Priorities




                        aP
 ●   Context switch


                    vi
     –   Occurs when a thread snatches the control of CPU from
         another
              ee
     –   When does it occur?
          ●   Running thread voluntarily relinquishes CPU control
         .n
          ●   Running thread is preempted by a higher priority thread
     More than one highest priority thread that is ready
   w

 ●

     to run
ww



     –   Deciding which receives CPU control depends on the
         operating system
     –   Windows 95/98/NT: Uses time-sliced round-robin
     –   Solaris: Executing thread should voluntarily relinquish
         CPU control                                                    11
DF
        aP
        vi
       ee
   .n
   w


       Thread Class
ww




                      12
DF
      The Thread Class: Constructor




                  aP
 ●   Has eight constructors


               vi
          ee
   w   .n
ww




                                      13
DF
       The Thread Class: Constants




                   aP
 ●   Contains fields for priority values


                vi
           ee
   w   .n
ww




                                           14
DF
       The Thread Class: Methods




                aP
 ●   Some Thread methods


             vi
         ee
   w  .n
ww




                                   15
DF
        aP
        vi
       ee
   .n
   w


  Two Ways of Creating
ww




     Java Threads
                         16
DF
 Two Ways of Creating and Starting




                aP
            a Thread
 1.Extending the Thread class


            vi
 2.Implementing the Runnable interface
        ee
   w .n
ww




                                         17
DF
        aP
        vi
       ee
   .n
   w


   Extending Thread
ww




        Class
                      18
DF
            Extending Thread Class




                     aP
 ●   The subclass extends Thread class


                 vi
     –   The subclass overrides the run() method of Thread class
            ee
 ●   An object instance of the subclass can then be
     created
         .n
 ●   Calling the start() method of the object instance
     starts the execution of the thread
   w


     –   Java runtime starts the execution of the thread by
         calling run() method of object instance
ww




                                                                   19
DF
 Two Schemes of starting a thread




                     aP
        from a subclass
 1.The start() method is not in the constructor of the


                 vi
   subclassee
    –   The start() method needs to be explicitly invoked after
        object instance of the subclass is created in order to start
        the thread
        .n

 2.The start() method is in the constructor of the
   subclass
   w


    –   Creating an object instance of the subclass will start the
ww



        thread




                                                                       20
DF
 Scheme 1: start() method is Not in
    the constructor of subclass




                       aP
 1    class PrintNameThread extends Thread {
          PrintNameThread(String name) {



                   vi
 2

 3            super(name);
              ee
 4        }
 5        public void run() {
 6            String name = getName();
          .n

 7            for (int i = 0; i < 100; i++) {
                  System.out.print(name);
   w

 8

 9            }
ww



 10       }
 11   }
 12   //continued


                                                21
DF
 Scheme 1: start() method needs to
       be called explicitly




                      aP
 14   class ExtendThreadClassTest1 {
          public static void main(String args[]) {



                  vi
 15

 16           PrintNameThread pnt1 =
              ee
 17                          new PrintNameThread("A");
 18           pnt1.start(); // Start the first thread
 19           PrintNameThread pnt2 =
          .n

 20                          new PrintNameThread("B");
              pnt2.start(); // Start the second thread
   w

 21

 22
ww



 23       }
 24   }



                                                         22
DF
      Scheme 2: start() method is in a
        constructor of the subclass




                       aP
 1    class PrintNameThread extends Thread {
          PrintNameThread(String name) {



                   vi
 2

 3            super(name);
              ee
 4            start(); //runs the thread once instantiated
 5        }
 6        public void run() {
          .n

 7            String name = getName();
              for (int i = 0; i < 100; i++) {
   w

 8

 9                System.out.print(name);
ww



 10           }
 11       }
 12   }
 13   //continued
                                                             23
DF
          Scheme 2: Just creating an object
              instance starts a thread




                       aP
 14   class ExtendThreadClassTest2 {
           public static void main(String args[]) {



                   vi
 15

 16            PrintNameThread pnt1 =
               ee
 17                           new PrintNameThread("A");
 18            PrintNameThread pnt2 =
 19                           new PrintNameThread("B");
          .n

 20

           }
   w

 21

 22   }
ww




                                                          24
DF
 Scheme 2: Just creating an object




                    aP
     instance starts a thread
 ●   Can modify main method as follows:


                vi
     14   class ExtendThreadClassTest3 {
            ee
     15      public static void main(String args[]) {
     16         new PrintNameThread("A");
     17         new PrintNameThread("B");
          .n

     18      }
          }
   w

     19
ww




                                                        25
DF
        aP
        vi
       ee
   .n
   w


    Implementing
ww




  Runnable Interface
                       26
DF
                 Runnable Interface




                     aP
 ●   The Runnable interface should be implemented by


                 vi
     any class whose instances are intended to be
     executed as a thread
            ee
 ●   The class must define run() method of no
     arguments
         .n

     –   The run() method is like main() for the new thread
   w


 ●   Provides the means for a class to be active while
     not subclassing Thread
ww



     –   A class that implements Runnable can run without
         subclassing Thread by instantiating a Thread instance
         and passing itself in as the target

                                                                 27
DF
 Two Ways of Starting a Thread For




                     aP
 a class that implements Runnable
 1.Caller thread creates Thread object and starts it


                 vi
   explicitly after an object instance of the class that
   implements Runnable interface is created
           ee
    –   The start() method of the Thread object needs to be
        explicitly invoked after object instance is created
        .n

 2.The Thread object is created and started within the
   constructor method of the class that implements
   w


   Runnable interface
ww



    –   The caller thread just needs to create object instances of
        the Runnable class


                                                                     28
DF
      Scheme 1: Caller thread creates a
     Thread object and starts it explicitly




                    aP
 // PrintNameRunnable implements Runnable interface
 class PrintNameRunnable implements Runnable {




               vi
     String name;
          ee
     PrintNameRunnable(String name) {
         this.name = name;
     }
       .n

     // Implementation of the run() defined in the
   w

     // Runnable interface.
     public void run() {
         for (int i = 0; i < 10; i++) {
ww



             System.out.print(name);
         }
     }
 }

                                                      29
DF
         Scheme 1: Caller thread creates a
        Thread object and starts it explicitly




                    aP
public class RunnableThreadTest1 {

    public static void main(String args[]) {



                 vi
         PrintNameRunnable pnt1 = new PrintNameRunnable("A");
            ee
         Thread t1 = new Thread(pnt1);
         t1.start();
         .n
    }
}
   w
ww




                                                            30
DF
 Scheme 2: Thread object is created
  and started within a constructor




                aP
 // PrintNameRunnable implements Runnable interface
 class PrintNameRunnable implements Runnable {




            vi
     Thread thread;
        ee
     PrintNameRunnable(String name) {
         thread = new Thread(this, name);
         thread.start();
     }
     .n

     // Implementation of the run() defined in the
   w

     // Runnable interface.
     public void run() {
ww



         String name = thread.getName();
         for (int i = 0; i < 10; i++) {
             System.out.print(name);
         }
     }
 }
                                                      31
DF
    Scheme 2: Thread object is created
     and started within a constructor




                   aP
public class RunnableThreadTest2 {

    public static void main(String args[]) {



                vi
        // Since the constructor of the PrintNameRunnable
           ee
        // object creates a Thread object and starts it,
        // there is no need to do it here.
        new PrintNameRunnable("A");
        .n

        new PrintNameRunnable("B");
        new PrintNameRunnable("C");
   w


    }
}
ww




                                                            32
DF
        aP
        vi
       ee
   .n

   Extending Thread Class
   w
ww



      vs. Implementing
     Runnable Interface
                            33
DF
 Extending Thread vs. Implementing




                        aP
         Runnable Interface
 ●   Choosing between these two is a matter of taste


                    vi
 ●   Implementing the Runnable interface
              ee
     –   May take more work since we still
          ●   Declare a Thread object
         .n
          ●   Call the Thread methods on this object
     –   Your class can still extend other class
   w


 ●   Extending the Thread class
     –   Easier to implement
ww



     –   Your class can no longer extend any other class



                                                           34
DF
        aP
        vi
       ee
   .n
   w


       ThreadGroup
ww




                     35
DF
                ThreadGroup Class




                     aP
 ●   A thread group represents a set of threads


                 vi
 ●   In addition, a thread group can also include other
            ee
     thread groups
     –   The thread groups form a tree in which every thread
         group except the initial thread group has a parent
         .n

 ●   A thread is allowed to access information about its
   w


     own thread group, but not to access information
     about its thread group's parent thread group or any
ww



     other thread groups.



                                                               36
DF
       Example: ThreadGroup




              aP
 1     // Start three threads
 2      new SimpleThread("Jamaica").start();




            vi
 3      new SimpleThread("Fiji").start();
 4      new SimpleThread("Bora Bora").start();
       ee
 5

 6      ThreadGroup group
      .n
 7       = Thread.currentThread().getThreadGroup();
 8
   w

 9      Thread[] tarray = new Thread[10];
 10     int actualSize = group.enumerate(tarray);
ww



 11     for (int i=0; i<actualSize;i++){
 12         System.out.println("Thread " +
 13         tarray[i].getName() + " in thread group "
 14          + group.getName());
 15     }                                               37
DF
          aP
        vi
       ee
   .n
   w


       Synchronization
ww




                         38
DF
     Race condition & How to Solve it




                      aP
 ●   Race conditions occur when multiple,


                  vi
     asynchronously executing threads access the same
     object (called a shared resource) returning
            ee
     unexpected (wrong) results
 ●   Example:
         .n

     –   Threads often need to share a common resource ie a
         file, with one thread reading from the file while another
   w


         thread writes to the file
ww



 ●   They can be avoided by synchronizing the threads
     which access the shared resource


                                                                     39
DF
          An Unsynchronized Example




                       aP
 1    class TwoStrings {
 2        static void print(String str1, String str2) {




                   vi
 3            System.out.print(str1);
 4            try {
              ee
 5                Thread.sleep(500);
 6            } catch (InterruptedException ie) {
          .n
 7            }
 8            System.out.println(str2);
   w

 9        }
 10   }
ww



 11   //continued...




                                                          40
DF
          An Unsynchronized Example




                       aP
 12   class PrintStringsThread implements Runnable {
 13       Thread thread;




                  vi
 14       String str1, str2;
 15       PrintStringsThread(String str1, String str2) {
              ee
 16           this.str1 = str1;
 17           this.str2 = str2;
          .n
 18           thread = new Thread(this);
 19           thread.start();
   w

 20       }
 21       public void run() {
ww



 22           TwoStrings.print(str1, str2);
 23       }
 24   }
 25   //continued...
                                                           41
DF
          An Unsynchronized Example




                      aP
 26   class TestThread {
 27       public static void main(String args[]) {




                  vi
 28           new PrintStringsThread("Hello ", "there.");
 29           new PrintStringsThread("How are ", "you?");
              ee
 30           new PrintStringsThread("Thank you ",
 31                                       "very much!");
          .n
 32       }
 33   }
   w
ww




                                                            42
DF
       An Unsynchronized Example




                      aP
 ●   Sample output:
     Hello How are Thank you there.




                vi
     you?
     very much!
           ee
   w   .n
ww




                                      43
DF
                  Synchronization:




                      aP
                  Locking an Object
 ●   A thread is synchronized by becoming an owner of


                  vi
     the object's monitor
            ee
     –   Consider it as locking an object
 ●   A thread becomes the owner of the object's monitor
     in one of three ways
         .n

     –   Option 1: Use synchronized method
   w


     –   Option 2: Use synchronized statement on a common
         object
ww




                                                            44
DF
 Option 1: Use synchronized method




                       aP
 1    class TwoStrings {




                   vi
 2        synchronized static void print(String str1,
 3            ee                          String str2) {
 4            System.out.print(str1);
 5            try {
                  Thread.sleep(500);
          .n
 6

 7            } catch (InterruptedException ie) {
              }
   w

 8

 9            System.out.println(str2);
ww



 10       }
 11   }
 12   //continued...


                                                           45
DF
 Option 1: Use synchronized method




                       aP
 13   class PrintStringsThread implements Runnable {
 14       Thread thread;




                  vi
 15       String str1, str2;
 16       PrintStringsThread(String str1, String str2) {
              ee
 17           this.str1 = str1;
 18           this.str2 = str2;
          .n
 19           thread = new Thread(this);
 20           thread.start();
   w


 21       }
 22       public void run() {
ww



 23           TwoStrings.print(str1, str2);
 24       }
 25   }
 26   //continued...
                                                           46
DF
 Option 1: Use synchronized method




                      aP
 27   class TestThread {
 28       public static void main(String args[]) {



                  vi
 29           new PrintStringsThread("Hello ", "there.");
              new PrintStringsThread("How are ", "you?");
 30
              ee
 31           new PrintStringsThread("Thank you ",
 32                                        "very much!");
          .n
 33       }
 34   }
   w
ww




                                                            47
DF
 Option 1: Executing Synchronized
              Method




                      aP
 ●   Sample output:
     Hello there.



                vi
     How are you?
           ee
     Thank you very much!
   w   .n
ww




                                    48
DF
            Option 2: Use synchronized
          statement on a common object




                        aP
 1    class TwoStrings {
 2         static void print(String str1, String str2) {



                    vi
 3             System.out.print(str1);
               try {
 4
               ee
 5                 Thread.sleep(500);
 6             } catch (InterruptedException ie) {
          .n
 7             }
 8             System.out.println(str2);
   w


 9         }
ww



 10   }
 11   //continued...




                                                           49
DF
         Option 2: Use synchronized
       statement on a common object




                       aP
 12   class PrintStringsThread implements Runnable {
 13      Thread thread;



                 vi
 14      String str1, str2;
         TwoStrings ts;
 15
             ee
 16      PrintStringsThread(String str1, String str2,
 17                            TwoStrings ts) {
        .n
 18          this.str1 = str1;
 19          this.str2 = str2;
   w


 20          this.ts = ts;
             thread = new Thread(this);
ww



 21

 22          thread.start();
 23      }
 24   //continued...

                                                        50
DF
            Option 2: Use synchronized
          statement on a common object




                        aP
 25        public void run() {
 26            synchronized (ts) {




                    vi
 27                ts.print(str1, str2);
 28            }
               ee
 29        }
 30   }
           .n
 31   class TestThread {
 32        public static void main(String args[]) {
   w


 33            TwoStrings ts = new TwoStrings();
 34            new PrintStringsThread("Hello ", "there.", ts);
ww



 35            new PrintStringsThread("How are ", "you?", ts);
 36            new PrintStringsThread("Thank you ",
 37                                         "very much!", ts);
 38   }}
                                                                 51
DF
        aP
        vi
       ee
   .n
   w


     Inter-thread
ww




   Synchronization
                     52
DF
   Inter-thread Communication:




         aP
    Methods from Object Class


        vi
       ee
   .n
   w
ww




                                 53
DF
      wait() method of Object Class




                  aP
 ●   wait() method causes a thread to release the lock it


               vi
     is holding on an object; allowing another thread to
     run
          ee
 ●   wait() method is defined in the Object class
     wait() can only be invoked from within synchronized
       .n
 ●

     code
   w


 ●   it should always be wrapped in a try block as it
     throws IOExceptions
ww



 ●   wait() can only invoked by the thread that own's the
     lock on the object

                                                            54
DF
      wait() method of Object Class




                     aP
  ●   When wait() is called, the thread becomes disabled for
      scheduling and lies dormant until one of four things


                 vi
      occur:ee
      –   another thread invokes the notify() method for this object
          and the scheduler arbitrarily chooses to run the thread
      –   another thread invokes the notifyAll() method for this
       .n

          object
      –   another thread interrupts this thread
   w


      –   the specified wait() time elapses
ww



  ●   When one of the above occurs, the thread becomes re-
      available to the Thread scheduler and competes for a
      lock on the object
  ●   Once it regains the lock on the object, everything
      resumes as if no suspension had occurred             55
DF
                    notify() method




                     aP
 ●   Wakes up a single thread that is waiting on this
     object's monitor


                 vi
     –   If any threads are waiting on this object, one of them is
         chosen to be awakened
            ee
     –   The choice is arbitrary and occurs at the discretion of the
         implementation
      .n
 ●   Can only be used within synchronized code
 ●   The awakened thread will not be able to proceed
   w


     until the current thread relinquishes the lock on this
     object
ww




                                                                       56
DF
        aP
        vi
       ee
       Inter-thread
   .n
   w


     Communication:
ww



   Producer-Consumer
        Example
                       57
DF
   Inter-thread Communication




         aP
        vi
       ee
   .n
   w
ww




                                58
DF
               Producer-Consumer




                      aP
 ●   Imagine a scenario in which there exists two


                  vi
     distinct threads both operating on a single shared
     data area
            ee
 ●   One thread, the Producer inserts information into
     the data area whilst the other thread, the
         .n

     Consumer, removes information from that same
     area
   w


 ●   In order for the Producer to insert information into
ww



     the data area, there must be enough space
     –   The Producer's sole function is to insert data into the
         data-area, it is not allowed to remove any data from the
         area.
                                                                    59
DF
               Producer-Consumer




                     aP
 ●   For the Consumer to be able to remove information


                 vi
     from the data area, there must be information there
     in the first place
            ee
     –   The sole function of the Consumer is to remove data
         from the data area
         .n

 ●   The solution of the Producer-Consumer problem
     lies with devising a suitable communication protocol
   w


     through which the two processes may exchange
ww



     information.
 ●   The definition of such a protocol is the main factor
     that makes the Producer-Consumer problem
     interesting in terms of concurrent systems
                                                               60
DF
     Unsynchronized Producer-Consumer
         Example: CubbyHole.java




                    aP
 1    public class CubbyHole {
 2        private int contents;



                vi
 3

          public int get() {
 4
              ee
 5            return contents;
 6        }
          .n
 7

 8        public synchronized void put(int value) {
   w


 9            contents = value;
          }
ww



 10

 11   }




                                                      61
DF
    Unsynchronized Producer-
 Consumer Example: Producer.java




                    aP
 1    public class Producer extends Thread {
 2        private CubbyHole cubbyhole;




                vi
 3        private int number;
 4
          public Producer(CubbyHole c, int number) {
 5
            ee
 6            cubbyhole = c;
 7            this.number = number;
 8        }
          .n
 9
 10       public void run() {
   w

 11           for (int i = 0; i < 10; i++) {
 12               cubbyhole.put(i);
                  System.out.println("Producer #" + this.number
ww



 13
 14                                  + " put: " + i);
 15               try {
 16                   sleep((int)(Math.random() * 100));
 17               } catch (InterruptedException e) { }
 18           }
 19       }                                                 62
 20   }
DF
     Unsynchronized Producer-Consumer
          Example: Consumer.java




                    aP
 1    public class Consumer extends Thread {
 2        private CubbyHole cubbyhole;




                vi
 3        private int number;
 4
          public Consumer(CubbyHole c, int number) {
 5
            ee
 6            cubbyhole = c;
 7            this.number = number;
 8        }
          .n
 9
 10       public void run() {
   w

 11           int value = 0;
 12           for (int i = 0; i < 10; i++) {
                  value = cubbyhole.get();
ww



 13
 14               System.out.println("Consumer #" + this.number
 15                                  + " got: " + value);
 16           }
 17       }
 18   }
 19                                                         63
DF
    Unsynchronized Producer-
 Consumer Example: Main program




                    aP
 1    public class ProducerConsumerUnsynchronized {
 2




                vi
 3        public static void main(String[] args) {
 4
              ee
 5            CubbyHole c = new CubbyHole();
 6
          .n
 7            Producer p1 = new Producer(c, 1);
 8            Consumer c1 = new Consumer(c, 1);
   w


 9

              p1.start();
ww



 10

 11           c1.start();
 12       }
 13   }

                                                      64
DF
           Result of Unsynchronized




                     aP
             Producer-Consumer
 ●   Results are unpredictable


                 vi
     –   A number may be read before a number has been
         produced
            ee
     –   Multiple numbers may be produced with only one or two
         being read
   w     .n
ww




                                                                 65
DF
        Result of Unsynchronized




                       aP
          Producer-Consumer
  Consumer #1 got: 0




                vi
  Producer #1 put: 0
  Consumer #1 got: 0
  Consumer #1 got: 0
          ee
  Consumer #1 got: 0
  Consumer #1 got: 0
  Consumer #1 got: 0
  Consumer #1 got: 0
     .n
  Consumer #1 got: 0
  Consumer #1 got: 0
  Consumer #1 got: 0
   w


  Producer #1 put: 1
  Producer #1 put: 2
ww



  Producer #1 put: 3
  Producer #1 put: 4
  Producer #1 put: 5
  Producer #1 put: 6
  Producer #1 put: 7
  Producer #1 put: 8
  Producer #1 put: 9
                                   66
DF
      Synchronized Producer-Consumer
          Example: CubbyHole.java




                    aP
 1    public class CubbyHole {
 2       private int contents;



                 vi
 3       private boolean available = false;
 4
             ee
 5       public synchronized int get() {
 6           while (available == false) {
        .n
 7               try {
 8                   wait();
   w


 9               } catch (InterruptedException e) { }
             }
ww



 10

 11          available = false;
 12          notifyAll();
 13          return contents;
 14      }
                                                        67
 15      // continued
DF
      Synchronized Producer-Consumer
          Example: CubbyHole.java




                   aP
 1




                  vi
 2        public synchronized void put(int value) {
 3            while (available == true) {
              ee
 4                try {
 5                    wait();
          .n
 6                } catch (InterruptedException e) { }
 7            }
   w


 8            contents = value;
              available = true;
ww



 9

 10           notifyAll();
 11       }
 12   }

                                                         68
DF
 Result of Synchronized Producer-




                      aP
            Consumer
  Producer 1 put: 0




                vi
  Consumer 1 got: 0
  Producer 1 put: 1
  Consumer 1 got: 1
          ee
  Producer 1 put: 2
  Consumer 1 got: 2
  Producer 1 put: 3
  Consumer 1 got: 3
     .n
  Producer 1 put: 4
  Consumer 1 got: 4
  Producer 1 put: 5
   w


  Consumer 1 got: 5
  Producer 1 put: 6
ww



  Consumer 1 got: 6
  Producer 1 put: 7
  Consumer 1 got: 7
  Producer 1 put: 8
  Consumer 1 got: 8
  Producer 1 put: 9
  Consumer 1 got: 9
                                    69
DF
        aP
        vi
       ee
   .n

   Scheduling a task
   w


     via Timer &
ww




  TimerTask Classes
                       70
DF
                        Timer Class




                      aP
 ●   Provides a facility for threads to schedule tasks for
     future execution in a background thread

                  vi
     Tasks may be scheduled for one-time execution, or
 ●
            ee
     for repeated execution at regular intervals.
 ●   Corresponding to each Timer object is a single
         .n
     background thread that is used to execute all of the
     timer's tasks, sequentially
   w


 ●   Timer tasks should complete quickly
ww



     –   If a timer task takes excessive time to complete, it "hogs"
         the timer's task execution thread. This can, in turn, delay
         the execution of subsequent tasks, which may "bunch
         up" and execute in rapid succession when (and if) the
         offending task finally completes.
                                                                       71
DF
                TimerTask Class




                  aP
 ●   Abstract class with an abstract method called run()


               vi
 ●   Concrete class must implement the run() abstract
     method
          ee
   w   .n
ww




                                                           72
DF
               Example: Timer Class




                       aP
  public class TimerReminder {

      Timer timer;




                     vi
      public TimerReminder(int seconds) {
        timer = new Timer();
            ee
        timer.schedule(new RemindTask(), seconds*1000);
      }

      class RemindTask extends TimerTask {
       .n

        public void run() {
          System.out.format("Time's up!%n");
   w


          timer.cancel(); //Terminate the timer thread
        }
ww



      }

      public static void main(String args[]) {
        System.out.format("About to schedule task.%n");
        new TimerReminder(5);
        System.out.format("Task scheduled.%n");
      }                                                   73
  }
ww
        w.n
                   ee
                         vi
                           aP
                              DF
            Thank You!


74

More Related Content

PDF
AWTEventModel
DOCX
J query
PDF
this is ruby test
KEY
openFrameworks 007 - events
PDF
Building Scalable Web Apps
PDF
아이폰강의(3)
PDF
citigroup January 13, 2006 - Reformatted Quarterly Financial Data Supplement...
PDF
Writing Maintainable JavaScript
AWTEventModel
J query
this is ruby test
openFrameworks 007 - events
Building Scalable Web Apps
아이폰강의(3)
citigroup January 13, 2006 - Reformatted Quarterly Financial Data Supplement...
Writing Maintainable JavaScript

Viewers also liked (9)

PDF
javaiostream
PDF
06-Event-Handlingadvansed
PDF
slides6
PDF
Java-Events
PDF
hibernate
PDF
Sms several papers
PDF
javabeans
PDF
swingbasics
PDF
servlets
javaiostream
06-Event-Handlingadvansed
slides6
Java-Events
hibernate
Sms several papers
javabeans
swingbasics
servlets
Ad

Similar to Java_Comb (20)

PDF
Awt event
PPTX
Event handling
PPS
Java session11
PPTX
event-handling.pptx
PPT
JavaYDL16
PPTX
Advance Java Programming(CM5I) Event handling
PDF
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
PPT
Event handling62
PPS
Dacj 2-2 b
PPTX
Java awt (abstract window toolkit)
PPT
09events
PPTX
Java Abstract Window Toolkit (AWT) Presentation. 2024
PPTX
Java Abstract Window Toolkit (AWT) Presentation. 2024
PPTX
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
PPT
event_handling.ppt
DOCX
Lecture8 oopj
PPT
Unit 6 Java
PPT
unit-6.pptbjjdjdkd ndmdkjdjdjjdkfjjfjfjfj
PDF
Ajp notes-chapter-03
Awt event
Event handling
Java session11
event-handling.pptx
JavaYDL16
Advance Java Programming(CM5I) Event handling
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Event handling62
Dacj 2-2 b
Java awt (abstract window toolkit)
09events
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
event_handling.ppt
Lecture8 oopj
Unit 6 Java
unit-6.pptbjjdjdkd ndmdkjdjdjjdkfjjfjfjfj
Ajp notes-chapter-03
Ad

More from Arjun Shanka (16)

PDF
Asp.net w3schools
PDF
Php tutorial(w3schools)
PDF
Jun 2012(1)
PDF
System simulation 06_cs82
PDF
javaexceptions
PDF
javainheritance
PDF
javarmi
PDF
java-06inheritance
PDF
javapackage
PDF
javaarray
PDF
spring-tutorial
PDF
struts
PDF
javathreads
PPT
72185-26528-StrutsMVC
PDF
javanetworking
PDF
javainterface
Asp.net w3schools
Php tutorial(w3schools)
Jun 2012(1)
System simulation 06_cs82
javaexceptions
javainheritance
javarmi
java-06inheritance
javapackage
javaarray
spring-tutorial
struts
javathreads
72185-26528-StrutsMVC
javanetworking
javainterface

Recently uploaded (20)

PDF
Getting Started with Data Integration: FME Form 101
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
Tartificialntelligence_presentation.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
A Presentation on Touch Screen Technology
PDF
Hybrid model detection and classification of lung cancer
PDF
Encapsulation theory and applications.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Getting Started with Data Integration: FME Form 101
Assigned Numbers - 2025 - Bluetooth® Document
Heart disease approach using modified random forest and particle swarm optimi...
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Group 1 Presentation -Planning and Decision Making .pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
1. Introduction to Computer Programming.pptx
Hindi spoken digit analysis for native and non-native speakers
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A comparative study of natural language inference in Swahili using monolingua...
Tartificialntelligence_presentation.pptx
A comparative analysis of optical character recognition models for extracting...
Digital-Transformation-Roadmap-for-Companies.pptx
A Presentation on Touch Screen Technology
Hybrid model detection and classification of lung cancer
Encapsulation theory and applications.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...

Java_Comb

  • 1. om JDK 1.1 AWT Event Handling .c ===================== DF aP vi n ee w. ww Object Computing, Inc. 1 AWT Event Handling
  • 2. om AWT .c DF • Abstract Windowing Toolkit package – java.awt aP • Easier to learn than Motif/X and MFC • Not as easy as using graphical GUI vi builders – several companies are creating them for Java ee – will output Java code that uses the AWT package • AWT classes fall in four categories – components n – containers w. – layout managers – event handling ww Object Computing, Inc. 2 AWT Event Handling
  • 3. om Steps To Use AWT .c • Create a container – Frame, Dialog, Window, Panel, ScrollPane DF • Select a LayoutManager – Flow, Border, Grid, GridBag, Card, none (null) • Create components aP – Button, Checkbox, Choice, Label, List, TextArea, TextField, PopupMenu • Add components to container vi • Specify event handling (changed in 1.1) ee – listeners are objects interested in events – sources are objects that “fire” events – register listeners with sources n • component.add<EventType>Listener – EventTypes are ActionEvent, AdjustmentEvent, w. ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, WindowEvent – implement methods of listener interfaces in listener classes ww • an event object is passed to the methods • ActionListener, AdjustmentListener, ComponentListener, FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, TextListener, WindowListener Object Computing, Inc. 3 AWT Event Handling
  • 4. om Event Sources, .c Listeners, and Objects DF Event Object • describes an event • ex. ActionEvent holds state of Shift key tes crea aP Event Source vi • generates events • ex. Button pas ses to ee list ene rm eth od Event Listener • any object can implement these interfaces • ex. ActionListener has method actionPerformed() n w. ww Object Computing, Inc. 4 AWT Event Handling
  • 5. om Simple AWT Example .c DF import java.awt.*; import java.awt.event.*; private private aP public class SimpleAWT extends java.applet.Applet implements ActionListener, ItemListener { Button button = new Button("Push Me!"); Checkbox checkbox = new Checkbox("Check Me!"); private Choice choice = new Choice(); vi private Label label = new Label("Pick something!"); public void init() { button.addActionListener(this); ee checkbox.addItemListener(this); choice.addItemListener(this); // An Applet is a Container because it extends Panel. setLayout(new BorderLayout()); n choice.addItem("Red"); w. choice.addItem("Green"); choice.addItem("Blue"); Panel panel = new Panel(); panel.add(button); ww panel.add(checkbox); panel.add(choice); add(label, "Center"); add(panel, "South"); } Object Computing, Inc. 5 AWT Event Handling
  • 6. om Simple AWT Example .c (Cont’d) DF public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("The Button was pushed."); } } aP public void itemStateChanged(ItemEvent e) { if (e.getSource() == checkbox) { label.setText("The Checkbox is now " + vi checkbox.getState() + "."); } else if (e.getSource() == choice) { label.setText(choice.getSelectedItem() + “ was selected.”); } ee } } n w. ww Object Computing, Inc. 6 AWT Event Handling
  • 7. om Event Classes .c DF • Hierarchy java.util.EventObject – java.awt.AWTEvent aP • java.awt.event.ComponentEvent – java.awt.event.FocusEvent vi – java.awt.event.InputEvent • java.awt.event.KeyEvent • java.awt.event.MouseEvent ee • java.awt.event.ActionEvent • java.awt.event.AdjustmentEvent • java.awt.event.ItemEvent • java.awt.event.TextEvent n • Can create custom, non-AWT event w. classes – extend java.util.EventObject ww Object Computing, Inc. 7 AWT Event Handling
  • 8. om Event Object Contents .c DF • java.util.EventObject – source holds a reference to the object that fired the event – java.awt.AWTEvent • id indicates event type aP – set to a constant in specific event classes (listed on following pages) • java.awt.event.ActionEvent – modifiers indicates state of control, shift, and meta (alt) vi keys – actionCommand holds the action specific command string ee • usually the label of a Button or MenuItem • java.awt.event.AdjustmentEvent – for Scrollbars used for n – value holds value checkboxes and – adjustmentType is unit +/-, block +/-, track radio buttons w. • java.awt.event.ItemEvent – for Choice, List, Checkbox, and CheckboxMenuItem – stateChange indicates selected or deselected • java.awt.event.TextEvent ww – listeners are notified of every keystroke that changes the value – listeners are also notified when setText() is called • other subclasses are on the following pages Object Computing, Inc. 8 AWT Event Handling
  • 9. om Event Object Contents .c (Cont’ d) DF • java.awt.AWTEvent – java.awt.event.ComponentEvent aP • id indicates moved, resized, shown, or hidden • java.awt.event.ContainerEvent – id indicates added or removed – child holds a reference to the component added or vi removed • java.awt.event.FocusEvent – id indicates gained or lost ee – temporary indicates temporary or permanent (see documentation in source) • java.awt.event.WindowEvent n – id indicates opened, closing, closed, iconified, deiconified, activated, and deactivated w. brought to front ww Object Computing, Inc. 9 AWT Event Handling
  • 10. om Event Object Contents .c (Cont’ d) DF • java.awt.AWTEvent – java.awt.event.InputEvent aP • modifiers is a mask that holds – state of control, shift, and meta (alt) keys – state of mouse buttons 1, 2, & 3 • when holds time the event occurred vi – probably should have been put in java.util.EventObject! • java.awt.event.KeyEvent ee – id indicates typed, pressed, or released – keyChar holds the ascii code of the key pressed – keyCode holds a constant identifying the key pressed (needed for non-printable keys) n • java.awt.event.MouseEvent – id indicates clicked, pressed, released, moved, entered, w. exited, or dragged – clickCount holds # of times button was clicked – x,y hold location of mouse cursor ww Object Computing, Inc. 10 AWT Event Handling
  • 11. om Event Listener Interfaces .c • Class hierarchy and methods DF – java.util.EventListener • java.awt.event.ActionListener – actionPerformed • java.awt.event.AdjustmentListener aP – adjustmentValueChanged • java.awt.event.ComponentListener – componentHidden, componentMoved, componentResized, componentShown • java.awt.event.FocusListener vi – focusGained, focusLost • java.awt.event.ItemListener ee – itemStateChanged • java.awt.event.KeyListener – keyPressed, keyReleased, keyTyped • java.awt.event.MouseListener n – mouseEntered, mouseExited, mousePressed, mouseReleased, mouseClicked w. • java.awt.event.MouseMotionListener – mouseDragged, mouseMoved • java.awt.event.TextListener – textValueChanged ww • java.awt.event.WindowListener – windowOpened, windowClosing, windowClosed, windowActivated, windowDeactivated, windowIconified, windowDeiconified Object Computing, Inc. 11 AWT Event Handling
  • 12. om Event Sources and .c Their Listeners DF • Component (ALL components extend this) – ComponentListener, FocusListener, KeyListener, • Dialog - WindowListener aP MouseListener, MouseMotionListener • Frame - WindowListener vi • Button - ActionListener ee • Choice - ItemListener • Checkbox - ItemListener n • CheckboxMenuItem - ItemListener w. • List - ItemListener, ActionListener when an item is double-clicked • MenuItem - ActionListener ww • Scrollbar - AdjustmentListener • TextField - ActionListener, TextListener • TextArea - TextListener Object Computing, Inc. 12 AWT Event Handling
  • 13. om Listener Adapter Classes .c DF • Provide empty default implementations of methods in listener interfaces with more than one method • They include aP vi – java.awt.event.ComponentAdapter – java.awt.event.FocusAdapter ee – java.awt.event.KeyAdapter – java.awt.event.MouseAdapter – java.awt.event.MouseMotionAdapter n – java.awt.event.WindowAdapter • To use, extend from them w. – override methods of interest – usefulness is limited by single inheritance ww • can’ do if another class is already being extended t • implementation for methods that are not of interest could look like this public void windowIconified(WindowEvent e) {} Object Computing, Inc. 13 AWT Event Handling
  • 14. om Design For Flexibility .c and Maintainability DF invokes app. methods Event App Handlers • Can separate rs ne pa ates d nts liste cre sse GU co rs h re an – application code ss of iste App dlers t e as aP elf I mp an f., en rs n an on dle ve sse ha d – GUI code pa ates reg s cre GUI – event handling code • Steps to achieve this separation vi – create a single class whose constructor creates the entire GUI, possibly using other GUI-only classes ee – create the GUI by invoking this constructor from an application class – create classes whose only function is to be notified of n GUI events and invoke application methods • their constructors should accept references to application w. objects whose methods they will invoke – create event handling objects in a GUI class and register them with the components whose events they ww will handle Object Computing, Inc. 14 AWT Event Handling
  • 15. om AWT Example .c DF aP vi • FontTest allows specification of text to be displayed, font name, style, color and size ee • It illustrates • creation of GUI components n • use of the Canvas and PopupMenu w. • component layout using BorderLayout, FlowLayout, and GridLayout • event handling ww • Invoke with <APPLET CODE=FontTest.class WIDTH=580 HEIGHT=250> </APPLET> Object Computing, Inc. 15 AWT Event Handling
  • 16. om FontTest.java .c DF import java.awt.*; import java.awt.event.*; import java.util.Enumeration; import COM.ociweb.awt.ColorMap; aP public class FontTest extends java.applet.Applet implements ActionListener, AdjustmentListener, ItemListener, MouseListener { static final String DEFAULT_FONT = "Helvetica"; static final String DEFAULT_TEXT = "FontTest"; vi static final int DEFAULT_SIZE = 24; private static final int BOX_SIZE = 3; private static final int MIN_SIZE = 6; ee private static final int MAX_SIZE = 250; private CheckboxGroup styleGroup = new CheckboxGroup(); private Checkbox boldRadio = new Checkbox("Bold", false, styleGroup); private Checkbox bothRadio = new Checkbox("Both", false, styleGroup); n private Checkbox italicRadio = new Checkbox("Italic", false, styleGroup); w. private Checkbox plainRadio = new Checkbox("Plain", true, styleGroup); private Choice fontChoice = new Choice(); private List colorList = new List(4, false); private MyCanvas myCanvas = new MyCanvas(); private PopupMenu popup = new PopupMenu("Font"); ww private Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, DEFAULT_SIZE, BOX_SIZE, MIN_SIZE, MAX_SIZE + BOX_SIZE); private TextField sizeField = new TextField(String.valueOf(DEFAULT_SIZE), 3); private TextField textField = new TextField(DEFAULT_TEXT, 40); Object Computing, Inc. 16 AWT Event Handling
  • 17. om FontTest.java (Cont’d) .c DF public void init() { fontChoice.addItem("TimesRoman"); fontChoice.addItem("Helvetica"); fontChoice.addItem("Courier"); aP fontChoice.select(DEFAULT_FONT); Panel fontPanel = new Panel(); fontPanel.add(new Label("Font:")); fontPanel.add(fontChoice); vi Panel stylePanel = new Panel(); stylePanel.add(plainRadio); stylePanel.add(boldRadio); stylePanel.add(italicRadio); ee stylePanel.add(bothRadio); Enumeration e = ColorMap.getColorNames(); while (e.hasMoreElements()) { colorList.addItem((String) e.nextElement()); n } colorList.select(0); w. Panel sizePanel = new Panel(); sizePanel.add (new Label("Size (" + MIN_SIZE + "-" + MAX_SIZE + ")")); sizePanel.add(sizeField); ww Panel westPanel = new Panel(new GridLayout(0, 1)); westPanel.add(fontPanel); unknown # of rows, westPanel.add(stylePanel); one column westPanel.add(colorList); westPanel.add(sizePanel); Object Computing, Inc. 17 AWT Event Handling
  • 18. om FontTest.java (Cont’d) .c DF setLayout(new BorderLayout()); add(myCanvas, "Center"); add(westPanel, "West"); aP add(textField, "North"); add(scrollbar, "South"); fontChoice.addItemListener(this); plainRadio.addItemListener(this); boldRadio.addItemListener(this); vi italicRadio.addItemListener(this); bothRadio.addItemListener(this); colorList.addItemListener(this); sizeField.addActionListener(this); ee textField.addActionListener(this); scrollbar.addAdjustmentListener(this); fontPanel.addMouseListener(this); stylePanel.addMouseListener(this); sizePanel.addMouseListener(this); n myCanvas.addMouseListener(this); MenuItem timesRomanItem = new MenuItem("TimesRoman"); w. MenuItem helveticaItem = new MenuItem("Helvetica"); MenuItem courierItem = new MenuItem("Courier"); timesRomanItem.addActionListener(this); helveticaItem.addActionListener(this); ww courierItem.addActionListener(this); popup.add(timesRomanItem); popup.add(helveticaItem); popup.add(courierItem); add(popup); } Object Computing, Inc. 18 AWT Event Handling
  • 19. om FontTest.java (Cont’d) .c public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == textField) { myCanvas.setText(textField.getText()); DF } else if (source == sizeField) { int size = Integer.parseInt(sizeField.getText()); scrollbar.setValue(size); setFont(); } else if (source instanceof MenuItem) { MenuItem menuItem = (MenuItem) source; } } setFont(); aP if (menuItem.getParent() == popup) { fontChoice.select(e.getActionCommand()); } vi public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == scrollbar) { ee sizeField.setText(String.valueOf(scrollbar.getValue())); setFont(); } } public void itemStateChanged(ItemEvent e) { n Object source = e.getSource(); if (source == fontChoice) { w. setFont(); } else if (source instanceof Checkbox) { Checkbox checkbox = (Checkbox) source; if (checkbox.getCheckboxGroup() == styleGroup) { setFont(); ww } } else if (source == colorList) { Color color = ColorMap.getColor(colorList.getSelectedItem()); myCanvas.setColor(color); } } Object Computing, Inc. 19 AWT Event Handling
  • 20. om FontTest.java (Cont’d) .c DF // MouseListener methods that need no action. public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} aP public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) { } popup.show((Component) e.getSource(), e.getX(), e.getY()); vi private void setFont() { int style = Font.PLAIN; Checkbox styleRadio = styleGroup.getSelectedCheckbox(); ee if (styleRadio == plainRadio) { style = Font.PLAIN; } else if (styleRadio == boldRadio) { style = Font.BOLD; } else if (styleRadio == italicRadio) { n style = Font.ITALIC; } else if (styleRadio == bothRadio) { w. style = Font.BOLD + Font.ITALIC; } Font font = new Font(fontChoice.getSelectedItem(), ww style, Integer.parseInt(sizeField.getText())); myCanvas.setFont(font); } } Object Computing, Inc. 20 AWT Event Handling
  • 21. om FontTest.java (Cont’d) .c DF class MyCanvas extends Canvas { private Color color = Color.black; private Font font = new Font(FontTest.DEFAULT_FONT, Font.PLAIN, aP FontTest.DEFAULT_SIZE); private String text = FontTest.DEFAULT_TEXT; public void setColor(Color color) { vi this.color = color; repaint(); } ee public void setFont(Font font) { this.font = font; repaint(); } n public void setText(String text) { this.text = text; repaint(); w. } public void paint(Graphics g) { g.setColor(color); g.setFont(font); ww g.drawString(text, 10, 200); } } Object Computing, Inc. 21 AWT Event Handling
  • 22. om ColorMap.java .c DF package COM.ociweb.awt; import java.awt.Color; import java.util.Enumeration; import java.util.Hashtable; public class ColorMap { aP private static Hashtable hashtable = new Hashtable(); static { vi hashtable.put("White", Color.white); hashtable.put("Gray", Color.gray); hashtable.put("DarkGray", Color.darkGray); hashtable.put("Black", Color.black); ee hashtable.put("Red", Color.red); hashtable.put("Pink", Color.pink); hashtable.put("Orange", Color.orange); hashtable.put("Yellow", Color.yellow); hashtable.put("Green", Color.green); n hashtable.put("Magenta", Color.magenta); hashtable.put("Cyan", Color.cyan); hashtable.put("Blue", Color.blue); w. } public static Color getColor(String name) { return (Color) hashtable.get(name); ww } public static Enumeration getColorNames() { return hashtable.keys(); } } Object Computing, Inc. 22 AWT Event Handling
  • 23. om Appendix A .c DF JDK 1.0 AWT aP Event Handling vi n ee w. ww Object Computing, Inc. 23 AWT Event Handling
  • 24. om 1.0 Default Event Handling .c (delegation-based event handling was added in Java 1.1) DF • Provided by Component class • handleEvent(Event evt) aP – first method invoked when an event occurs – default implementation tests for specific types of events and invokes the methods below vi • Methods to handle specific types of events – default implementations do nothing ee – they are • mouseDown and mouseUp • mouseDrag and mouseMove • mouseEnter and mouseExit n • keyDown and keyUp • gotFocus and lostFocus w. – from mouse click, tab key, or requestFocus method • action (discussed two slides ahead) • All event handling methods return boolean ww – indicates whether they handled the event – if false, the event is handled recursively by containers Object Computing, Inc. 24 AWT Event Handling
  • 25. om Overriding 1.0 Default Event Handling .c • Custom event handling methods other than DF handleEvent – created by overriding implementations in Component which do nothing aP – invoked by the default handleEvent implementation • Custom handleEvent method vi – created by overriding implementation in Component – can handle all events by comparing id field to constants in Event class to see what kind of event ee occurred – if overridden, other event handling methods will not be invoked unless n • they are invoked directly from this method – not recommended approach w. • this method invokes the handleEvent method of a superclass – recommended approach – do this if the event is not one you wish to handle in your ww handleEvent method – invoke with “return super.handleEvent(e); ” – first superclass to implement handleEvent is typically Component which disperses the event to methods which handle specific types of events Object Computing, Inc. 25 AWT Event Handling
  • 26. om 1.0 Action Events .c • Most user interface components generate “action” events DF – Label and TextArea don’ generate any events t – List and Scrollbar generate events that are not “action” events • must be handled in a handleEvent method, aP not an action method • Default handleEvent invokes public boolean action(Event evt, Object what) vi • Second argument varies based on the component ee – Button • String representing button label – Checkbox (and radiobutton) n • Boolean state (true for on, false for off) • generated when picked w. – Choice (option menu) • String representing selected item – TextField ww • null • generated when user presses return key • not when field is exited with mouse or tab key – use lostFocus method to catch that Object Computing, Inc. 26 AWT Event Handling
  • 27. ww Java Tutorial Extending Classes and Interfaces Inheritance in Java java-06.fm w. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). In Java, ne inheritance is used for two purposes: 1. class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the inheritance. ev base class. Java only allows a class to have one immediate base class, i.e., single class 2. interface inheritance - create a new class to implement the methods defined as part of an ia interface for the purpose of subtyping. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance. PD In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements. public class derived-class-name extends base-class-name { // derived class methods extend and possibly override F. co // those of the base class } public class class-name implements interface-name { } // class provides an implementation for the methods // as specified by the interface m Greg Lavender Slide 1 of 12 6/15/99
  • 28. ww Java Tutorial Extending Classes and Interfaces Example of class inhertiance java-06.fm w. package MyPackage; ne class Base { private int x; public int f() { ... } ev protected int g() { ... } } class Derived extends Base { private int y; ia public int f() { /* new implementation for Base.f() */ } PD public void h() { y = g(); ... } } In Java, the protected access qualifier means that the protected item (field or method) is visible to a F. any derived class of the base class containing the protected item. It also means that the protected item is visible to methods of other classes in the same package. This is different from C++. co Q: What is the base class of class Object? I.e., what would you expect to get if you executed the following code? Object x = new Object(); System.out.println(x.getClass().getSuperclass()); m Greg Lavender Slide 2 of 12 6/15/99
  • 29. ww Java Tutorial Extending Classes and Interfaces Order of Construction under Inheritance java-06.fm w. Note that when you construct an object, the default base class constructor is called implicitly, before the body of the derived class constructor is executed. So, objects are constructed top-down under ne inheritance. Since every object inherits from the Object class, the Object() constructor is always called implicitly. However, you can call a superclass constructor explicitly using the builtin super keyword, as long as it is the first statement in a constructor. ev For example, most Java exception objects inherit from the java.lang.Exception class. If you wrote your own exception class, say SomeException, you might write it as follows: ia public class SomeException extends Exception { public SomeException() { } public SomeException(String s) { PD super(); // calls Exception(), which ultimately calls Object() } F. super(s); // calls Exception(String), to pass argument to base class public SomeException (int error_code) { this("error”); // class constructor above, which calls super(s) System.err.println(error_code); co } } m Greg Lavender Slide 3 of 12 6/15/99
  • 30. ww Java Tutorial Extending Classes and Interfaces Abstract Base Classes java-06.fm w. An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A ne subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { ev // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ia ... // other abstract methods, object methods, class methods PD } public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations F. co } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); That is, operator new is invalid when applied to an abstract class. // ERROR! m Greg Lavender Slide 4 of 12 6/15/99
  • 31. ww Java Tutorial Extending Classes and Interfaces Example abstract class usage java-06.fm w. abstract class Point { private int x, y; ne public Point(int x, int y) { this.x = x; this.y = y; } public void move(int dx, int dy) { x += dx; y += dy; plot(); } ev public abstract void plot(); // has no implementation } abstract class ColoredPoint extends Point { private int color; ia protected public ColoredPoint(int x, int y, int color) PD { super(x, y); this.color = color; } } class SimpleColoredPoint extends ColoredPoint { F. public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); } public void plot() { ... } // code to plot a SimpleColoredPoint } co Since ColoredPoint does not provide an implementation of the plot method, it must be declared abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point m reference and initialize it with an instance of a subclass object that implements the plot method: Point p = new SimpleColoredPoint(a, b, red); p.plot(); Greg Lavender Slide 5 of 12 6/15/99
  • 32. ww Java Tutorial Extending Classes and Interfaces Interfaces java-06.fm w. An abstract class mixes the idea of mutable data in the form of instance variables, non-abstract methods, and abstract methods. An abstract class with only static final instance variables and all ne abstract methods is called an interface. An interface is a specification, or contract, for a set of methods that a class that implements the interface must conform to in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method, just as with an abstract method in an abstract class. ev So, you can think of an interface as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access defined. All methods declared in an ia interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. an interface, then they are implicitly defined to be: • public. PD You can define data in an interface, but it is less common to do so. If there are data fields defined in • static, and • final F. In other words, any data defined in an interface are treated as public constants. co m Note that a class and an interface in the same package cannot share the same name. Methods declared in an interace cannot be declared final. Why? Greg Lavender Slide 6 of 12 6/15/99
  • 33. ww Java Tutorial Extending Classes and Interfaces Interface declaration java-06.fm w. Interface names and class names in the same package must be distinct. ne public interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constant-expr; ev // one or more implicitly abstract and public methods return-type method-name ( formal-params ); ia } An interface declaraion is nothing more than a specification to which some class that purports to PD implement the interface must conform to in its implementation. That is, a class the implements the interface must have defined implementations for each of the interface methods. The major reason for interfaces being distinct elements in Java is that you often want to define some F. operation to operate on objects that all conform to the same interface. So, you can define some code in a very general way, with a guarantee that by only using the methods defined in the interface, that all co objects that implement the interface will have defined implementations for all the methods. For example, you might define a Shape interface that defines an area() method, and so you would expect that any class that implements the Shape interface, would define an area method. So, if I m have a list of references to objects that implement the Shape interface, I can legitimately invoke the area method, abstractly, on each of these objects and expect to obtain as a result a value that represents the area of some shape. Greg Lavender Slide 7 of 12 6/15/99
  • 34. ww Java Tutorial Extending Classes and Interfaces Separation of Interface from Implementations java-06.fm w. Interfaces are specifications for many possible implementations. Interfaces are used to define a contract for how you interact with an object, independent of the underlying implementation. The ne objective of an object-oriented programmer is to separate the specification of the interface from the hidden details of the implementation. Consider the specification of a common LIFO stack. public interface StackInterface { boolean empty(); ev ia void push(Object x); Object pop() throws EmptyStackException; Object peek() throws EmptyStackException; } PD Note that the methods in this interface are defined to operate on objects of type Object. Since a stack is a “container type”, it is very common to use the base class for all objects, namely Object, as the F. type of the arguments and results to a container type. Since all objects ultimately inherit from class Object, we can always generically refer to any object in the system using an Object reference. co However, when we pop from a stack, we have to explicitly type case from the very general type Object to a concrete type, so that we can manipulate the object concretely. Q: How many different ways are there to implement a stack? If we are using just using a Stack object m (as opposed to implementing it ourselves) should we care? Greg Lavender Slide 8 of 12 6/15/99
  • 35. ww Java Tutorial Extending Classes and Interfaces Stack implementation of the StackInterface java-06.fm w. public class Stack implements StackInterface { ne private Vector v = new Vector(); // use java.util.Vector class ev public boolean empty() { return v.size() == 0; } public void push(Object item) { v.addElement(item); } public Object pop() { Object obj = peek(); ia PD v.removeElementAt(v.size() - 1); return obj; } F. public Object peek() throws EmptyStackException { if (v.size() == 0) throw new EmptyStackException(); co return v.elementAt(v.size() - 1); } } m Greg Lavender Slide 9 of 12 6/15/99
  • 36. ww Java Tutorial Extending Classes and Interfaces Should a stack use or inherit from a vector? java-06.fm w. The java.util.Stack class is defined as a subclass of the java.util.Vector class, rather than using a Vector object as in the previous example. This sort of inheritance is not subtype inheritance, because ne the interface of a Stack object can be violated because a Vector has a “wider” interface than a Stack, i.e., a vector allows insertion into the front and the rear, so it is possible to violate the stack contract by treating a stack object as a vector, and violating the LIFO specification of a stack. public class Stack extends Vector { ev public Object push(Object item) {addElement(item); return item;} public Object pop() { ia Object obj; int len = size(); PD obj = peek(); removeElementAt(len - 1); return obj; } public Object peek() { int len = size(); if (len == 0) throw new EmptyStackException(); F. co return elementAt(len - 1); } public boolean empty() { return size() == 0;} } Vector v = new Stack(); // legal - base class reference to subclass object v.insertElementAt(x, 2); // insert object x into Vector slot 2!! m Greg Lavender Slide 10 of 12 6/15/99
  • 37. ww Java Tutorial Extending Classes and Interfaces When to use an Interface vs when to use an abstract class java-06.fm w. Having reviewed their basic properties, there are two primary differences between interfaces and abstract classes: ne • an abstract class can have a mix of abstract and non-abstract methods, so some default implementations can be defined in the abstract base class. An abstract class can also have static methods, static data, private and protected methods, etc. In other words, a class is a class, so it ev can contain features inherent to a class. The downside to an abstract base class, is that since their is only single inheritance in Java, you can only inherit from one class. • an interface has a very restricted use, namely, to declare a set of public abstract method ia singatures that a subclass is required to implement. An interfaces defines a set of type constraints, in the form of type signatures, that impose a requirement on a subclass to implement the methods of the interface. Since you can inherit multiple interfaces, they are often a very PD useful mechanism to allow a class to have different behaviors in different situations of usage by implementing multiple interfaces. F. It is usually a good idea to implement an interface when you need to define methods that are to be explicitly overridden by some subclass. If you then want some of the methods implemented with co default implementations that will be inherited by a subclass, then create an implementation class for the interface, and have other class inherit (extend) that class, or just use an abstract base class instead of an interface. m Greg Lavender Slide 11 of 12 6/15/99
  • 38. ww Java Tutorial Extending Classes and Interfaces Example of default interface implementations java-06.fm interface X { void f(); w. ne int g(); } ev class XImpl implements X { void g() { return -1; } // default implementation for g() } class Y extends XImpl implements X { void f() { ... } // provide implementation for f() ia PD } Note that when you invoke an abtract method using a reference of the type of an abstract class or an interface, the method call is dynamically dispatched. X x = new Y(); x.f(); F. co The call x.f() causes a run-time determination of the actual type of object that ‘x’ refers to, then a method lookup to determine which implementation of f() to invoke. In this case, Y.f(x) is called, but the type of x is first converted to Y so that the ‘this’ reference is initialized to a reference of type Y inside of f(), since the implicit type signature of Y.f() is really Y.f(final Y this); m Greg Lavender Slide 12 of 12 6/15/99
  • 39. ww w.n ee vi aP DF Java Array 1
  • 40. DF Agenda aP ● What is an array vi ● Declaration of an array ee ● Instantiation of an array ● Accessing array element .n ● Array length ● Multi-dimensional array w ww 2
  • 41. DF aP vi ee .n w What is an Array? ww 3
  • 42. DF Introduction to Arrays aP ● Suppose we have here three variables of type int with vi different identifiers for each variable. ee int number1; int number2; int number3; .n number1 = 1; number2 = 2; w number3 = 3; ww As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. 4
  • 43. DF Introduction to Arrays aP ● In Java and other programming languages, there is one vi capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of ee variable is called an array. .n ● An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots. w ww 5
  • 44. DF aP vi ee .n Declaration of w ww an Array 6
  • 45. DF Declaring Arrays aP ● To declare an array, write the data type, followed by a set of vi square brackets[], followed by the identifier name. ee ● For example, int []ages; .n or int ages[]; w ww 7
  • 46. DF aP vi ee .n Instantiation of w ww an Array 8
  • 47. DF Array Instantiation aP ● After declaring, we must create the array and specify its vi length with a constructor statement. ee ● Definitions: – Instantiation .n ● In Java, this means creation w – Constructor ● In order to instantiate an object, we need to use a constructor for this. A ww constructor is a method that is called to create a certain object. ● We will cover more about instantiating objects and constructors later. 9
  • 48. DF Array Instantiation aP ● To instantiate (or create) an array, write the new keyword, vi followed by the square brackets containing the number of elements you want the array to have. ee ● For example, //declaration .n int ages[]; //instantiate object w ages = new int[100]; or, can also be written as, ww //declare and instantiate object int ages[] = new int[100]; 10
  • 49. DF Array Instantiation aP vi ee .n w ww 11
  • 50. DF Array Instantiation aP ● You can also instantiate an array by directly initializing it with vi data. ee ● For example, int arr[] = {1, 2, 3, 4, 5}; .n This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5). w ww 12
  • 51. DF Sample Program aP 1 //creates an array of boolean variables with identifier 2 //results. This array contains 4 elements that are vi 3 //initialized to values {true, false, true, false} 4 5 boolean results[] = { true, false, true, false }; ee 6 7 //creates an array of 4 double variables initialized 8 //to the values {100, 90, 80, 75}; 9 .n 10 double []grades = {100, 90, 80, 75}; 11 12 //creates an array of Strings with identifier days and w 13 //initialized. This array contains 7 elements 14 15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, ww “Sun”}; 13
  • 52. DF aP vi ee .n w Accessing Array ww Element 14
  • 53. DF Accessing an Array Element aP ● To access an array element, or a part of the array, you use vi a number called an index or a subscript. ee ● index number or subscript – assigned to each member of the array, to allow the program to .n access an individual member of the array. – begins with zero and progress sequentially by whole numbers to the w end of the array. – NOTE: Elements inside your array are from 0 to (sizeOfArray-1). ww 15
  • 54. DF Accessing an Array Element aP ● For example, given the array we declared a while ago, we vi have //assigns 10 to the first element in the array ee ages[0] = 10; //prints the last element in the array .n System.out.print(ages[99]); w ww 16
  • 55. DF Accessing an Array Element aP ● NOTE: vi – once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data. ee – for reference data types such as Strings, they are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly. w .n ww 17
  • 56. DF Accessing an Array Element aP ● The following is a sample code on how to print all the vi elements in the array. This uses a for loop, so our code is shorter. ee 1 public class ArraySample{ 2 public static void main( String[] args ){ .n 3 int[] ages = new int[100]; 4 for( int i=0; i<100; i++ ){ 5 System.out.print( ages[i] ); w 6 } 7 } 8 } ww 18
  • 57. DF Coding Guidelines aP 1. It is usually better to initialize or instantiate the vi array right away after you declare it. For example, the declaration, ee int []arr = new int[100]; .n is preferred over, w int []arr; ww arr = new int[100]; 19
  • 58. DF Coding Guidelines aP 2. The elements of an n-element array have indexes vi from 0 to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of- ee bounds exception. .n 3. Remember: You cannot resize an array. w ww 20
  • 59. DF aP vi ee .n w Array Length ww 21
  • 60. DF Array Length aP ● In order to get the number of elements in an array, you can vi use the length field of an array. ee ● The length field of an array returns the size of the array. It can be used by writing, .n arrayName.length w ww 22
  • 61. DF Array Length aP 1 public class ArraySample { 2 public static void main( String[] args ){ vi 3 int[] ages = new int[100]; 4 ee 5 for( int i=0; i<ages.length; i++ ){ 6 System.out.print( ages[i] ); 7 } 8 } .n 9 } w ww 23
  • 62. DF Coding Guidelines aP 1. When creating for loops to process the elements of an vi array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust ee automatically for different-sized arrays. .n 2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, w final int ARRAY_SIZE = 1000; //declare a constant ww . . . int[] ages = new int[ARRAY_SIZE]; 24
  • 63. DF aP vi ee .n Multi-Dimensional w ww Array 25
  • 64. DF Multidimensional Arrays aP ● Multidimensional arrays are implemented as arrays of vi arrays. ee ● Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. w .n ww 26
  • 65. DF Multidimensional Arrays aP ● For example, vi // integer array 512 x 128 elements ee int[][] twoD = new int[512][128]; // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24]; .n // String array 4 rows x 2 columns w String[][] dogs = {{ "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"}, ww { "fido", "black"} }; 27
  • 66. DF Multidimensional Arrays aP ● To access an element in a multidimensional array is just the vi same as accessing the elements in a one dimensional array. ee ● For example, to access the first element in the first row of the array dogs, we write, .n System.out.print( dogs[0][0] ); w This will print the String "terry" on the screen. ww 28
  • 67. DF Summary aP ● Arrays vi – Definition ee – Declaration – Instantiation and constructors (brief overview – to be discussed more later) .n – Accessing an element – The length field w – Multidimensional Arrays ww 29
  • 68. ww core w. ne evprogramming Handling iMouse and aP DF Keyboard Events .c om 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
  • 69. ww Agenda w. • • ne General event-handling strategy Handling events with separate listeners • ev Handling events by implementing interfaces • Handling events with named inner classes ia • Handling events with anonymous inner classes PD • The standard AWT listener types • Subtleties with mouse events F. • Examples co m 2 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 70. ww General Strategy w. ne • Determine what type of listener is of interest – 11 standard AWT listener types, described on later slide. ev • ActionListener, AdjustmentListener, ComponentListener, ContainerListener, ia FocusListener, ItemListener, KeyListener, WindowListener • Define a class of that type PD MouseListener, MouseMotionListener, TextListener, F. – Implement interface (KeyListener, MouseListener, etc.) – Extend class (KeyAdapter, MouseAdapter, etc.) • Register an object of your listener class co with the window – w.addXxxListener(new MyListenerClass()); • E.g., addKeyListener, addMouseListener m 3 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 71. ww Events with a Handling w. Separate Listener: Simple Case ne • Listener does not need to call any methods of the window to which it is attached ev import java.applet.Applet; ia import java.awt.*; PD public class ClickReporter extends Applet { public void init() { F. setBackground(Color.yellow); addMouseListener(new ClickListener()); } } co m 4 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 72. ww Listener: Simple Case Separate w. (Continued) ne import java.awt.event.*; ev public class ClickListener extends MouseAdapter { public void mousePressed(MouseEvent event) { ia System.out.println("Mouse pressed at (" + event.getX() + "," + } PD event.getY() + ")."); } F. co m 5 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 73. ww Generalizing Simple Case w. ne • What if ClickListener wants to draw a circle wherever mouse is clicked? ev • Why can’t it just call getGraphics to get a Graphics object with which to draw? ia • General solution: PD – Call event.getSource to obtain a reference to window or GUI component from which event originated – Cast result to type of interest F. – Call methods on that reference co m 6 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 74. ww Events with Separate Handling w. Listener: General Case ne import java.applet.Applet; ev import java.awt.*; ia public class CircleDrawer1 extends Applet { public void init() { PD setForeground(Color.blue); addMouseListener(new CircleListener()); } } F. co m 7 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 75. ww Listener: General Separate w. Case (Continued) ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; ia public class CircleListener extends MouseAdapter { private int radius = 25; PD public void mousePressed(MouseEvent event) { Applet app = (Applet)event.getSource(); F. Graphics g = app.getGraphics(); g.fillOval(event.getX()-radius, co event.getY()-radius, 2*radius, } } 2*radius); m 8 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 76. ww Listener: General Separate w. Case (Results) ne ev ia PD F. co m 9 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 77. ww 2: Implementing a Case w. Listener Interface ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; ia public class CircleDrawer2 extends Applet implements MouseListener { PD private int radius = 25; public void init() { F setForeground(Color.blue); addMouseListener(this); .c } om 10 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 78. ww Implementing a Listener w. Interface (Continued) ne public public void void mouseEntered(MouseEvent event) {} mouseExited(MouseEvent event) {} public public ev void void mouseReleased(MouseEvent event) {} mouseClicked(MouseEvent event) {} ia PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); g.fillOval(event.getX()-radius, F event.getY()-radius, 2*radius, 2*radius); .c } } om 11 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 79. ww Case 3: Named Inner Classes w. import java.applet.Applet; import java.awt.*; ne import java.awt.event.*; ev ia public class CircleDrawer3 extends Applet { public void init() { setForeground(Color.blue); addMouseListener(new CircleListener());PD } F. co m 12 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 80. ww Inner Classes Named w. (Continued) ne • Note: still part of class from previous slide ev private class CircleListener extends MouseAdapter { ia private int radius = 25; PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); F g.fillOval(event.getX()-radius, event.getY()-radius, 2*radius, .c } } 2*radius); om } 13 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 81. ww 4: Anonymous Inner Case w. Classes ne public class CircleDrawer4 extends Applet { public void init() { ev setForeground(Color.blue); addMouseListener (new MouseAdapter() { ia private int radius = 25; PD public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); F. g.fillOval(event.getX()-radius, event.getY()-radius, } co 2*radius, 2*radius); } } }); m 14 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 82. ww Handling Strategies: Event w. Pros and Cons ne • Separate Listener – Advantages ev • Can extend adapter and thus ignore unused methods • Separate class easier to manage ia – Disadvantage PD • Need extra step to call methods in main window • Main window that implements interface – Advantage F. • No extra steps needed to call methods in main window – Disadvantage co • Must implement methods you might not care about m 15 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 83. ww Handling Strategies: Event w. Pros and Cons (Continued) ne • Named inner class – Advantages ev • Can extend adapter and thus ignore unused methods • No extra steps needed to call methods in main ia window – Disadvantage PD • A bit harder to understand • Anonymous inner class – Advantages F. co • Same as named inner classes • Even shorter – Disadvantage m • Much harder to understand 16 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 84. ww AWT Event Listeners Standard w. (Summary) ne Adapter Class ev Listener ActionListener (If Any) Registration Method addActionListener ia AdjustmentListener ComponentListener ComponentAdapter addAdjustmentListener addComponentListener FocusListener ItemListener PD ContainerListener ContainerAdapter FocusAdapter addContainerListener addFocusListener addItemListener KeyListener MouseListener F. KeyAdapter MouseAdapter addKeyListener addM ouseListener MouseMotionListener TextListener WindowListener co MouseMotionAdapter WindowAdapter addM ouseMotionListener addTextListener addWindowListener m 17 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 85. ww AWT Event Listeners Standard w. (Details) ne • ActionListener – Handles buttons and a few other actions ev • actionPerformed(ActionEvent event) • AdjustmentListener ia – Applies to scrolling PD • adjustmentValueChanged(AdjustmentEvent event) • ComponentListener • F. – Handles moving/resizing/hiding GUI objects componentResized(ComponentEvent event) • • co componentMoved (ComponentEvent event) componentShown(ComponentEvent event) • m componentHidden(ComponentEvent event) 18 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 86. ww AWT Event Listeners Standard w. (Details Continued) ne • ContainerListener – Triggered when window adds/removes GUI controls ev • componentAdded(ContainerEvent event) • componentRemoved(ContainerEvent event) • FocusListeneria PD – Detects when controls get/lose keyboard focus • focusGained(FocusEvent event) F. • focusLost(FocusEvent event) co m 19 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 87. ww AWT Event Listeners Standard w. (Details Continued) ne • ItemListener – Handles selections in lists, checkboxes, etc. ev • itemStateChanged(ItemEvent event) • KeyListener ia – Detects keyboard events PD • keyPressed(KeyEvent event) -- any key pressed down F. • keyReleased(KeyEvent event) -- any key released • keyTyped(KeyEvent event) -- key for printable char released co m 20 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 88. ww AWT Event Listeners Standard w. (Details Continued) ne • MouseListener – Applies to basic mouse events • •ev mouseEntered(MouseEvent event) mouseExited(MouseEvent event) • ia mousePressed(MouseEvent event) • • PD mouseReleased(MouseEvent event) mouseClicked(MouseEvent event) -- Release without drag F. – Applies on release if no movement since press • MouseMotionListener co – Handles mouse movement m • mouseMoved(MouseEvent event) • mouseDragged(MouseEvent event) 21 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 89. ww AWT Event Listeners Standard w. (Details Continued) ne • TextListener – Applies to textfields and text areas ev • textValueChanged(TextEvent event) • WindowListener ia – Handles high-level window events PD • windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, F. windowActivated, windowDeactivated – windowClosing particularly useful co m 22 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 90. ww Mouse Events: Details w. ne • MouseListener and MouseMotionListener share event types • Location of clicks ev – event.getX() and event.getY() • Double clicks ia – Determined by OS, not by programmer – Call event.getClickCount() PD • Distinguishing mouse buttons F. – Call event.getModifiers() and compare to MouseEvent.Button2_MASK for a middle click and co MouseEvent.Button3_MASK for right click. – Can also trap Shift-click, Alt-click, etc. m 23 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 91. ww Example: Spelling- Simple w. Correcting Textfield ne • KeyListener corrects spelling during typing • ActionListener completes word on ENTER ev • FocusListener gives subliminal hints ia PD F. co m 24 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 92. ww Example: Simple Whiteboard w. import java.applet.Applet; import java.awt.*; ne import java.awt.event.*; ev public class SimpleWhiteboard extends Applet { protected int lastX=0, lastY=0; ia public void init() { setBackground(Color.white); PD setForeground(Color.blue); addMouseListener(new PositionRecorder()); F. } addMouseMotionListener(new LineDrawer()); co protected void record(int x, int y) { } lastX = x; lastY = y; m 25 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 93. ww Simple Whiteboard (Continued) w. ne private class PositionRecorder extends MouseAdapter { ev public void mouseEntered(MouseEvent event) { requestFocus(); // Plan ahead for typing } record(event.getX(), event.getY()); ia PD public void mousePressed(MouseEvent event) { record(event.getX(), event.getY()); } } F. ... co m 26 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 94. ww Simple Whiteboard (Continued) w. ... ne ev private class LineDrawer extends MouseMotionAdapter { public void mouseDragged(MouseEvent event) { int x = event.getX(); int y = event.getY(); ia Graphics g = getGraphics(); g.drawLine(lastX, lastY, x, y); record(x, y); PD } } F. } co m 27 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 95. ww Simple Whiteboard (Results) w. ne ev ia PD F. co m 28 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 96. ww Whiteboard: Adding Keyboard w. Events ne import java.applet.Applet; import java.awt.*; ev import java.awt.event.*; public class Whiteboard extends SimpleWhiteboard { ia protected FontMetrics fm; PD public void init() { super.init(); F. Font font = new Font("Serif", Font.BOLD, 20); setFont(font); } co fm = getFontMetrics(font); addKeyListener(new CharDrawer()); m 29 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 97. ww Whiteboard (Continued) w. ... ne private class CharDrawer extends KeyAdapter { ev // When user types a printable character, // draw it and shift position rightwards. ia public void keyTyped(KeyEvent event) { PD String s = String.valueOf(event.getKeyChar()); getGraphics().drawString(s, lastX, lastY); record(lastX + fm.stringWidth(s), lastY); } } F. } co m 30 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 98. ww Whiteboard (Results) w. ne ev ia PD F. co m 31 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 99. ww Summary w. • General strategy ne – Determine what type of listener is of interest ev • Check table of standard types – Define a class of that type ia • Extend adapter separately, implement interface, in anonymous inner class PD extend adapter in named inner class, extend adapter – Register an object of your listener class with the window • Call addXxxListener F. • Understanding listeners – Methods give specific behavior. co • Arguments to methods are of type XxxEvent – Methods in MouseEvent of particular interest m 32 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 100. ww core w. ne evprogramming ia PD Questions? F. co m 33 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
  • 101. ww Preview w. ne • Whiteboard had freehand drawing only – Need GUI controls to allow selection of other drawing methods ev • Whiteboard had only “temporary” drawing ia – Covering and reexposing window clears drawing PD – After cover multithreading, we’ll see solutions to this problem • Most general is double buffering • Whiteboard was “unshared” F. – Need network programming capabilities so that two co different whiteboards can communicate with each other m 34 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 102. ww w.n ee vi aP DF Inheritance 1
  • 103. DF Agenda aP ● What is and Why Inheritance? ● How to derive a sub-class? vi ● Object class ee ● Constructor calling chain ● “super” keyword .n ● Overriding methods w ● Hiding methods Hiding fields ww ● ● Type casting ● Final class and final methods 2
  • 104. DF aP vi ee .n w What is ww Inheritance? 3
  • 105. DF What is Inheritance? aP ● Inheritance is the concept of a child class (sub class) vi automatically inheriting the variables and methods defined in its parent class (super class). ee ● A primary feature of object-oriented programming along with encapsulation and polymorphism w .n ww 4
  • 106. DF Why Inheritance? Reusability aP ● Benefits of Inheritance in OOP : Reusability vi – Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses ee ● Thus, you write a method only once and it can be used by all subclasses. .n – Once a set of properties (fields) are defined in a super class, the same set of properties are inherited by all w subclasses ww ● A class and its children share common set of properties – A subclass only needs to implement the differences between itself and the parent. 5
  • 107. DF aP vi ee .n w How to derive a ww sub-class? 6
  • 108. DF extends keyword aP ● To derive a child class, we use the extends keyword. vi ● Suppose we have a parent class called Person. ee public class Person { protected String name; .n protected String address; /** w * Default constructor */ ww public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } . . . . } 7
  • 109. DF extends keyword aP ● Now, we want to create another class named Student vi ● Since a student is also a person, we decide to just ee extend the class Person, so that we can inherit all the properties and methods of the existing class Person. .n ● To do this, we write, w public class Student extends Person { ww public Student(){ System.out.println(“Inside Student:Constructor”); } . . . . } 8
  • 110. DF What You Can Do in a Sub-class aP ● A subclass inherits all of the “public” and “protected” vi members (fields or methods) of its parent, no matter what package the subclass is in ee ● If the subclass is in the same package as its parent, it also inherits the package-private members (fields .n or methods) of the parent w ww 9
  • 111. DF What You Can Do in a Sub-class Regarding Fields aP ● The inherited fields can be used directly, just like any vi other fields. ee ● You can declare new fields in the subclass that are not in the super class .n ● You can declare a field in the subclass with the same name as the one in the super class, thus hiding it w (not recommended). A subclass does not inherit the private members of ww ● its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be used by the subclass. 10
  • 112. DF What You Can Do in a Sub-class Regarding Methods aP ● The inherited methods can be used directly as they are. vi ● You can write a new instance method in the subclass that ee has the same signature as the one in the super class, thus overriding it. You can write a new static method in the subclass that .n ● has the same signature as the one in the super class, thus hiding it. w ● You can declare new methods in the subclass that are ww not in the super class. 11
  • 113. DF aP vi ee .n w Object Class ww 12
  • 114. DF Object Class aP ● Object class is mother of all classes – In Java language, all classes are sub-classed (extended) from the Object super class vi – Object class is the only class that does not have a parent ee class ● Defines and implements behavior common to all .n classes including the ones that you write – getClass() w – equals() ww – toString() – ... 13
  • 115. DF Class Hierarchy aP ● A sample class hierarchy vi ee w .n ww 14
  • 116. DF Super class & Sub class aP ● Super class (Parent class) Any class above a specific class in the class hierarchy. vi – ● Sub class (Child class) ee – Any class below a specific class in the class hierarchy. w .n ww 15
  • 117. DF aP vi ee .n w Constructor Calling ww Chain 16
  • 118. DF How Constructor method of a Super class gets called aP ● A subclass constructor invokes the constructor of vi the super class implicitly ee – When a Student object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Person class, is invoked implicitly before .n sub-class's constructor method is invoked ● A subclass constructor can invoke the constructor w of the super explicitly by using the “super” keyword ww – The constructor of the Student class can explicitly invoke the constructor of the Person class using “super” keyword – Used when passing parameters to the constructor of the super class 17
  • 119. DF Example: Constructor Calling Chain aP ● To illustrate this, consider the following code, vi public static void main( String[] args ){ ee Student anna = new Student(); } In the code, we create an object of class Student. .n ● The output of the program is, w Inside Person:Constructor ww Inside Student:Constructor 18
  • 120. DF Example: Constructor Calling Chain aP ● The program flow is shown below. vi ee w .n ww 19
  • 121. DF aP vi ee .n w “super” keyword ww 20
  • 122. DF The “super” keyword aP ● A subclass can also explicitly call a constructor of vi its immediate super class. ee ● This is done by using the super constructor call. .n ● A super constructor call in the constructor of a w subclass will result in the execution of relevant constructor from the super class, based on the ww arguments passed. 21
  • 123. DF The “super” keyword aP ● For example, given our previous example classes vi Person and Student, we show an example of a super constructor call. ee ● Given the following code for Student, .n public Student(){ super( "SomeName", "SomeAddress" ); w System.out.println("Inside Student:Constructor"); } ww 22
  • 124. DF The “super” keyword aP ● Few things to remember when using the super vi constructor call: ee – The super() call must occur as the first statement in a constructor – The super() call can only be used in a constructor (not in .n ordinary methods) w ww 23
  • 125. DF The “super” keyword aP ● Another use of super is to refer to members of the vi super class (just like the this reference ). ee ● For example, public Student() { .n super.name = “somename”; super.address = “some address”; w } ww 24
  • 126. DF aP vi ee .n w Overriding Methods ww 25
  • 127. DF Overriding methods aP ● If a derived class needs to have a different implementation of a certain instance method from vi that of the super class, override that instance method in the sub class ee – Note that the scheme of overriding applies only to instance methods .n – For static methods, it is called hiding methods The overriding method has the same name, w ● number and type of parameters, and return type as ww the method it overrides ● The overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type 26
  • 128. DF Example: Overriding Methods aP ● Suppose we have the following implementation for vi the getName method in the Person super class, ee public class Person { : : .n public String getName(){ System.out.println("Parent: getName"); w return name; } } ww 27
  • 129. DF Example: Overriding Methods aP ● To override the getName method of the super class Person in the subclass Student, reimplement the vi method with the same signature ee public class Student extends Person{ : public String getName(){ .n System.out.println("Student: getName"); return name; } w : } ww ● Now, when we invoke the getName method of an object of the subclass Student, the getName method of the Student would be called, and the output would be, Student: getName 28
  • 130. DF Modifiers in the Overriding Methods aP ● The access specifier for an overriding method can vi allow more, but not less, access than the overridden method ee – For example, a protected instance method in the super class can be made public, but not private, in the subclass. .n ● You will get a compile-time error if you attempt to change an instance method in the super class to a w class method in the subclass, and vice versa ww 29
  • 131. DF aP vi ee .n Runtime w Polymorphism with ww Overriding Methods 30
  • 132. DF What is Polymorphism? aP ● Polymorphism in a Java program vi – The ability of a reference variable to change ee behavior according to what object instance it is holding. This allows multiple objects of different subclasses .n – to be treated as objects of a single super class, while automatically selecting the proper methods to w apply to a particular object based on the subclass it ww belongs to – (We will talk more on Polymorphism during our Polymorphism presentation.) 31
  • 133. DF Example: Runtime Polymorphism aP Code: vi Person person2 = new Student(); ee person2.myMethod("test4"); .n Person person3 = new InternationalStudent(); person3.myMethod("test5"); w Result: ww myMethod(test4) in Student class is called myMethod(test5) in InternationalStudent class is called 32
  • 134. DF aP vi ee .n w Hiding Methods ww 33
  • 135. DF Hiding Methods aP ● If a subclass defines a class method (static method) vi with the same signature as a class method in the super class, the method in the subclass “hides” the ee one in the super class w .n ww 34
  • 136. DF Example: Coding of Hiding Static Method aP class Animal { vi public static void testClassMethod() { System.out.println("The class method in Animal."); ee } } .n // The testClassMethod() of the child class hides the one of the w // super class – it looks like overriding, doesn't it? But // there is difference. We will talk about in the following slide. ww class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } 35 }
  • 137. DF Overriding Method vs. Hiding Method aP ● Hiding a static method of a super class looks like vi overriding an instance method of a super class ee ● The difference comes during runtime – When you override an instance method, you get the benefit of run-time polymorphism .n – When you override an static method, there is no runt-time w polymorphism ww 36
  • 138. DF Example: Overriding Method vs. Hiding Method during Runtime aP // Create object instance of Cat. vi Cat myCat = new Cat(); ee // The object instance is Cat type // and assigned to Animal type variable. Animal myAnimal2 = myCat; .n // For static method, the static method of // the super class gets called. w Animal.testClassMethod(); ww // For instance method, the instance method // of the subclass is called even though // myAnimal2 is a super class type. This is // run-time polymorphism. myAnimal2.testInstanceMethod(); 37
  • 139. DF aP vi ee .n w Hiding Fields ww 38
  • 140. DF Hiding Fields aP ● Within a sub class, a field that has the same name as vi a field in the super class hides the super class' field, even if their types are different ee ● Within the subclass, the field in the super class cannot be referenced by its simple name .n – Instead, the field must be accessed through super keyword w ● Generally speaking, hiding fields is not a recommended programming practice as it makes ww code difficult to read 39
  • 141. DF aP vi ee .n w Type Casting ww 40
  • 142. DF What is “Type”? aP ● When an object instance is created from a class, we vi say the object instance is “type” of the class and its super classes ee ● Example: .n Student student1 = new Student(); – student1 object instance is the type of Student or it is w Student type – student1 object instance is also type of Person if Student is ww a child class of Person – student1 object instance is also type of Object 41
  • 143. DF What is Significance? aP ● An object instance of a particular type can be used in vi any place where an instance of the type and its super type is called for ee ● Example: .n – student1 object instance is a “type” of TuftsStudent, Student, and Peson w – student1 object can be used in any place where object instance of the type of TuftsStudent, Student, or Person is ww called for ● This enables polymorphism 42
  • 144. DF Implicit Type Casting aP ● An object instance of a subclass can be assigned to a vi variable (reference) of a parent class through implicit type casting – this is safe since an object instance of a ee subclass “is” also the type of the super class ● Example .n – Let's assume Student class is a child class of Person class w – Let's assume TuftsStudent class is a child class of Student class ww TuftsStudent tuftstudent = new TuftsStudent(); Student student = tuftsstudent; // Implicit type casting Person person = tuftsstudent; // Implicit type casting Object object = tuftsstudent; // Implicit type casting 43
  • 145. DF Type Casting between Objects aP vi ee tuftsstudent student TuftsStudent .n Object instance person w ww 44
  • 146. DF Explicit Type Casting aP ● An object instance of a super class must be assigned to vi a variable (reference) of a child class through explicit type casting ee – Not doing it will result in a compile error since the type assignment is not safe .n – Compiler wants to make sure you know what you are doing w ● Example – Let's assume Student class is a child class of Person class ww Person person1 = new Student(); Student student1 = (Student) person1; // Explicit type casting 45
  • 147. DF Runtime Type Mismatch Exception aP ● Even with explicit casting, you could still end up vi having a runtime error ee ● Example – Let's assume Student class is a child class of Person class .n – Let's assume Teacher class is also a child class of Person class w Person person1 = new Student(); ww Person person2 = new Teacher(); Student student1 = (Student) person1; // Explicit type casting // No compile error, but runtime type mismatch exception Student student2 = (Student) person2; 46
  • 148. DF Use instanceof Operator to Prevent Runtime Type Mismatch Error aP ● You can check the type of the object instance using vi instanceof before the type casting ee ● Example Person person1 = new Student(); .n Person person2 = new Teacher(); w // Do the casting only when the type is verified ww if (person2 instanceof Student) { Student student2 = (Student) person2; } 47
  • 149. DF aP vi ee .n w Final Class & ww Final Method 48
  • 150. DF Final Classes aP ● Final Classes vi – Classes that cannot be extended – To declare final classes, we write, ee public final ClassName{ . . . .n } ● Example: w public final class Person { . . . ww } ● Other examples of final classes are your wrapper classes and String class – You cannot create a subclass of String class 49
  • 151. DF Final Methods aP ● Final Methods vi – Methods that cannot be overridden ee – To declare final methods, we write, public final [returnType] [methodName]([parameters]){ . . . .n } Static methods are automatically final w ● ww 50
  • 152. DF Example: final Methods aP public final String getName(){ vi return name; } ee .n w ww 51
  • 153. DF aP vi ee Inheritance .n w ww 52
  • 154. DF aP vi ee Abstract Class & .n Java Interface w ww 1
  • 155. DF Agenda aP ● What is an Abstract method and an Abstract class? ● What is Interface? vi ● Why Interface? ee ● Interface as a Type ● Interface vs. Class .n ● Defining an Interface w ● Implementing an Interface Implementing multiple Interface's ww ● ● Inheritance among Interface's ● Interface and Polymorphism ● Rewriting an Interface 2
  • 156. DF aP vi ee .n w What is ww an Abstract Class? 3
  • 157. DF Abstract Methods aP ● Methods that do not have implementation (body) vi ● To create an abstract method, just write the method ee declaration without the body and use the abstract keyword .n – No { } w ● For example, ww // Note that there is no body public abstract void someMethod(); 4
  • 158. DF Abstract Class aP ● An abstract class is a class that contains one or vi more abstract methods ee ● An abstract class cannot instantiated // You will get a compile error on the following code .n MyAbstractClass a1 = new MyAbstractClass(); ● Another class (Concrete class) has to provide w implementation of abstract methods ww – Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation – Concrete class uses extends keyword 5
  • 159. DF Sample Abstract Class aP public abstract class LivingThing { vi public void breath(){ System.out.println("Living Thing breathing..."); } ee public void eat(){ System.out.println("Living Thing eating..."); .n } w /** * Abstract method walk() ww * We want this method to be implemented by a * Concrete class. */ public abstract void walk(); } 6
  • 160. DF Extending an Abstract Class aP ● When a concrete class extends the LivingThing vi abstract class, it must implement the abstract method walk(), or else, that subclass will also ee become an abstract class, and therefore cannot be instantiated. .n For example, w ● public class Human extends LivingThing { ww public void walk(){ System.out.println("Human walks..."); } } 7
  • 161. DF When to use Abstract Methods & aP Abstract Class? ● Abstract methods are usually declared where two vi or more subclasses are expected to fulfill a similar role in different ways through different ee implementations – These subclasses extend the same Abstract class and .n provide different implementations for the abstract methods w ● Use abstract classes to define broad types of ww behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. 8
  • 162. DF aP vi ee .n w What is Interface? ww 9
  • 163. DF What is an Interface? aP ● It defines a standard and public way of specifying vi the behavior of classes ee – Defines a contract ● All methods of an interface are abstract methods .n – Defines the signatures of a set of methods, without the body (implementation of the methods) w ● A concrete class must implement the interface (all the abstract methods of the Interface) ww ● It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors 10
  • 164. DF Example: Interface aP vi // Note that Interface contains just set of method ee // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. .n public interface Relation { w public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); ww public boolean isEqual( Object a, Object b); } 11
  • 165. DF Example 2: OperatorCar Interface aP public interface OperateCar { vi // constant declarations, if any ee // method signatures int turn(Direction direction, .n double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); w int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, ww double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); ...... // more method signatures } 12
  • 166. DF aP vi ee .n w Why Interface? ww 13
  • 167. DF Why do we use Interfaces? Reason #1 aP ● To reveal an object's programming interface vi (functionality of the object) without revealing its implementation ee – This is the concept of encapsulation .n – The implementation can change without affecting the caller of the interface w – The caller does not need the implementation at the compile time ww ● It needs only the interface at the compile time ● During runtime, actual object instance is associated with the interface type 14
  • 168. DF Why do we use Interfaces? Reason #2 aP ● To have unrelated classes implement similar vi methods (behaviors) ee – One class is not a sub-class of another ● Example: .n – Class Line and class MyInteger ● They are not related through inheritance w ● You want both to implement comparison methods ww – checkIsGreater(Object x, Object y) – checkIsLess(Object x, Object y) – checkIsEqual(Object x, Object y) – Define Comparison interface which has the three abstract methods above 15
  • 169. DF Why do we use Interfaces? Reason #3 aP ● To model multiple inheritance vi – A class can implement multiple interfaces while it can extend only one class ee w .n ww 16
  • 170. DF Interface vs. Abstract Class aP ● All methods of an Interface are abstract methods vi while some methods of an Abstract class are abstract methods ee – Abstract methods of abstract class have abstract modifier .n ● An interface can only define constants while abstract class can have fields w ● Interfaces have no direct inherited relationship with ww any particular class, they are defined independently – Interfaces themselves have inheritance relationship among themselves 17
  • 171. DF aP vi ee .n w Interface as a ww Type 18
  • 172. DF Interface as a Type aP ● When you define a new interface, you are defining a vi new reference type ee ● You can use interface names anywhere you can use any other type name If you define a reference variable whose type is an .n ● interface, any object you assign to it must be an instance of a class that implements the interface w ww 19
  • 173. DF Example: Interface as a Type aP ● Let's say Person class implements PersonInterface vi interface You can do ● ee – Person p1 = new Person(); .n – PersonInterface pi1 = p1; – PersonInterface pi2 = new Person(); w ww 20
  • 174. DF aP vi ee .n w Interface vs. Class ww 21
  • 175. DF Interface vs. Class: Commonality aP ● Interfaces and classes are both types vi – This means that an interface can be used in places where a class can be used ee – For example: .n // Recommended practice PersonInterface pi = new Person(); w // Not recommended practice Person pc = new Person(); ww ● Interface and Class can both define methods 22
  • 176. DF Interface vs. Class: Differences aP ● The methods of an Interface are all abstract vi methodsee – They cannot have bodies ● You cannot create an instance from an interface .n – For example: PersonInterface pi = new PersonInterface(); //ERROR! w ● An interface can only be implemented by classes or extended by other interfaces ww 23
  • 177. DF aP vi ee .n w Defining Interface ww 24
  • 178. DF Defining Interfaces aP ● To define an interface, we write: vi ee public interface [InterfaceName] { //some methods without the body .n } w ww 25
  • 179. DF Defining Interfaces aP ● As an example, let's create an interface that defines vi relationships between two objects according to the “natural order” of the objects. ee public interface Relation { .n public boolean isGreater( Object a, Object b); w public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); ww } 26
  • 180. DF aP vi ee .n w Implementing ww Interface 27
  • 181. DF Implementing Interfaces aP ● To create a concrete class that implements an interface, use the implements keyword. vi /** * Line class implements Relation interface ee */ public class Line implements Relation { private double x1; .n private double x2; private double y1; private double y2; w public Line(double x1, double x2, double y1, double y2){ ww this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } // More code follows 28
  • 182. DF Implementing Interfaces public double getLength(){ aP double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)); return length; } vi public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); ee double bLen = ((Line)b).getLength(); return (aLen > bLen); } .n public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); w return (aLen < bLen); } ww public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); } } 29
  • 183. DF Implementing Interfaces aP ● When your class tries to implement an interface, vi always make sure that you implement all the methods of that interface, or else, you would ee encounter this error, .n Line.java:4: Line is not abstract and does not override w abstract method isGreater(java.lang.Object,java.lang.Object) in Relation ww public class Line implements Relation ^ 1 error 30
  • 184. DF Implementing Class aP ● Implementing class can have its own methods vi ● Implementing class extend a single super class or ee abstract class w .n ww 31
  • 185. DF aP vi ee .n w Implementing ww Multiple Interfaces 32
  • 186. DF Relationship of an Interface to a aP Class ● A concrete class can only extend one super class, vi but it can implement multiple Interfaces ee – The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative. .n ● All abstract methods of all interfaces have to be w implemented by the concrete class ww 33
  • 187. DF Example: Implementing Multiple aP Interfaces ● A concrete class extends one super class but vi multiple Interfaces: ee public class ComputerScienceStudent extends Student .n implements PersonInterface, AnotherInterface, w Thirdinterface{ // All abstract methods of all interfaces ww // need to be implemented. } 34
  • 188. DF aP vi ee .n w Inheritance ww Among Interfaces 35
  • 189. DF Inheritance Among Interfaces aP ● Interfaces are not part of the class hierarchy vi ● However, interfaces can have inheritance ee relationship among themselves .n public interface PersonInterface { void doSomething(); w } ww public interface StudentInterface extends PersonInterface { void doExtraSomething(); } 36
  • 190. DF aP vi ee .n w Interface & ww Polymorphism 37
  • 191. DF Interface and Polymorphism aP ● Interfaces exhibit polymorphism as well, since vi program may call an interface method, and the proper version of that method will be executed ee depending on the type of object instance passed to the interface method call w .n ww 38
  • 192. DF aP vi ee .n w Rewriting Interfaces ww 39
  • 193. DF Problem of Rewriting an Existing Interface aP ● Consider an interface that you have developed called DoIt: public interface DoIt { vi void doSomething(int i, double x); int doSomethingElse(String s); ee } ● Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: .n public interface DoIt { w void doSomething(int i, double x); int doSomethingElse(String s); ww boolean didItWork(int i, double x, String s); } ● If you make this change, all classes that implement the old DoIt interface will break because they don't implement all methods of the the interface anymore 40
  • 194. DF Solution of Rewriting an Existing Interface aP ● Create more interfaces later ● For example, you could create a DoItPlus interface that vi extends DoIt: ee public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); } .n ● Now users of your code can choose to continue to use the old interface or to upgrade to the new interface w ww 41
  • 195. DF aP vi ee .n When to Use an w Abstract Class over ww an Interface? 42
  • 196. DF When to use an Abstract Class over Interface? aP ● For non-abstract methods, you want to use them vi when you want to provide common implementation code for all sub-classes ee – Reducing the duplication .n ● For abstract methods, the motivation is the same with the ones in the interface – to impose a w common behavior for all sub-classes without dictating how to implement it ww ● Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class 43
  • 197. DF aP vi ee Abstract Class & .n Java Interface w ww 44
  • 198. DF aP vi ee Java I/O Stream .n w ww 1
  • 199. DF Topics aP ● What is an I/O stream? vi ● Types of Streams ● Stream class hierarchy ee ● Control flow of an I/O operation using Streams Byte streams .n ● ● Character streams w ● Buffered streams Standard I/O streams ww ● ● Data streams ● Object streams ● File class 2
  • 200. DF aP vi ee .n w What is an I/O ww Stream? 3
  • 201. DF I/O Streams aP ● An I/O Stream represents an input source or an vi output destination ee ● A stream can represent many different kinds of sources and destinations .n – disk files, devices, other programs, a network socket, and memory arrays w ● Streams support many different kinds of data ww – simple bytes, primitive data types, localized characters, and objects ● Some streams simply pass on data; others manipulate and transform the data in useful ways. 4
  • 202. DF I/O Streams aP ● No matter how they work internally, all streams vi present the same simple model to programs that use them ee – A stream is a sequence of data w .n ww 5
  • 203. DF Input Stream aP ● A program uses an input stream to read data from vi a source, one item at a time ee w .n ww 6 source:java.sun.com
  • 204. DF Output Stream aP ● A program uses an output stream to write data to a vi destination, one item at time ee w .n ww 7
  • 205. DF aP vi ee .n w Types of Streams ww 8
  • 206. DF General Stream Types aP ● Character and Byte Streams vi – Character vs. Byte ee ● Input and Output Streams – Based on source or destination .n ● Node and Filter Streams w – Whether the data on a stream is manipulated or transformed or not ww 9
  • 207. DF Character and Byte Streams aP ● Byte streams – For binary data vi – Root classes for byte streams: ee ● The InputStream Class ● The OutputStream Class .n ● Both classes are abstract ● Character streams w – For Unicode characters ww – Root classes for character streams: ● The Reader class ● The Writer class ● Both classes are abstract 10
  • 208. DF Input and Output Streams aP ● Input or source streams vi – Can read from these streams – Root classes of all input streams: ee ● The InputStream Class The Reader Class .n ● ● Output or sink (destination) streams w – Can write to these streams ww – Root classes of all output streams: ● The OutputStream Class ● The Writer Class 11
  • 209. DF Node and Filter Streams aP ● Node streams (Data sink stream) vi – Contain the basic functionality of reading or writing from a specific location ee – Types of node streams include files, memory and pipes .n ● Filter streams (Processing stream) w – Layered onto node streams between threads or processes ww – For additional functionality- altering or managing data in the stream ● Adding layers to a node stream is called stream chaining 12
  • 210. DF aP vi ee .n w Stream Class ww Hierarchy 13
  • 211. DF Streams InputStream aP vi OutputStream ee .n Reader w Writer ww 14
  • 212. DF Abstract Classes aP ● InputStream & OutputStream vi ● Reader & Writer ee w .n ww 15
  • 213. DF InputStream Abstract Class aP vi ee .n w ww 16
  • 214. DF InputStream Abstract Class aP vi ee .n w ww 17
  • 215. DF Node InputStream Classes aP vi ee .n w ww 18
  • 216. DF Filter InputStream Classes aP vi ee .n w ww 19
  • 217. DF OutputStream Abstract Class aP vi ee .n w ww 20
  • 218. DF Node OutputStream Classes aP vi ee .n w ww 21
  • 219. DF Filter OutputStream Classes aP vi ee .n w ww 22
  • 220. DF The Reader Class: Methods aP vi ee .n w ww 23
  • 221. DF The Reader Class: Methods aP vi ee .n w ww 24
  • 222. DF Node Reader Classes aP vi ee .n w ww 25
  • 223. DF Filter Reader Classes aP vi ee .n w ww 26
  • 224. DF The Writer Class: Methods aP vi ee .n w ww 27
  • 225. DF Node Writer Classes aP vi ee .n w ww 28
  • 226. DF Filter Writer Classes aP vi ee .n w ww 29
  • 227. DF aP vi ee .n Control Flow of w I/O Operation using ww Streams 30
  • 228. DF Control Flow of an I/O operation aP Create a stream object and associate it with a data- vi source (data-destination) ee Give the stream object the desired functionality through stream chaining .n while (there is more information) read(write) next data from(to) the stream w close the stream ww 31
  • 229. DF aP vi ee .n w Byte Stream ww 32
  • 230. DF Byte Stream aP ● Programs use byte streams to perform input and vi output of 8-bit bytes ee ● All byte stream classes are descended from InputStream and OutputStream .n ● There are many byte stream classes – FileInputStream and FileOutputStream w ● They are used in much the same way; they differ ww mainly in the way they are constructed 33
  • 231. DF When Not to Use Byte Streams? aP ● Byte Stream represents a kind of low-level I/O that vi you should avoid ee – If the data contains character data, the best approach is to use character streams .n – There are also streams for more complicated data types w ● Byte streams should only be used for the most primitive I/O ww ● All other streams are based on byte stream 34
  • 232. DF Example: FileInputStream & aP FileOutputStream public class CopyBytes { vi public static void main(String[] args) throws IOException { FileInputStream in = null; ee FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); .n out = new FileOutputStream("outagain.txt"); int c; w while ((c = in.read()) != -1) { ww out.write(c); } } // More code 35
  • 233. DF Example: FileInputStream & aP FileOutputStream finally { vi if (in != null) { in.close(); } ee if (out != null) { out.close(); .n } } w } } ww 36
  • 234. DF Simple Byte Stream input and aP output vi ee .n w ww 37
  • 235. DF aP vi ee .n w Character Stream ww 38
  • 236. DF Character Stream aP ● The Java platform stores character values using vi Unicode conventions ee ● Character stream I/O automatically translates this internal format to and from the local character set. .n – In Western locales, the local character set is usually an 8-bit superset of ASCII. w ● All character stream classes are descended from Reader and Writer ww ● As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. 39
  • 237. DF Character Stream aP ● For most applications, I/O with character streams is no more complicated than I/O with byte streams. vi – Input and output done with stream classes automatically translates to and from the local ee character set. – A program that uses character streams in place of .n byte streams automatically adapts to the local character set and is ready for internationalization — w all without extra effort by the programmer. ww – If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. – Later, if internationalization becomes a priority, your program can be adapted without extensive recoding. 40
  • 238. DF Example: FileReader & FileWriter aP public class CopyCharacters { vi public static void main(String[] args) throws IOException { FileReader inputStream = null; ee FileWriter outputStream = null; try { .n inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); w int c; ww while ((c = inputStream.read()) != -1) { outputStream.write(c); } } // More code 41
  • 239. DF Example: FileReader & FileWriter aP finally { vi if (inputStream != null) { inputStream.close(); } ee if (outputStream != null) { outputStream.close(); .n } } w } } ww 42
  • 240. DF Character Stream and Byte Stream aP ● Character streams are often "wrappers" for byte vi streamsee ● The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. .n – FileReader, for example, uses FileInputStream, w while FileWriter uses FileOutputStream ww 43
  • 241. DF Line-Oriented I/O aP ● Character I/O usually occurs in bigger units than vi single characters ee – One common unit is the line: a string of characters with a line terminator at the end .n – A line terminator can be a carriage-return/line- feed sequence ("rn"), a single carriage-return w ("r"), or a single line-feed ("n"). ww 44
  • 242. DF Example: Line-oriented I/O aP File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); vi FileReader in = new FileReader(inputFile); ee FileWriter out = new FileWriter(outputFile); BufferedReader inputStream = new BufferedReader(in); .n PrintWriter outputStream = new PrintWriter(out); w String l; while ((l = inputStream.readLine()) != null) { ww System.out.println(l); outputStream.println(l); } in.close(); 45 out.close();
  • 243. DF aP vi ee .n w Buffered Stream ww 46
  • 244. DF Why Buffered Streams? aP ● An unbuffered I/O means each read or write request is handled directly by the underlying OS vi – This can make a program much less efficient, since each such request often triggers disk access, ee network activity, or some other operation that is relatively expensive. .n ● To reduce this kind of overhead, the Java platform implements buffered I/O streams w – Buffered input streams read data from a memory ww area known as a buffer; the native input API is called only when the buffer is empty – Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. 47
  • 245. DF How to create Buffered Streams? aP ● A program can convert a unbuffered stream into a vi buffered stream using the wrapping idiom ee – A unbuffered stream object is passed to the constructor for a buffered stream class .n ● Example inputStream = w new BufferedReader(new FileReader("xanadu.txt")); ww outputStream = new BufferedWriter(new FileWriter("characteroutput.txt")); 48
  • 246. DF Buffered Stream Classes aP ● BufferedInputStream and BufferedOutputStream vi create buffered byte streams ee ● BufferedReader and BufferedWriter create buffered character streams w .n ww 49
  • 247. DF Flushing Buffered Streams aP ● It often makes sense to write out a buffer at critical vi points, without waiting for it to fill. This is known as flushing the buffer. ee ● Some buffered output classes support autoflush, specified by an optional constructor argument. .n – When autoflush is enabled, certain key events cause the buffer to be flushed w – For example, an autoflush PrintWriter object flushes ww the buffer on every invocation of println or format. ● To flush a stream manually, invoke its flush method – The flush method is valid on any output stream, but has no effect unless the stream is buffered. 50
  • 248. DF aP vi ee .n w Standard Streams ww 51
  • 249. DF Standard Streams on Java Platform aP ● Three standard streams vi – Standard Input, accessed through System.in ee – Standard Output, accessed through System.out – Standard Error, accessed through System.err .n ● These objects are defined automatically and do not need to be opened w ● System.out and System.err are defined as ww PrintStream objects 52
  • 250. DF aP vi ee .n w Data Streams ww 53
  • 251. DF Data Streams aP ● Data streams support binary I/O of primitive data vi type values (boolean, char, byte, short, int, long, float, and double) as well as String values ee ● All data streams implement either the DataInput interface or the DataOutput interface .n ● DataInputStream and DataOutputStream are most w widely-used implementations of these interfaces ww 54
  • 252. DF DataOutputStream aP ● DataOutputStream can only be created as a wrapper vi for an existing byte stream object out = new DataOutputStream( ee new BufferedOutputStream( new FileOutputStream(dataFile))); .n for (int i = 0; i < prices.length; i ++) { w out.writeDouble(prices[i]); out.writeInt(units[i]); ww out.writeUTF(descs[i]); } 55
  • 253. DF DataInputStream aP ● Like DataOutputStream, DataInputStream must be constructed as a wrapper for a byte stream vi ● End-of-file condition is detected by catching EOFException, instead of testing for an invalid return ee value in = new DataInputStream( .n new BufferedInputStream( new FileInputStream(dataFile))); w try{ ww double price = in.readDouble(); int unit = in.readInt(); String desc = in.readUTF(); } catch (EOFException e){ } 56
  • 254. DF aP vi ee .n w Object Streams ww 57
  • 255. DF Object Streams aP ● Object streams support I/O of objects vi – Like Data streams support I/O of primitive data types ee – The object has to be Serializable type ● The object stream classes are ObjectInputStream .n and ObjectOutputStream – These classes implement ObjectInput and w ObjectOutput, which are subinterfaces of DataInput ww and DataOutput – An object stream can contain a mixture of primitive and object values 58
  • 256. DF Input and Output of Complex aP Object ● The writeObject and readObject methods are vi simple to use, but they contain some very sophisticated object management logic ee – This isn't important for a class like Calendar, which just encapsulates primitive values. But many objects .n contain references to other objects. w ● If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the ww objects the original object referred to. – These additional objects might have their own references, and so on. 59
  • 257. DF WriteObject aP ● The writeObject traverses the entire web of object vi references and writes all objects in that web onto the stream ee ● A single invocation of writeObject can cause a large number of objects to be written to the stream. w .n ww 60
  • 258. DF I/O of multiple referred-to objects aP ● Object a contains references to objects b and c, vi while b contains references to d and e ee w .n ww 61
  • 259. DF I/O of multiple referred-to objects aP ● Invoking writeObject(a) writes not just a, but all the vi objects necessary to reconstitute a, so the other four objects in this web are written also ee ● When a is read back by readObject, the other four objects are read back as well, and all the original .n object references are preserved. w ww 62
  • 260. DF aP vi ee .n w Closing Streams ww 63
  • 261. DF Always Close Streams aP ● Closing a stream when it's no longer needed is very vi important — so important that your program should use a finally block to guarantee that both streams ee will be closed even if an error occurs – This practice helps avoid serious resource leaks. w .n ww 64
  • 262. ww w .n ee vi aP DF File Class 65
  • 263. DF The File Class aP ● Not a stream class vi ● Important since stream classes manipulate File ee objects ● Abstract representation of actual files and directory .n pathname w ww 66
  • 264. DF The File Class: Constructors aP ● Has four constructors vi ee w .n ww 67
  • 265. DF The File Class: Methods aP vi ee .n w ww 68
  • 266. DF The File Class: Methods aP vi ee .n w ww 69
  • 267. DF The File Class: Example aP 1 import java.io.*; vi 2 public class FileInfoClass { 3 ee 4 public static void main(String args[]) { 5 String fileName = args[0]; .n 6 File fn = new File(fileName); w 7 System.out.println("Name: " + fn.getName()); 8 if (!fn.exists()) { ww 9 System.out.println(fileName 10 + " does not exists."); 11 //continued... 70
  • 268. DF The File Class: Example aP 12 /* Create a temporary directory instead. */ vi 13 System.out.println("Creating temp directory..."); fileName = "temp"; 14 ee 15 fn = new File(fileName); 16 fn.mkdir(); .n 17 System.out.println(fileName + w 18 (fn.exists()? "exists": "does not exist")); 19 System.out.println("Deleting temp directory..."); ww 20 fn.delete(); 21 //continued... 71
  • 269. DF The File Class: Example aP 24 vi 25 System.out.println(fileName + " is a " + (fn.isFile()? "file." :"directory.")); 26 ee 27 28 if (fn.isDirectory()) { .n 29 String content[] = fn.list(); w 30 System.out.println("The content of this directory: 43 for (int i = 0; i < content.length; i++) { ww 44 System.out.println(content[i]); 45 } 46 } 35 72 36 //continued...
  • 270. DF The File Class: Example aP 36 vi 37 if (!fn.canRead()) { 38 ee 39 System.out.println(fileName 40 + " is not readable."); .n 41 return; w 42 } 43 //continued... ww 73
  • 271. DF The File Class: Example aP 47 System.out.println(fileName + " is " + fn.length() vi 48 + " bytes long."); System.out.println(fileName + " is " + 49 ee 50 fn.lastModified() + " bytes long."); 51 .n 52 if (!fn.canWrite()) { w 53 System.out.println(fileName 54 + " is not writable."); ww 55 } 56 } 57 } 74
  • 272. DF Modified InputStream/ aP OutputStream Example 24 } catch (IOException ie) { vi 25 ie.printStackTrace(); 26 } ee 27 } 28 .n 29 public static void main(String args[]) { 30 String inputFile = args[0]; w 31 CopyFile cf = new CopyFile(); ww 32 cf.copy(inputFile); 33 } 34 } 75
  • 273. ww w.n ee vi aP DF Thank You! 76
  • 274. References om 1. Java 2: The Complete Reference, Patrick Naughton and Herbert Schildt, Tata McGraw Hill, 1999. Rs 395. .c 2. Programming with Java, 2nd Edition, E. Balagurusamy, Tata McGraw Hill, 1998, reprint, 2000. Rs 170. DF 3. The Java Tutorial, 2nd ed., 2 volumes,Mary Campione and Kathy Walrath, Addison Wesley Longmans, 1998. Latest version available online at aP java.sun.com. Download free. Book: Rs 630 (Vol. 1) and Rs 395 (Vol. 2). 4. Core Java 2, 2 volumes, Cay S. Horstmann, Gary vi Cornell, The Sun Microsystems Press, 1999, Indian reprint 2000. Rs 450 (Vol. 1) and Rs 495 (Vol. 2). ee 5. Using Java 2 Joseph L. Weber Prentice Hall, Eastern Economy Edition, 2000. Rs 499. n 6. The Java Language Specification, 2nd ed, James w. Gosling, Bill Joy, Guy Steele & Gilad Bracha, (1st ed 1996, 2nd ed 2000), Sun Microsystems, 2000. ww
  • 275. Notes om • Basic familiarity will be assumed with – C and C++ – OOP .c – Internet and WWW • Note: Please do whatever is necessary to justify DF these assumptions! aP vi n ee w. ww CKR Java Notes 2
  • 276. Java: Prehistory om • Development 1: C++ – C++ (or “C with Classes”) was invented in 1979, and became the stock .c programming language in the 90’s. (Standardized in Nov. 1997.) DF – What were the reasons for its success? – Lesson: C++ very successful, since it enhanced an existing successful aP language like C. – (instead of building an entirely new programming language). vi • Development 2: GUI ee – Object orientation permits reusable code, hence a Graphical User interface GUI (E.g. MS-Windows). n – GUI has enormously expanded the w. number of computer-users. – Lesson: Object oriented programming ww (OOP) with GUI is the “grand consensus of the computer industry”. CKR Java Notes 3
  • 277. Java: Prehistory (contd.) om • Development 3: Internet – Internet stared in the 1960’s as a way to .c maintain communications in the event of a nuclear attack. DF – Success of ARPANET inspired NSFNET. – In 1983, TCP/IP became the official protocol which connected ARPANET and aP NSFNET. – This collection of connected networks came to be called the Internet. vi – By 1990, 3000 networks and 200,000 computers were connected to the ee Internet. By 1992, there were 1 million hosts. n – The hosts had diverse hardware and operating systems like DOS/Windows, w. UNIX, and MacOS. – Problem: How to share information easily ww across different computer platforms? CKR Java Notes 4
  • 278. Java: Prehistory (contd.) om • Development 4: WWW – To simplify sharing of documents and .c data across the Internet, WWW invented in 1989 at CERN, Geneva, for high-energy physicists. DF – WWW is an architectural framework for viewing documents stored across thousands of machines connected to aP the Internet. – The scattered document seems like a single document using a browser to view vi hypertext, which contains hyperlinks. – However, this concerned passive text or ee document files, and users on the www could not share executable programs. n – Problem: How to incorporate interactive programs on the Web? How to share w. executable programs across platforms? ww CKR Java Notes 5
  • 279. Java: History om • In 1990, Sun Microsystems started a project called Green. .c – Objective: to develop software for consumer electronics. DF – Sun best known for its popular Unix workstation, Solaris OS, and Network File System (NFS). aP – Project was assigned to James Gosling, a veteran of classic network software design. vi – Others included Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan. ee • The team started writing programs in C++ for embedding into n – toasters – washing machines w. – VCR’s – PDA’s (Personal Digital Assistants) ww • Aim was to make these appliances more “intelligent”. But they soon realized... CKR Java Notes 6
  • 280. Java: History (contd.) om • C++ is powerful, but also dangerous. – The power and popularity of C derived .c from the extensive use of pointers. – However, any incorrect use of pointers DF can cause memory leaks, leading the program to crash. – In a complex program, such memory aP leaks are often hard to detect. • Robustness is essential vi – Users have come to expect that Windows may crash or that a program running under Windows may crash. ee (“This program has performed an illegal operation and will be shut down”) n – However, users do not expect toasters to crash, or washing machines to crash. w. – A design for consumer electronics has to be robust. Replacing pointers by ww references, and automating memory management was the proposed solution. CKR Java Notes 7
  • 281. Java: History (contd.) om • Oak: Hence, the team built a new programming language called Oak, which .c – avoided potentially dangerous constructs in C++, such as pointers, pointer arithmetic, operator overloading DF etc. – introduced automatic memory management, freeing the programmer to aP concentrate on other things. • Architecture neutrality (Platform independence) vi – Many different CPU’s are used as controllers. Hardware chips are evolving rapidly. As better chips become ee available, older chips become obsolete and their production is stopped. n – Manufacturers of toasters and washing machines would like to use the chips w. available off the shelf, and would not like to reinvest in compiler development every two-three years. ww – So, the software and programming language had to be architecture neutral. CKR Java Notes 8
  • 282. Java: History (contd) om • It was soon realized that these design goals of consumer electronics perfectly suited an ideal programming language for the Internet and .c WWW, which should be: – object-oriented (& support GUI) – robust DF – architecture neutral • Internet programming presented a BIG business opportunity. Much bigger than programming for aP consumer electronics. – Java was “re-targeted” for the Internet • The team was expanded to include Bill Joy vi (developer of Unix), Arthur van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc. ee • In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava. n • In 1995, Oak was renamed Java. w. – A common story is that the name Java relates to the place from where the development team got its coffee. ww – The name Java survived the trade mark search. CKR Java Notes 9
  • 283. Java Features om • Additional features were added to make Java – secure – multithreaded (concurrent) .c – distributed and dynamic – high performance DF • Security: Is a key feature on the Internet. It should be possible to specify what system resources the program can access. – In the sandbox policy remote applets are aP not trusted to access any local resources, – while local applications are trusted to vi access all resources. – This can be modified, by allowing ee digitally signed applets selective access. • Multiple threads: C and C++ support multiple n threads, using fork(), – this feature is NOT a part of the ANSI/ISO w. standard, and is available only on UNIX. – DOS support is available for the spawn... ww and exec... family of functions. These features are not much used. CKR Java Notes 10
  • 284. But concurrency is essential on the om internet, since download times are uncertain, so one process should not block all others. – Threads also needed for e.g. animation. .c • Distributed: DF – The ultimate vision of OOP is to have objects stored on different computers to interact with each other. That is, a user can assemble a program different parts aP of which are stored on different computers. • Dynamic: vi – Java is both compiled and interpreted. – Thus, source code is compiled to ee bytecode. – The Java Virtual Machine loads and links n parts of the code dynamically at run time. w. – Hence it carries substantial run time type information on objects. ww – Hence, It supports late binding. CKR Java Notes 11
  • 285. High performance om – Though Java uses an interpreter, – it also has a compiler, which generates machine-independent bytecodes. .c – Optimization can take place at this stage to ensure that Java programs can match DF the speed of programs in compiled languages like C++. – Where speed cannot be traded off for aP platform independence, Java provides “native method support”, for code written in languages like C/C++, and compiled for specific platforms. vi n ee w. ww CKR Java Notes 12
  • 286. Java Features: Summary om • Simple • Secure .c • Portable DF • Object-oriented • Robust aP • Multithreaded • Architecture-neutral vi • Interpreted • High-performance ee • Distributed n • Dynamic w. ww CKR Java Notes 13
  • 287. Comparison of Java and other languages by Gosling om .c DF aP vi n ee w. Fig. 1: From the Java Language Environment White ww CKR Java Notes 14
  • 288. The JDK om • The JDK is the Java Development Kit. Major versions are 1.1 (Java 1) and 1.2 (Java 2). (Version 1.3 has just been released.) .c • This can be downloaded free of cost from http://java.sun.com DF • The JDK can be downloaded for different platforms: Windows, Unix (Solaris), MacOS. aP • Requires support for – long file names, and – case-sensitive file names. vi • Hence, will not run in DOS. (Limited platform independence.) ee • Hardware and Software requirements: – Win 95/Win NT4.0 or higher running on n x86 (min. 486/8MB). Little disk space (~ 40 MB). w. – Solaris 2.4 or higher on SPARC ww – Solaris 2.5 or higher on x86. CKR Java Notes 15
  • 289. Comes as a self-extracting exe for Win95+, which om extracts to c:jdk1.2 directory. • Certain environment variables, such as PATH and CLASSPATH need to be set/reset. .c – Path must be set to include c:jdk1.2bin DF – If upgrading, if CLASSPATH set to classes.zip, this should be removed. aP – Setting the CLASSPATH variable is optional: set CLASSPATH= .;c:mydirmyclass.jar;. myclasses.zip vi – There should be no space around = ee – The preferred method is to use the -classpath option with each jdk tool. n – This is preferred since applications may run differently depending upon the w. classpath. – More about CLASSPATH when we study ww packages. CKR Java Notes 16
  • 290. JDK Utilities om • The following are some of the important utilities available under jdk. • javac .c – The java compiler, converts source code into bytecode stored in class files. DF • java – The java interpreter that executes bytecode for a java application from class files. aP • appletviewer – The java interpreter that executes bytecode for a java applet from class vi files. • javadoc ee – Creates HTML documentation based on java source code, and the documentation comments it contains. n • jdb w. – The java debugger. Allows one to step through the program one line at a time, set breakpoints, and examine variables. ww • javah – Generates C/C+ header files for combining with native methods. CKR Java Notes 17
  • 291. Using the JDK: Hello World Application om • Step 1: Enter the Java source code: – Use any non-document text editor, or a simple Integrated Development .c Environment, like Kawa to type the following program. Program 1 DF /** * The HelloWorld class implements an * application that simply displays * “Hello World!” to the aP * standard output (console) */ public class HelloWorld { vi public static void main (String args[]) { //required prototype for main function ee System.out.println(“Hello world!”); } } n • Step 2: Save the source in a file: w. – The file MUST have the same name as the public class in the source, and must have a .java extension. (Hence, support ww for long filenames is required.) CKR Java Notes 18
  • 292. That is, the above file should be saved om as HelloWorld.java with the case maintained. – Note: A java source file cannot contain .c more than one public class according to the above restriction. DF • Step 3: Compile the source file using javac: – use the following command line at the aP shell prompt javac HelloWorld.java vi – If the code is correct, compilation will produce the file ee HelloWorld.class – if there are errors, repeat steps 1-3. n – To see what javac does behind the w. scenes, use the following command line javac -verbose HelloWorld.java ww CKR Java Notes 19
  • 293. Using the jdk: Hello World Application (contd.) om • Step 4: Run the compiled code. – Invoke the java interpreter by the command line .c java HelloWorld DF – Output: Hello World! • Congratulations! You have successfully run your first java program. aP • Note: 1. No file extension is needed when invoking the interpreter. 2. To view execution details of the compiled vi code, use the command line java -prof HelloWorld ee This will generate a profile which shows n – methods called in order of decreasing frequency. w. – how memory is used. ww – list of variable types and bytes necessary to store them. CKR Java Notes 20
  • 294. Anatomy of the HelloWorld program om • New style comments: – The first line of the HelloWorld program .c shows a new style comment. – This is a documentation comment which DF begins with /** and ends with */ – This is in addition to the C-style comments between /* and */ and the aP additional C++ style comments between // and the end of the line. • Using javadoc: vi – The new style comments are used to generate source code documentation. ee – To generate this documentation, use the command line n javadoc HelloWorld.java w. – javadoc ignores old-style comments. ww – it generates four html documents: packages.html, HelloWorld.html, AllNames.html, tree.html. CKR Java Notes 21
  • 295. Anatomy of the HelloWorld Program om • Stripped of comments, this is the HelloWorld program: public class HelloWorld .c { public static void main (String args[]) { DF System.out.println(“Hello world!”); } } • The first line declares a class. public is an aP access specifier for the class. – Note that the main function of C/C++ is put inside a class in Java. vi • Thus, Java is completely object oriented. ee – All methods including the main method (function) are inside classes. n – The main method continues to be the entry point. w. – Every Java application MUST have a main method declared as above. ww – This is NOT required for java applets. CKR Java Notes 22
  • 296. Anatomy of the HelloWorld program (contd) om • Note the prototype of the main method public static void main (String args[]) .c • For the main method – public is the access specifier. DF – static is the storage class. – void is the return type. – String args[] is an array of strings similar to int argc, char *argv[] of aP C/C++. • These declarations are mandatory. – Thus the following declaration will not vi work. public static void main() ee • We can check this out by writing a small program. Program 2 n /** class NoMain has an incorrectly defined w. * main function. This class will compile * correctly, but will not execute. * The interpreter will say ww * In class NoMain: void main (String argv[]) is not defined*/ CKR Java Notes 23
  • 297. om public class NoMain { public static void main() { System.out.println (“This program will not .c run”); } DF } • Why does this happen? aP – Several methods called main can be defined, in a java class. – The interpreter will look for a main vi method with the prescribed signature as the entry point. ee – A method named main, which has some other signature is of no particular significance. It is like any other method n in the class w. – Therefore, if the main method is not declared correctly, the application will not execute. ww CKR Java Notes 24
  • 298. A Java program with two main methods om • The following is an example of a java program with two main methods with different signatures. .c Program 3 public class TwoMains { DF /** This class has two main methods with * different signatures */ public static void main (String args[]) aP { //required prototype for main method System.out.println(“Hello world!”); int i; vi i = main(2); System.out.println (“i = ” + i ); } ee /**This is the additional main method*/ public static int main(int i) { n return i*i; } w. } • Output: ww Hello World! i = 4 CKR Java Notes 25
  • 299. Anatomy of the Hello World Program (contd.) om • The argument to the mandatory main function public static void main (String args[]) .c which is String args [] DF can also be written as String [] args aP • Any other name can be used in place of args, such as argv or argument. • This represents the string of command line vi parameters, as in C/C++, • But ee – There is no need for argc, since an array in Java always knows how many elements it has. n – args[0] is NOT the name of the w. program itself, but the first parameter on the command line. • The last line refers to the println method of the ww out variable (representing the standard output stream) of the System class. CKR Java Notes 26
  • 300. Command line arguments om • We can test the above considerations by means of a small program. Program 4 .c public class CommandLine { public static void main (String argv []) DF { int length = argv.length; String myString = “No. of parameters”r + “ on the command line: ”; aP System.out.println (myString + length); for (int i=0; i length; i++) { myString = argv[i]; vi System.out.println (i + “: ” + myString); } ee } } • Input: java CommandLine Java is a good n language. w. • Output: No of parameters on the command line: 5 0: Java 1: is ww 2: a 3: good 4: language. CKR Java Notes 27
  • 301. Debugging a program om • Sometimes the program compiles but does not work as intended. .c • In this situation the java debugger can be used. – to generate full debugging info use the -g option with javac DF • The debugger is invoked as follows. jdb HelloWorld aP • To set a breakpoint, use the command stop in HelloWorld.main vi followed by run ee • When the breakpoint is hit, type list n to see the code. w. • Type clear HelloWorld.main followed by ww • cont CKR Java Notes 28
  • 302. ww CKR w. nee vi aP Java Notes DF .c om 29
  • 303. ww CKR w. nee vi aP Java Notes DF .c om 30
  • 304. Summary om • We have used the following utilities of JDK – javac (compiler) .c – java (interpreter) – javadoc (for extracting documentation comments) DF – jdb (debugger) • We have learnt to write a basic application in Java, to compile it, and run it. aP • Every java application must have a main method – This main method is defined inside a vi class. – It must have the prescribed signature. ee • Note: A main method is NOT required for java n applets. w. • Java is completely object oriented. No residue from structured programming. – The main method is inside a class ww – class declarations need no semicolon. – Everything must be inside some class! CKR Java Notes 31
  • 305. Elements of Programming style: om • Java is a free-form language, and white space may be used almost anywhere in a Java program. .c – However indentation helps humans to understand the program. DF – Hence we will use appropriate indentation. • Also, object-oriented programming involves a aP profusion of names, hence names must be chosen systematically. – Thus, class names begin with capital vi letters by convention. – method and variable names begin with ee lowercase letters by convention. • If the name involves more than one word, n mixed-capitalization is used to indicate the beginning of the word for a method, and w. underscore for a variable. E.g. – myMethod – my_variable ww • Constants are in all capitals: e.g. PI • Provide ample documentation. CKR Java Notes 32
  • 306. Program 5 om public class FreeForm { public static void .c main ( DF String args [] ) aP { //required prototype for main method System . out vi . println ( ee “ Java is a ” + “free-form language!” n //strings must still be terminated //before end of line. w. //They must be concatenated using + // and not merely by whitespace. ) ww ; }} CKR Java Notes 33
  • 307. A program with three classes om • There can be more than one class within a file, and a program may appeal to any number of classes. .c Program 6 In file Point.java: DF public class Point { float x; float y; public void setXY (float x0, float y0) aP { x = x0; y = y0; } vi public float getX () { return x; ee } public float getY () { n return y; } w. } class Line ww { Point a = new Point(); Point b = new Point(); CKR Java Notes 34
  • 308. public float length () om { float temp1, temp2; temp1 = (a.getX()-b.getX()); temp1 *= temp1; temp2 = (a.getY()- b.getY()); .c temp2 *= temp2; return (float) Math.sqrt DF ((double)temp1+temp2); } } aP • In file PointLine.java: public class PointLine { public static void main (String args[]) vi { Line myLine = new Line(); myLine.a.setXY (0.0f, 0.0f); ee myLine.b.setXY (1.0f, 0.0f); System.out.println ( “length of myLine = ”+ n myLine.length() ); } w. } • After compiling both files, use the command java PointLIne ww • Output: Length of myLine = 1 CKR Java Notes 35
  • 309. Hello World Applet om • Java programs are commonly of two types – Applications .c – Applets • A piglet is to a pig as an applet is to an DF application. • Applications are stand-alone Java programs. aP • Applets are programs that require a browser to run. Applets are typically downloaded from the Internet and run in an applet window within a browser. vi • Since download times are uncertain, an applet is intended to be a relatively small program. ee • But there is no inherent limitation to the size of an applet, and they can be as complex as one n wants. w. • Applets get their parameters not from the command line but from the web page within which they run. ww CKR Java Notes 36
  • 310. Hello World Applet (contd.) om • Unlike applications, applets do not utilise a main method. Instead they use the following methods. .c – public void init(): Initializes the applet. Called only once. DF – public void start(): called when the browser is ready to run the applet. – public void stop(): called when the aP browser wishes to stop the applet, or the user leaves the web page, or the browser is iconified. vi – public void destroy(): called when the browser clears the applet out of memory. ee – public void paint (Graphics g): called whenever the browser needs to n redraw the applet. w. • Applets get their parameters using the String getParameter(String Param_name) method. ww CKR Java Notes 37
  • 311. Hello World Applet (contd.) om • Step 1: Write the source code: For the HelloWorld Applet, create a java source file as follows. .c Program 7 import java.awt.*; DF public class HelloWorldApplet extends java.applet.Applet { public void paint (Graphics screen) aP { screen.drawString (“Hello World Applet!”, 50, 25); } vi } • Step 2: Compile the source file using javac. ee • Step 3: Create a minimal html file as follows. n <applet code = “HelloWorldApplet.class” height = 100 width = 300> </applet> w. • and save it as CallApp.html ww • Step 4: Viewing the applet in appletviewer: Run appletviewer by appletviewer CallApp.html CKR Java Notes 38
  • 312. HelloWorld Applet (contd.) om • Step 4: Preparing to viewing the applet in a browser: Wrap the above html code within any desired html code, e.g. .c <HTML> <HEAD> DF <TITLE>Hello World Applet</TITLE> </HEAD> <BODY> This is what my applet does: aP <applet code = “HelloWorldApplet.class” height = 100 width = 300> </applet> vi </BODY> </HTML> Save the code in a file: myfile.html ee • Step 5: Open the above html file using any java-enabled browser. n – E.g. use “Open page” on Netscape Navigator w. – the applet will automatically run in the assigned area. ww CKR Java Notes 39
  • 313. Anatomy of the HelloWorldApplet applet om • The first line in the HelloWorldApplet program is import java.awt.*; .c • The import statement is an instruction to the compiler to help resolve class names. DF – An import statement helps to refer to the classes in the java.awt package by their short names. aP – Thus to refer to the Graphics class, we now use the statement vi public void paint (Graphics screen) • Without the import statement, we would have to use the fully qualified name: ee public void paint ( java.awt.Graphics screen ) n • Similarly, if we used the statement import java.applet.Applet w. • the second line of the program could be abbreviated to public class HelloWorldApplet extends ww Applet i.e., we could refer to java.applet.Applet simply as Applet. CKR Java Notes 40
  • 314. Anatomy of the HelloWorldApplet applet (contd.) om • The HelloWorldApplet does not use the init(), start(), stop(), or destroy() methods. – It uses only the paint method. .c – The paint method takes a Graphics object as an argument. – The Graphics class is part of the DF Abstract Windows Toolkit (awt) package. • The declaration public void paint (Graphics screen) aP says that the Graphics object will be referred by the name screen within the paint method. – “screen” is only an identifier, and can be replaced by any other identifier, such as vi “g”. – Since the graphics class woks in the ee graphics mode (as in classic C), the preferred method is to draws strings rather than perform console output. n – The instruction w. screen.drawString (“Hello World Applet!”, 50, 25); – means that the string is to be drawn at ww pixels x=50, y=25, relative to the applet window, measured from the top left hand corner of the applet window. CKR Java Notes 41
  • 315. Anatomy of the HelloWorldApplet applet (contd.) om • As observed before, an applet cannot run on its own, and must run within a browser. – Hence the applet code must be .c supplemented with HTML code. • The minimum HTNL code that is needed for DF appletviewer is the following. <applet code = “HelloWorldApplet.class” height = 100 width = 300> </applet> aP • The HTML syntax is self-explanatory: it says that the applet with the given class file name should be displayed in a window of the given height and width in pixels. vi • The exact positioning of the window will be decided by the browser and any other HTML ee commands such as ALIGN. • if the applet class file is not in the same directory n as the web page, then use the syntax w. CODEBASE= URL • with the URL or path of the directory where the ww applet class file is located. CKR Java Notes 42
  • 316. Anatomy of the HelloWorldApplet (contd.) om • Unlike applications which take command line parameters, applets get their parameters using – The <PARAM,> tag in the HTML code .c – The getParameter method in the applet code. DF • The <PARAM> tag has the syntax <PARAM NAME="parameter-name" VALUE="parameter-value"> aP • The getParameter method has the prototype String getParameter(String parameter_name) vi • E.g. below shows how two parameters are obtained by the applet. (Note the capitalization.) ee Program 8 • Code in HTML file: n <applet code = GetParam.class height = 100 w. width = 100> <param name = Name value = “Myname”> <param name = class value = “myclass”> ww </applet> CKR Java Notes 43
  • 317. Code in file GetParameter.java om import java.awt.*; import java.applet.Applet; public class GetParam extends Applet { String s1, s2; .c public void init() { DF s1 = getParameter (“NAme”) s2 = getParameter (“class”); } aP public void paint(Graphics screen) { if (s1 != null) screen.drawString (s1, 50, 100); vi else screen.drawString (“No Name”, 50, 100); if (s2 != null) ee screen.drawString (s2, 50, 200); else screen.drawString (“No Class”, 50, 200); n } w. } ww CKR Java Notes 44
  • 318. General Applets om • The Hello World applet used only the paint method. .c • The Get Parameter applet used only the init and the paint methods. DF • The other methods of an applet are always called, and a default implementation is provided. • To see how they are called, we can use the aP following applet code. • The code also shows how applets may use the console, although they usually don’t for obvious vi reasons. • To see the output when the applet is running in a ee browser use the Java Console window of the browser. Program 9 n import java.awt.*; w. import java.applet.Applet; public class TestApplet extends Applet { ww static int countInit=0; static int countStart=0; static int countStop=0; CKR Java Notes 45
  • 319. static int countPaint=0; om static int countDestroy=0; public void init() { System.out.println (“Init = ” + .c (++countInit)); } DF public void start() { System.out.println (“Start = ” + aP (++countStart)); repaint(); } vi public void stop() { System.out.println (“Stop = ” + ee (++countStop)); repaint(); } n public void paint (Graphics screen) w. { System.out.println (“Paint = ” + (++countPaint)); ww /*repaint();//recursive call to paint*/ } CKR Java Notes 46
  • 320. public void destroy() om { System.out.println (“Destroy =” + (++countDestroy)); repaint(); } .c } DF aP vi n ee w. ww CKR Java Notes 47
  • 321. Summary om • There are two common types of Java programs. – Applications – Applets .c • Applications use the main method, applets don’t. DF • Applications are stand-alone, while applets run within a browser. • Applets are inherently graphical. (However, they aP can use console i/o). • From the point of view of the language, both applications and applets are the same.. vi • Applications can avoid graphics and use only console i/o, so they are faster, and more ee convenient in a development environment. • Hence, we will study the language using n primarily applications. w. ww CKR Java Notes 48
  • 322. How Java works om • Java is two things – Java Platform – Java language .c • Computer world today has many platforms – MicroSoft windows DF – Unix – Macintosh – OS/2 – NetWare aP • Software must be compiled separately for each platform. The binary files for an application that runs on one platform cannot run on another vi platform, since they are machine specific. • The Java Platform is a software platform that ee – sits on top of the other platforms – The Java compiler compiles source files (.java files) to bytecodes (.class files). n – these bytecodes are not specific to any machine. w. – they are instructions for the Java Virtual Machine. – Hence exactly the same file can run on ww any machine on which the Java Platform is present. CKR Java Notes 49
  • 323. The Java Platform om • Each underlying computer platform has its own implementation of the Java Virtual Machine. .c • But there is only one virtual machine specification. DF • Hence Java is able to provide the “Write Once, Run Anywhere” capability. – This capability is very important today, aP because of the diverse machines connected to the Internet. (E.g. Adobe PDF format documents.) vi – It is also important because of the high costs of software development makes it desirable to reuse code as easily as ee possible. • The Java Platform consists of n – The Java Virtual Machine, and w. – The java API (Application programmer interface/ class files). ww • The Java Base Platform consists of the JVM and a minimum set of API known as Base API. CKR Java Notes 50
  • 324. The Java Virtual Machine om • The Java Virtual machine is a ‘soft machine’ – a piece of software compiled for different platforms. .c • The JVM behaves like a real machine in that – it has an instruction set DF – it manipulates various memory areas at run time. – similar to the P-Code machine of UCSD Pascal (which was not such a success aP because “University people know nothing of marketing.”) • “The Java Virtual Machine knows nothing of the vi Java Language” (Tim Lindholm and Frank Yellin The Java Virtual Machine Specifications) ee • The Java Virtual Machine understands only a particular binary format known as the class file format. n • The class file format contains w. – JVM instructions or bytecodes – a symbol table and other ancillary info. ww • In principle, the JVM can run the instructions from any language which can be compiled into the class file format. CKR Java Notes 51
  • 325. The Java Virtual Machine (contd.) om • The Java Virtual Machine starts execution by – invoking the method main of some specified class .c – passing to it a single argument which is an array of strings. DF • This causes that class to be – loaded – linked to other types it uses, and – Initialised aP • The loading process is implemented by the class ClassLoader or its subclasses. – Different subclasses may implement vi different loading policies, e.g. pre-fetch based on expected usage, load a related group of classes etc. ee – This may not be transparent to the running application. E.g. a newly compiled version of a class is not loaded n because a previously compiled version is cached. w. – Responsibility of class loader to reflect errors only when they could have arisen without prefetching or group loading. ww CKR Java Notes 52
  • 326. The Java Virtual Machine (contd.) om • Linking is the process of taking the binary form of a class type or an interface type, and combining it into the run time state of the JVM so that it can .c be executed. – A class or interface is always loaded before it is linked. DF • Linking involves – verification – preparation, and aP – resolution of symbolic references • Depending upon implementation, symbolic references may be resolved vi – individually, when needed (lazy or late resolution) – collectively when the class is loaded ee (static resolution) • Verification ensures that the binary representation n of a class or interface is structurally correct. – E.g. that every instruction has a valid w. operation code. • Preparation ww – involves creating the static fields and intializing them to their default values. CKR Java Notes 53
  • 327. Java Virtual Machine: Limitation om • Despite all the hype, the Java Virtual machine has certain limitations. .c • The number of dimensions in an array is limited to 255.. DF • The number of method parameters is limited to 255 9with long and double counted as 2 parameters). aP • The number of fields in a class is limited to 64K (65535). (This does not include inherited fields.) • The number of methods in a class is limited to vi 64K. (Does not include inherited methods. ) • The amount of code per (non-native, ee non-abstract) method is limited to 64K bytes. • For more details: consult The JVM Specifications n by Lindholm and Yellin. w. ww CKR Java Notes 54
  • 328. Java Virtual Machine limitations (Example Program) om • The Java virtual Machine can also run out of memory. Here is an example. .c • The array size may have to be adjusted for different machines. DF Program 10 class BigArray { public static void main(String args[]) aP { double myArray[]; myArray = new double [256*256*256]; for (int i=0; i<=256*256*256; i++) vi { myArray[i] = (double)i; System.out.println (i+ “th element = ” + ee myArray[i]); } } n } w. • Expected output: Java.lang.OutOfMemoryError at BigArray.main(BigArray.java:6) ww CKR Java Notes 55
  • 329. The Java API om • The Java API provide a standard interface of ready made code that a programmer can rely upon, irrespective of the platform. .c • The Base API provide the language (java.lang), utility (java.util), i/o (java.io), network (java.net), DF gui (java.awt), and applet (java.applet) services. • The Standard Extension API provide various other services. aP • Naturally, the classification will change with time. vi n ee w. ww Fig. 2: The Java Platform is the same for all systems CKR Java Notes 56
  • 330. The Java Environment om • The Java development environment includes both Java compile time and run-time environment. .c • The developers source code (.java files) are converted to bytecodes (.class files). • In the case of applets the bytecodes are DF downloaded. • Once in the JVM, these are interpreted by the Interpreter or optionally turned into machine code by a Just in Time (JIT) code generator, aP popularly called a JIT compiler. • The Java Runtime Environment is provided separately, for those who merely wish to run Java applicatoins, but do not wishh to compile vi them. n ee w. ww Fig. 3: The Java Compile and Runtime Environment CKR Java Notes 57
  • 331. Identifiers and Unicode om • A legal identifier in Java is a finite sequence of characters. .c • Java programs (v. 1.1.7 upwards) may use Unicode character encoding (v. 2.1) as specified in DF • The Unicode Standard Version 2.0 ISBN 0-201-48345-9 aP • Unicode only for identifiers, and the contents of characters and string literals, and comments. • Everything else must be in ASCII. vi • The unicode character set uses 16 bit encoding, to try to represent characters from various ee languages (currently some 24 languages). – Of the 65536 possible characters, 49194 n have been assigned. w. – The first 256 of these are the standard ASCII character set. ww – Supports Japanese, Greek, Russian, Hebrew etc. CKR Java Notes 58
  • 332. Indian scripts supported include: om – Devnagari – Bengali – Gujarati – Gurmukhi – Malayalam .c – Tamil – Oriya DF – Telegu – Kannada • A unicode character may be represented within a aP string by uhhhh, where h are the hex digits. – E.g. “u0043" is the ASCII character C. vi – For more information on Unicode consult http://www.unicode.org n ee w. ww CKR Java Notes 59
  • 333. Data types om • Three kinds of datatypes in Java. – primitive data types .c – reference data types – the special null data type, also the type DF of the expression null. • The null reference is the only possible value of an expression of null type, and can always be aP converted to any reference type. – In practice, the null type can be ignored, and one can pretend that null is just a vi special kind of literal. – i.e. if(obj != null) always makes sense. ee • Java datatypes are NOT machine-dependent. n • The Java datatypes are defined as part of the language, as follows. w. • Apart from the primitive data types, (and the null data type) everything else is an object or a ww reference datatype in Java. CKR Java Notes 60
  • 334. Datatypes (contd.) om • The primitive data types are – numeric data types – Non-numeric data types .c • The non-numeric data types are DF – boolean (true or false) – char . (16 bit unicode) • The numeric data types are further divided into aP – integer numeric types, and – real numeric types. • The integer numeric types are as follows. vi – byte 8 bit 2c – short 16 bit 2c ee – int 32 bit 2c – long 64 bit. 2c n • Note: There is NO unsigned integer type in Java. w. • 2c representation means that there is wrap around without any notification of error. This feature is similar to C and C++. ww CKR Java Notes 61
  • 335. A class which adds two integers om Program 11 /** This program demonstrates how Java .c * adds two integers. */ public class BigInt { DF public static void main(String args[]) { int a = 2000000000; //(9 zeros) int b = 2000000000; aP System.out.println ( “This is how Java adds integers”); System.out.println ( a + “+” + b + “ = ” + (a+b) ); vi } } ee • Output: This is how Java adds integers n 2000000000 + 2000000000 = -294967296 w. • Q. Explain why this happens. What, if any, is the remedy to this problem? ww • This explains the difference between portable and architecture neutral. CKR Java Notes 62
  • 336. Portable and architecture neutral revisited om • We observed earlier Gosling’s claim that C/C+ are portable, but NOT architecture neutral. .c • The above code provides an example. • In C/C++, an int is defined as two bytes, but the DF actual size in bits is implementation and architecture dependent. • Though one can use bitsperbyte to ensure aP architecture neutrality, this is rarely done. • Thus, the following C/C+= program will give different results on different systems. vi #include <stdio.h> main() ee { int a = 20000; int b = 20000; n int c; c = a+b; w. printf (“%d + %d = %d”", a, b, c); } • Output: 20000+20000 = 40000 ww (eg on Sun SPARC) 20000+20000 = -25536 (on x86) CKR Java Notes 63
  • 337. Primitive Datatypes (contd) om • The real data types are – float 32 bit (23+8+1) – double 64 bit (52+11+1) .c – roughly as per IEEE floating point 754 standard of 1985. DF • The key differences from IEEE 754 are – In the handling of Nan aP – In the handling of division by zero. – INF is denoted by Infinity. • The range of representable numbers is restricted vi by both mantissa and exponent. – The size of the exponent decides the smallest and largest numbers that can ee be represented. – the size of the mantissa decides the precision or accuracy. n • Note that use of floating point numbers means w. the failure of the usual laws of arithmetic, such as – associative law ww – distributive law CKR Java Notes 64
  • 338. Significant figures and failure of associative law om Program 12 public class Significant { .c public static void main (String args[]) { final float PI = 3.141519265359f; DF float radius = 1.0f; float area; area = PI * radius * radius; System.out.println (“The area of the aP circle = ” + area); } } • Output: area of the circle = 3.1415193 vi Program 13 class AssocLaw ee { public static void main(String args[]) { n float epsilon = (float)1.0E-7; float a1, a2; w. a1 = (epsilon + 1) -1; a2 = epsilon + (1-1); System.out.println (“The difference is = ” ww + (a1-a2)); } } • Output: difference = 1.9209288E-8 CKR Java Notes 65
  • 339. Difference from IEEE floating point representation om Program 14 public class NumberTest { .c public static void main(String args[]) { int a = 0, b=0; DF float fa = 0, fb = 0; try { System.out.print (“(int) 0/0 = ” ); aP System.out.println (“ ”+ a/b); } catch (ArithmeticException e) { vi System.out.println (“Caught Arithmetic" +"Exception”); } ee System.out.println (“(float) 0/0 = ” + fa/fb); fa = (float) 1.0; n System.out.println (“(float) 1/0 = ” + fa/fb); w. fa = (float) 1E+39; System.out.println (“(float) 1E39 = ” + fa); ww fb = (float) 2E+39; System.out.println (“(float) 1E39/2E39 = ” + fa/fb); CKR Java Notes 66
  • 340. fb = 0.0f; om System.out.println (“(float) 1E39 * 0 =” + fa * fb); double lfa = 1E+39; double lfb = 2E+39; System.out.println (“(double) 1E39/2E39 = .c ” + lfa/lfb); DF } } • Output: aP (int) 0/0 = Caught Arithmetic Exception (float) 0/0 = NaN (float) 1/0 = Infinity (float) 1E39 = Infinity vi (float) 1E39/2E39 = Nan (float) 1E39*0 = NaN (double) 1E39/2E39 = 0.5 n ee w. ww CKR Java Notes 67
  • 341. Features added by Java om • Relational operators: • New use of the arithmetic operator % .c – The % operator now applies also to floating point data types. DF – for real a, b, a%b returns the remainder or the floating point value, a-nb, where n is an int. aP • These follow the same conventions as in C/C++. – Namely: For integers a, b, and integer vi division a/b, the quotient is always rounded towards zero. Hence, ee – a%b always has the same sign as a (to preserve the relation between dividend, divisor, quotient and remainder) . That is, n if w. dividend = a divisor = d quotient = q remainder = r, then ww a = qd + r CKR Java Notes 68
  • 342. Features added by Java (contd.) om Program 15 class RemainderTest { .c public static void main(String args[]) { float a=3.2f, b=4.3f, c; DF c = b%a; System.out.println (“b%a = ” + c); b = -4.3f; c=b%a; aP System.out.println (“-b%a = ” + c); } } vi • Output: b%a = 1.1000001 -b%a = -1.1000001 ee • New operator >>>: – To compensate for the absence of the n unsigned type, w. – and to permit better bit level manipulation for graphics. ww – Java has an unsigned right shift. >>> CKR Java Notes 69
  • 343. Features added by Java (contd.) om Program 16 class RightShift { .c public static void main (String args[]) { System.out.println (“-1>>4 = ” + (-1>>4)); DF System.out.println (“-1>>>25 = ” + (-1>>>25)); char ch = 0x43; System.out.println (“ ”+ch); aP //char is promoted to int after call to //right shift System.out.println (“ch>>> 1 = ” + (ch >>> 1)); vi } } ee • Output: -1 >> 4 = -1 -1>>>25 = 127 C n ch >>>1 = 5 w. ww CKR Java Notes 70
  • 344. Labeled loops and multi-level breaks om • The goto statement was strongly opposed by proponents of structured programming. – imagine jumping into the middle of a for .c loop. • However, a classic study of thousands of lines of DF computer code showed that 90% of the time, the goto was used to jump completely out of deeply nested loops. aP • This suggested that the anti-goto lobby had gone too far. C offers no other mechanism for jumping out of deeply nested loops. vi • the solution offered by Java is to eliminate goto, but allow jumping out of deeply nested loops through the use of ee – labeled breaks, and – labeled continue statements. n • We recall that – break can be used only inside a for, w. while, do-while, or switch statement. – continue can be used only inside a for, while, do-while statement block. ww – continue distinguishes between for and while loops. CKR Java Notes 71
  • 345. Labeled loops and Multi-Level Break om • Accordingly Java provides an elegant solution to the goto problem – by restricting jump statements to loops, .c – using multi-level break and continue. • A loop can be labeled, and the break and DF continue statements can be followed by the label to permit execution to jump out of the loop. Program 17 aP public class MultiLevelBreak { public static void main(String args[]) { vi Identifier1: for (int k=0;k<=2; k++) { System.out.println (“In top for loop”); ee Identifier2: for (int i=0; i<=20; i++) { System.out.println (“In next for loop”); n for (int j=0; j<=30; j++) { w. if (j==2) break Identifier2; if (i==2) continue Identifier1; System.out.println (“In bottom for loop”); ww } } }}} CKR Java Notes 72
  • 346. Pass by value om • Java passes by value means – value of primitive types and reference value of reference types (objects, arrays .c etc.) are passed by value. • Therefore, DF – A method cannot change the value of a primitive type. – A method cannot change an object aP reference which is its argument. • However, – a method CAN change the accessible vi variables within an object by invoking the objects methods or otherwise. ee • This is demonstrated by the following program. Step 1: Define an object n In file: Ncomplex.java w. public class Ncomplex { ww public float real; public float im; public Ncomplex (float real1, float im1) CKR Java Notes 73
  • 347. { om real = real1; im = im1; } } .c Step 2: Define methods which modify arguments, and DF the instance variables of the arguments. In file: PrimObj.java aP public class PrimObj { vi public void passPrimitive (float real1, float im1, Ncomplex c) { ee real1 = c.real; im1 = c.im; } n public void passObject1 (float real1, float im1, Ncomplex c) w. { c.real = real1; c.im = im1; ww } CKR Java Notes 74
  • 348. public void passObject2 (Ncomplex c) om { Ncomplex c1; /*get object reference. Exactly like declaring a pointer to c1*/ c1 = new Ncomplex(1.0f, 2.0f); /*Initialise the reference declared .c earlier */ c = c1; DF } } Step 3: Define a main method which calls the relevant aP method, using the object and primitive data types. In file: PassRefTest.java vi public class PassRefTest { public static void main (String args[]) ee { PrimObj my_PrimObj = new PrimObj (); Ncomplex c1 = new Ncomplex (1.0f, 0.0f); n Ncomplex c2 = new Ncomplex (0.0f, 1.0f); float real1 = 0.0f; w. float im1 = 0.0f; /*1: pass primitive and try to change it*/ my_PrimObj.passPrimitive (real1, im1, c1); ww System.out.println (“c1.real = ” + c1.real); System.out.println (“real1 = ” + real1); CKR Java Notes 75
  • 349. om /*2: pass reference and try to change its accessible members*/ System.out.println (“Before: c1.real =” + c1.real); my_PrimObj.passObject1 (real1, im1, c1); .c System.out.println (“After: c1.real = ” + c1.real); DF /*3: pass reference and try to change reference*/ System.out.println (“Before: c2.real = ” + aP c2.real); my_PrimObj.passObject2 (c2); System.out.println (“After: c2.real = ” + vi c2.real); } ee } • Output: c1.real = 1.0 n real1 = 1.0 Before: c1.real = 1.0 w. After: c1.real = 0.0 Before c2.real = 0.0 After c2.real = 0.0 ww c2.real = 0.0 c2.im -= 1.0 CKR Java Notes 76
  • 350. Features removed by Java from C++ om • Simplicity: “You know when you have achieved perfection .c in design, Not When you have nothing more to add, But when you have nothing more to take away.” DF – Antoinne de Saint Exupery as quoted in the Java Language Environment White Paper. aP • No more – Preprocessor directives – # define vi • Keywords removed: No more – typedef ee – enum – structure – union n since they are all subsumed under the notion of class. w. • No more storage class modifiers – auto (default, use static when needed) – extern (no global variables) ww – register (register access not permitted) – • Control statements: No more goto CKR Java Notes 77
  • 351. No more automatic coercions. om • Functions: No more – default arguments – inline functions .c • Operators DF – No more operator overloading. • No more pointers? aP – No more uninitialised pointers. – (References can always be used.) • Inheritance vi – No more multiple inheritance. Imagine DDD syndrome with dynamic class binding. ee DDD = Dreaded Diamond of Derivation Since, in a distributed environment, user may not know the entire family tree of the class, and class n designer may not know all possible end-uses of a class. w. – No more: virtual keyword. – use final in place of const – Unlike C++, final class members may ww and must be initialised where declared. final int a=2; – CKR Java Notes 78
  • 352. Classes om • Classes in Java are similar to classes in C++. But the following salient differences exist. .c • The class definition does NOT close with a semicolon. – Since Java is completely object oriented, DF there is nothing outside of classes, not even a semicolon! • The class itself can have access specifiers aP – public – (no specifier) default • A public class is visible to all other classes. vi – There cannot be more than one public class within a file. ee – The file must have the same name as the name of the public class. n • A default class is visible only to members of its own package w. – (More on packages shortly) ww CKR Java Notes 79
  • 353. Class members om • Class members: named variables or reference types are called fields. .c – static fields are called class variables – non static fields are called instance DF variables. • Class members can also have the following types of access specifiers aP – public – private – protected – (no specifier) default vi • Note: private protected no longer supported. This is not updated in the book by ee Balagurusamy. • Unlike C++, n – default access is NOT private w. – There is no colon after the access specifier ww – Access specifiers must be repeated on each line, else default access is assumed. CKR Java Notes 80
  • 354. – Thus, om public int a; int b; – means that b has default access. • Members with default access CAN be accessed .c by other classes in the same package. DF • The term protected plays a similar role as it does in C++ – protected members are like default members, in that they cannot be aP accessed from outside the package. – However, protected members are unlike default members in that they can be vi inherited, also by subclasses in other packages. n ee w. ww CKR Java Notes 81
  • 355. Classes: Constructors om • Classes have constructors, as in C++. – If no constructor is specified, then the system provides a default constructor. .c – if any constructor is specified, no default constructor is provided. DF – The superclass constructor is always called as the first line in a constructor. If not explicitly called, then the superclass aP constructor with no arguments super() is automatically called, and this may result in a compile time error. vi • Unlike C++ an appropriate constructor is NOT automatically called when an object is declared. ee • Memory allocation for objects is not done automatically: the constructor must be explicitly called. n – Thus, if My_Class is a class MyClass mc; w. – only declares an object reference. – To obtain the object, memory must be explicitly allocated, using e.g. the default ww constructor mc = new MyClass() CKR Java Notes 82
  • 356. Classes: Memory Deallocation om • However, unlike C++, in Java classes do NOT have destructors. – Memory deallocation is done .c automatically. • Java does automatic garbage collection to claim DF back memory of objects not required any more. – Garbage collection is done on a low priority basis. (More on threads later.) aP – Garbage collection strategies are implementation dependent. vi • Garbage collection can be explicitly initiated by hand by calling the method gc() of the Runtime class. The gc() method has the signature ee void gc() n • Note: Remote applets canNOT access the Runtime class without risking a security w. exception. – Untrusted applets will raise a security exception. ww – hence untrusted applets cannot initiate garbage collection on demand. CKR Java Notes 83
  • 357. Memory Deallocation: finalize() method om • There is also a finalize method which has the signature .c protected void finalize() • The finalize method is normally called just before garbage collection is initiated. DF • However, whereas C++ destructors are called deterministically whenever an object goes out of scope, the finalize method is not. aP – Specifically, the finalize method may or may not be called even if garbage collection is manually initiated. vi • Since Applets cannot usually initiate garbage collection, on demand, it is even more uncertain when finalize will be called in Applets. ee • Hence the finalize method should make NO assumptions about what objects exist and what n do not. w. • Better procedure is to define a method, say cleanup, which is explicitly called just before the object goes out of scope. ww • These ideas are illustrated by the following program. CKR Java Notes 84
  • 358. Program 18 om class MyClass { float myfloat []; MyClass()//define constructor { .c myfloat = new float [2000]; System.out.println (“Constructor called”); DF } protected void finalize () { System.out.println (“Finalize called”); aP } } public class Finalize { vi public static void main (String args[]) { Runtime r = Runtime.getRuntime(); ee //Runtime class cannot be instantiated //however we can get a reference to it. n long tmem, bmem, amem; tmem = r.totalMemory(); //returns long w. bmem = r.freeMemory(); System.out.println (“Total Memory: ” + ww tmem); System.out.println (“Free Memory Before: ” + bmem); CKR Java Notes 85
  • 359. if (true) om { //instantiate MyClass and invoke its //constructor MyClass myclass = new MyClass(); .c //again check free memory amem = r.freeMemory(); DF System.out.println (“Free Memory After” +"allocation: “ + amem); } aP //myclass goes out of scope; r.gc(); //initiate garbage collection amem = r.freeMemory(); System.out.println (“Free Memory After” vi + “garbage collection: ” + amem); } } ee • Sample output: Total Memory = 1048568 n Free Memory Before: 927824 Constructor called w. Free Memory After allocation: 918608 Free Memory After garbage collection: 923208 Application Exit... ww • Note: Finalize method was NOT called in the above run. CKR Java Notes 86
  • 360. Inheritance and Polymorphism om • Theoretically, Java permits only multi-level inheritance. – That is, a given class can have exactly .c one superclass. • Officially Java does not permit multiple DF inheritance. But multiple inheritance creeps in through – interfaces (officially), and – inner classes (more on this later.). aP • Unlike C++ – No colon “:” is used to indicate the base class. Instead one uses the keyword vi extends. For example, public class MyApplet extends Applet ee • The base class of C++ is called superclass in Java. n – There is no scope resolution operator, but one can refer to the superclass w. members using the keyword super. – This is the counterpart of the this ww pointer available in any non-static method. CKR Java Notes 87
  • 361. Polymorphism: method overloading and overriding om • Overloading works exactly as in C++. • Overloading means that two methods .c – have the same name, but – have different parameter lists – so that they have different signatures. DF – (Note: signature differences due to differences in return type alone are not permitted: the parameter lists must be different. ) aP • Overriding means that two methods – have the same name, and – have the same parameter lists vi – so that they have the same signature, – but one method is defined in a super class, ee – and the second method is defined in a derived class. n • Overriding works exactly as in C++. This corresponds to dynamic polymorphism. w. – the right version of the method is called at run time. ww • However, instead of pointers, one uses object references. CKR Java Notes 88
  • 362. Program 19 om import java.io.*; class Animal { void sleep () { .c System.out.println (“Animalzzz..”); } DF void sleep (int t) //overload sleep method { System.out.println (“Animalzzz... for” + t + “ seconds”); aP } } class Dog extends Animal vi { void sleep () //override sleep method { ee System.out.println (“Dogzzz...”); } n void sleep (int t) //override second sleep method w. { System.out.println (“Dogzzz... for ” + t + “ seconds”); ww } } CKR Java Notes 89
  • 363. class Mongrel extends Dog om { void sleep () //override sleep method { System.out.println (“Mongrelzzz...”); } .c void sleep (int t) DF //override second sleep method { System.out.println (“Mongrelzzz... for ” + t + “ seconds”); aP } } public class Polymorph vi { public static void main (String args[]) throws IOException ee { //obtain a reference to Animal Animal my_Animal; n //initialise to Animal object w. my_Animal = new Animal(); int trun; DataInputStream in = new ww DataInputStream(System.in); System.out.println (“n Enter an integer”); CKR Java Notes 90
  • 364. String inString = in.readLine(); om trun = Integer.parseInt (inString); switch (trun) { case 1: .c //re-initialize the reference to an //appropriate object DF my_Animal = new Dog(); break; case 2: aP my_Animal = new Mongrel(); break; default: vi break; } ee //just code the following two lines my_Animal.sleep(); my_Animal.sleep(2); n //the right version of sleep is called. } w. } • Ouptut: The right version of sleep is called. E.g. input trun = 1, output: ww Dogzzz... Dogzzz... for 2 seconds CKR Java Notes 91
  • 365. Overriding (contd): abstract and final classes om • Since there is no virtual keyword in Java, there are no pure virtual functions. .c • However, a method which has no implementation is called an abstract method, and may be ddeclared as such, using the abstract DF keyword. abstract ret_type method_name (args); • A class containing an abstract method is not only known as an abstract class, it must be aP declared as such. • Though an abstract class cannot be instantiated, a reference to it can be created. vi – This is essential to permit dynamic polymorphism. • In the preceding example, if one or both of the ee sleep methods in the Animal class is declared abstract, then the class cannot be instantiated, so its constructor cannot be called. n – However, the rest of the program will work similarly. w. • On the other hand, to prevent a method from being overridden one can declare the method (or ww class) to be final, using the final keyword. – A final class cannot be subclassed. CKR Java Notes 92
  • 366. Packages and C++ namespaces om • Since Java, like C++, permits both – method overloading, and – method overriding .c An unintended name collision can lead to unexpected program behaviour. DF • Such unintended name collision may arise, for example when using two libraries sourced from two different third-parties. aP • A similar problem was encountered in C++, where the programmers had three choices: – discard one of the libraries – get the source code for one of the vi libraries and change the name – persuade the owner of the library to recompile the library after changing the ee name of the concerned function. • Very often, none of these choices was feasible. n • Hence it is desirable to have a mechanism to w. limit the scope of names. • This is achieved in C++ through the use of ww namespaces. • Java uses packages. CKR Java Notes 93
  • 367. Packages (contd) om • A package is created by the statement package pkg; .c • A package statement always has file scope, so that – a package statement, if used, must be DF the first statement in a file. – If no package statement is used, a default package is automatically aP provided. • The use of a package limits the scope of names, so that the fully qualified name of a variable or vi method is its name preceded by the package name. pkg.my_variable ee – Note that Java uses a dot, since there is no scope resolution operator. n • The fully qualified name may be abbreviated within the file by an import statement w. import pkg.*; //imports all classes in pkg – The Java import statement is the ww counterpart of the C++ using statement. CKR Java Notes 94
  • 368. Packages: Java source file structure om • Thus, a java source file can have any or all of the following four internal parts. .c • (1) A single package statement (optional) – this must be the first non-comment statement of the program DF • (2) Any number of import statements (optional) • (3) A single public class declaration (necessary) aP • (4) Any number of class declarations (optional) – subject to the overall limitations of the JVM. vi • If multiple import statements lead to a name collision, this will be flagged as an error. ee • That is, if package pkg1 has a class called MyClass, and package pkg2 also has a class n called MyClass, and if one invokes MyClass, without specifying the package name, this will be w. flagged as an error. ww CKR Java Notes 95
  • 369. Packages: hierarchies and CLASSPATH om • Like namespaces, packages may be nested into a hierarchy. .c package pkg1.pkg2.pkg3 • For the benefit of the JVM Class Loader, DF – public class names must match file names, and – A package hierarchy must match the aP directory structure. • CLASSPATH environment variable must be set to the root of this directory tree. vi – Preferably use -classpath option, instead of setting the CLASSPATH variable globally. ee • In the following example, there are two packages – pkg1 in e:javakawapkg1 directory – pkg2 in e:javakawapkg2 directory n • set CLASSPATH to include e:javakawa w. – (Java 1.1) set CLASSPATH=.;e:javalibCLASSES.ZIP;e:java ww kawa – java 1.2 set CLASSPATH=.;e:jdk1.2;e:javakawa CKR Java Notes 96
  • 370. Package and access: example om Program 20 • Source in file e:javakawapkg1Base.java .c package pkg1; public class Base DF { public int pub; //public access protected int prot; //protected int def;//default access aP //inconsistent declaration //private protected int priprot; //illegal private int priv; vi } class Derived extends Base ee { int deriv; void showPriv () n { //error: private variables are not w. //inherited //System.out.println (“b.priv = ” + priv); } ww } CKR Java Notes 97
  • 371. Source in file e:javakawapkg1InheritTest.java om package pkg1; import pkg2.*; public class InheritTest { .c public static void main (String args[]) { DF Base b = new Base(); Derived d = new Derived(); System.out.println (“b.pub = ” + b.pub); System.out.println (“d.pub = ” + d.pub); aP System.out.println (“b.prot = ” + b.prot); System.out.println (“d.prot = ” + d.prot); System.out.println (“b.def = ” + b.def); System.out.println (“d.def = ” + d.def); vi //error: private variable not accessible //System.out.println (“b.priv = ” + //b.priv); ee //Now declare object from another package n Other o = new Other(); System.out.println (“o.pub = ” + o.pub); w. System.out.println (“o.prot = ” + o.prot); //def variable may be accessed thus. System.out.println (“o.def = ” + o.def); ww // o.showDef ();//error showDef not //accessible here o.showProt();}} CKR Java Notes 98
  • 372. Source in e:javakawapkg2Other.java om package pkg2; import pkg1.*; public class Other extends Base { .c int other; void showDef () DF { //error variable def not accessible here //System.out.println (“o.def = ” + def); //protected variable from other package aP //can be accessed here. public void showProt () { System.out.println (“o.prot = ” + prot); } vi } } • Output: ee b.pub = 0 d.pub = 0 n b.prot = 0 d.prot = 0 w. b.def = 0 d.def = 0 o.pub = 0 ww o.prot =0 o.def = 0 o.prot = 0 CKR Java Notes 99
  • 373. Access rules for class members om Private Default Protected Public Same class Y Y Y Y Same package: .c N Y Y Y subclass Same package: N Y Y Y DF nonsubclass Different package: N N Y Y subclass aP Different package N N N Y non-subclass vi n ee w. ww CKR Java Notes 100
  • 374. JAR files om • JAR files are Java archive files. • Exactly like zip files, except that the terminology and usage relates to Unix, where .c – tape archive files are called tar files. – Moreover, compressed JAR files are acceptable to the JVM. DF • Bundling and Compression: The advantage of zip files is that the directory structure can be recursed and stored in the zip file. • Portability: This makes JAR files particularly aP suitable for storing and transferring large packages. – E.g. on Mac more than 32 characters were not accepted as Dir names vi • Thus, the previous example can also be run by first archiving and calling the jar tool from E:javakawa directory (Java 1.1) ee jar -cvf0 Inherit.jar pkg1 c= create new, v=verbose, f=filename 0= no n compression. • Since the argument is a directory, it is w. automatically recursed. • One now adds Inherit.jar to the classpath, and invokes java InheritTest, and the classloader will ww locate the InheritTest class. • Security: Jar files can be signed, thus providing a layer of security. CKR Java Notes 101
  • 375. Interfaces om • Java’s first route to multiple inheritance is provided through interfaces. .c • Usually, in multiple inheritance one is interested only in the methods, and not in duplicate inheritance of data members. DF • An interface contains only – constants (i.e., final data members), and – method declarations aP – Like a class the interface itself can have default or public access. vi access_type interface i_name { return_type method1(param_lst); ee return_type method2 (param_lst); type final var_name1 = value; ... n } w. • However, all methods and constants in an interface are implicitly public. ww • A class implements an interface. – i.e., the class defines the methods declared in the interface. CKR Java Notes 102
  • 376. all interface methods must be declared om public in the class implementation. • A class may implement more than one interface, by providing a comma separated list of interfaces. .c access class class_name [extends DF superclass_name] implements interface_name1, interface_name 2 {... ] aP • If a class which implements an interface, does not implement all the methods of that interface, then the class must be declared as abstract. vi • Any subclass must either implement all the methods or be itself declared as abstract. ee • Interfaces thus provide a form of multiple inheritance, in which a class may inherit n methods from a variety of sources. w. ww CKR Java Notes 103
  • 377. Dynamic polymorphism, extending interfaces and om adapter classes – An object reference may be declared to be of interface type. .c – This reference may be assigned at run time to any one of various classes which DF implements the interface. – The implemented methods of that class will be called. aP • Inheritance of interfaces: – One interface can extend another interface. vi interface mine extends yours { ee //new methods ] • A class which now implements interface mine n must implement all the methods in yours and mine. w. • However, there are Adapter classes which enable one to implement only part of an interface. ww CKR Java Notes 104
  • 378. om Program 21 interface Area { final float pi = 3.14f; float area (float diameter); .c } DF class Circle implements Area { public float area (float diameter) { aP return pi*diameter; } } vi class Square implements Area { public float area (float diameter) ee { return diameter*diameter; } n } w. ww CKR Java Notes 105
  • 379. om public class Interf { public static void main (String args[]) { Area a; .c a = new Circle(); System.out.println (“Area of circle = ” + DF a.area (2.0f)); a = new Square(); System.out.println (“Area of square= ”+ a.area (2.0f)); aP } } • Output: vi Area of circle = 6.38 Area of square = 4 n ee w. ww CKR Java Notes 106
  • 380. Inner classes and multiple inheritance in Java om • Interfaces provide one route to multiple inheritance. .c • Inner classes provide another route. • This second route is not documented, and sun DF documentation speaks of adapter classes. • However, while inner classes may be used in that context, adapter classes are irrelevant to the aP basic syntax of inner classes. • One class may be defined within another. vi • Such a class is called a nested class. • A static nested class behaves like a top-level ee class (i.e., a class which is not contained in any class) n • A non-static nested class is called an inner class. w. • Such nested classes may be defined within any expression. ww CKR Java Notes 107
  • 381. Nested and inner classes (contd) om • Nested classes have access to all of the variables of the enclosing class. .c • However, the enclosing class must access the nested class variables through an object reference. DF • The key point is that the nested class can inherit independently of the inheritance hierarchy of the enclosing class. aP • Thus, inner classes permit multiple inheritance in practice. vi • This is illustrated by the following example. • Note: Java rejects multiple inheritance in ee principle, since it permits one class to have only one superclass. – Inner classes do NOT negate this rule in n principle. – However, through inner classes, one can w. effectively subvert this principle in practice. ww CKR Java Notes 108
  • 382. om Program 22 • In file: e:javakawapkg2Base2.java package pkg2; public class Base2 .c { int base2; DF protected void base2Method() { System.out.println (“In Base 2"); } aP } • In file: e:javakawapkg1MultipleInherit.java package pkg1; vi class Base1 { int base1; ee void base1Method() { System.out.println (“In Base 1"); n } } w. class Derived extends Base1 ww { int derivInt=2; CKR Java Notes 109
  • 383. class Inner extends pkg2.Base2 om { void showInner() { base1Method(); base2Method(); .c //access protected method from other //package DF System.out.println (”Though I abused"+ “multiple inheritance, I still use it”); } }//end of class Inner aP void deriv() { Inner i = new Inner(); i.showInner(); vi }} public class MultipleInherit { public static void main(String args[]) ee { Derived d = new Derived(); d.deriv(); n //Inner i = new Inner(); //illegal //i.showInner(); w. }} • Output: In Base 1 ww In Base 2 Though I abused multiple inheritance, I still use it. CKR Java Notes 110
  • 384. Exceptions om • An exception is an unusual condition in a program. – Example: an illegal mathematical .c operation is an exception. – Eg. integer division by zero will lead to DF an exception and to immediate program termination. Program 23 public class DivideByZero aP { public static void main (String args[]) { int a=1; vi int b=0; System.out.println (“a/b = ” + a/b); } ee } • output: n java.lang.ArithmeticException: / by zero w. at DivideByZero.main(DivideByZero.java:7) Application Exit ww CKR Java Notes 111
  • 385. Though the stack trace provided by Java is om helpful to the programmer for debugging, such abrupt termination is likely to leave the user confused. • Exceptions allow the programmer to handle such .c situations smoothly.. DF • The classical C approach to exception handling involves two routes. – signal and raise – setjmp and longjmp aP • In the signal method, an exceptional condition, such as division by zero, is indicated by means of a signal SIGFPE, defined in signal.h vi • (Alternatively, a user may raise a signal through raise.). ee • When a signal is raised, a signal handler (a function) is called. n • A default signal handler is provided, and the user w. may override it by registering an alternative signal handler (pointer to a function). • A default math error handler is provided, and the ww user may override it by redefining the function matherr. CKR Java Notes 112
  • 386. These considerations are illustrated by the om following C program (which works also in C++) Program 24 #include <stdlib.h> #include <stdio.h> #include <math.h> .c #include <signal.h> DF /*==trap floating point errors === */ void float_trap(int sig) { fixerr(); /*do some deallocation*/ printf(“n Encountered a floating point”, aP “error.”); printf(“n Check whether the last input:, ”was mathematically well-posed."); return; vi } /*==signal handler for floating point errors====*/ ee void siginst(void)r { if (signal(SIGFPE, float_trap) == SIG_ERR) n { printf(“Error installing signal” “handler.n”); w. exit(3); } } ww /*=user defined handler for math errors =*/ int matherr (struct exception *a) { CKR Java Notes 113
  • 387. /*This user-modifiable function is called om automatically when a mathematical error is encountered. struct exception is defined in math.h*/ char *s1; fixerr(); .c printf (“n Encountered a mathematical error,”); DF printf (“n related to the function:%s.”, a->name); switch (a->type) { aP case DOMAIN: s1 = “The argument was” “outside the domain of the function.”; break; case SING: s1= “The argument was singular” vi “(i.e., on the domain boundary).”;break; case OVERFLOW: s1="The function value was" “too large.”; break; ee case UNDERFLOW: s1="The function value" “was too small.”; break; case TLOSS: n case PLOSS:s1="There was total or partial" “loss of significance.”; break; w. default: s1= “ ”; break; } printf (“n %snn”, s1); ww exit(1); return 1; } CKR Java Notes 114
  • 388. /*=============fixerr================*/ om fixerr(){ } /* ============main=============== */ main() { float a=1, b=0; .c float c; system(“cls”); DF siginst (); /*install signal handler*/ /*if (b==0) raise (SIGFPE);*/ /*The commented code above is an example aP of a user generated signal. Below the signal is raised by the system*/ c=a/b; c = log (-a); vi return; } • Output: ee Encountered a floating point error... Encountered a mathematical error related to the function log n The input was outside the domain of the function. w. ww CKR Java Notes 115
  • 389. Exceptions (contd) om • The other way to handle exceptions is through the functions setjmp and longjmp. .c • The state of the stack at a user-determined point in the program is saved through a call to setjmp. DF • If an error is subsequently encountered, the stack is unwound to the previously saved state, i.e., the program executes a goto to the previously saved state by calling longjmp. aP • This is illustrated by the following program. vi n ee w. ww CKR Java Notes 116
  • 390. Program 25 om #include <stdio.h> #include <setjmp.h> #include <signal.h> jmp_buf jumper; /*jmp_buf is a structure defined in .c setjmp.h*/ /*==trap floating point errors ==== */ DF void float_trap(int sig) { char *s = “nn Encountered a floating point error”; aP printf (“%s”, s); longjmp (jumper, 1); } /*===signal for floating point errors vi =========*/ void siginst(void) { ee if (signal(SIGFPE, float_trap) == SIG_ERR) { printf(“Error installing signal n handler.n”); exit(3); w. } } /* ==============main=============== */ ww main() { int value; CKR Java Notes 117
  • 391. float a=1, b=0; om float c; siginst (); /*install signal handler*/ value = setjmp(jumper); if (value != 0) { .c printf(“n Longjmp with value %dn”, value); DF goto next; } c=a/b; next: aP printf (“n Reached next”); return; } vi • Output: Error encountered Long jump with value 1 ee Reached next. • While this approach may be used in C++ it has n certain disadvantages. w. • The disadvantages of this older approach of handling exceptions, arise from certain new features introduced by C++, namely classes and ww objects. CKR Java Notes 118
  • 392. Exceptions (contd.) om • Consider the following sort of code involving longjmp void some_function () .c { FILE* fp = fopen (fname, “rw”); float *pf = DF (float *) malloc (1000*sizeof(float); /* do something */ if (error) aP longjmp (jumper, ErrorCode); /*do something else*/ fclose (fp); free (pf); vi } • if the program encounters an exception, and ee takes a long jump to the previously saved state. • Hence the file handle is not closed, and n subsequent attempts to access the same file would fail. w. – If a new file is opened each time, the system would soon run out of file handles. ww • The dynamically allocated memory would not be returned to the heap. CKR Java Notes 119
  • 393. Exceptions (contd) om • Thus, a longjmp creates a problem when there are interim resources at risk. .c • Since the longjmp has to be executed at the point where the error/exception is encountered, all resources must be freed. DF • However, unwinding the stack only frees automatic variables and function calls. aP • The manually allocated heap memory, and other resources must be freed manually. • This is difficult to perform in C++/Java, since vi references to objects also occupy the stack. • Unwinding the stack frees the references to ee these objects, but it does not free the heap memory occupied by the objects. n • For that to happen, the destructor functions must execute, and this would be bypassed when w. a longjmp takes place. • Hence, C++/Java needs an alternative method of ww exception handling. CKR Java Notes 120
  • 394. Exception handling: Java specific om • In Java exception handling is done through 5 keywords – throw .c – try – catch – throws DF – finally • When an exception is thrown, – not only is the stack unwound to a aP previously saved state, but – automatic objects are marked for finalization (destructors are exeecuted in C++) vi – if the exception is thrown from within a constructor, the finalizer of that object is not executed. ee – key resources may be manually freed through the use of a finally block which is guaranteed to execute, whether or not an n exception is thrown. w. • The code to be monitored is put into a a try block. • The action to be taken, when an exception is ww thrown is put into various catch blocks. CKR Java Notes 121
  • 395. Each catch block decides what action is to be om taken when a particular exception is thrown. try{//try block } catch (Exception_type1 arg) .c { //catch block } DF catch (Exceptiontype2 arg) { //catch block 2 } ... aP vi Object ee Throwable n Error Exception w. RunTimeException ww ArithmeticException CKR Java Notes 122
  • 396. Exceptions: try, throw, catch sequence om • The following code is an example of a basic try-throw-catch sequence. .c Program 26 public class CatchException { DF public static void main(String args[]) { int a = 1; int b = 0; aP try //start try block { System.out.println (“Trying...”); int c = a/b; //exception is thrown vi } catch (ArithmeticException e)//and caught { ee System.out.println (“Well caught”); } System.out.println (“Normal program exit”); n } } w. • Output: Trying... Well caught ww Normal program exit. CKR Java Notes 123
  • 397. Exceptions: multiple catch blocks om • Catch is not called: program execution is transferred to it. – if no exception occurs, then the catch .c block will NOT execute. • There may be more than one catch block. DF – Each catch block handles one type of exception . – But only that catch block will be aP executed which matches the type of the exception generated. • Thus, if we rewrite the previous program, so that vi – there are two catch blocks: ee – one which handles arithmetic exceptions. – and one which handles i/o exceptions, n – and if an integer is incorrectly entered, w. – then the exception will NOT be caught, and an abnormal program termination ww will occur . CKR Java Notes 124
  • 398. Program 27 om import java.io.*; public class MultipleCatch { public static void main(String args[]) { int a; .c int b; DF try { System.out.println (“a = ”); DataInputStream in = new aP DataInputStream(System.in); String inString = in.readLine(); a = Integer.parseInt (inString); System.out.println (“b = ”); vi b = Integer.parseInt (in.readLine()); int c = a/b; } ee catch(ArithmeticException e) { System.out.println (“Caught Arithmetic"+ n “exception”); } w. catch (IOException i) { System.out.println (“Caught i/o”+ “exception”); ww } System.out.println (“Program exit”); }} CKR Java Notes 125
  • 399. Case 1: input: om a=2 b=3 • output: Program exit .c • Case 2: Inputa=2 b=0 DF • Output: Caught Arithmetic Exception Program exit aP • Case 3: input: a= * • output: vi java.lang.NumberFormatException: * at java.lang.Integer.parseInt(Integer.java:231) at java.lang.Integer.parseInt (Integer.java:278) ee at MultipleCatch.main (MultipleCatch.java:15) • Case1: no catch block is executed, since no n exception is thrown. w. • Case 2: the first catch block is executed, since an ArithmeticException is thrown. ww • Case 3: a NumberFormatException is thrown but there is no matching catch block. Hence the program terminates CKR Java Notes 126
  • 400. Exceptions: Throwable and checked exceptions om • Unlike C++, primitive types cannot be thrown. Throwable types must be subclasses of Throwable .c • In the previous example we saw that an uncaught exception leads to program DF termination. • Not all exceptions can be uncaught. Exceptions may be divided into two classes • Unchecked exceptions are aP – subclasses of Error, or – subclasses of RunTimeException • checked exceptions: all others vi Exceptions: catch all ee • if a method can generate checked exceptions, then these must be either – specified using a throws clause – or caught in a try block n else there is a compile-time error w. • Unchecked exceptions need not be specified. – hence lazy programmers tend to subclass RunTimeException to produce ww their exceptions. – Program 28 CKR Java Notes 127
  • 401. class MyException extends Exception om { int exception_num; } public class CheckedException .c { int myMethod (int a, int b) throws DF MyException { MyException e = new MyException(); if (a==0) aP { e.exception_num = 1; throw e; } vi if (b==0) { e.exception_num=2; ee throw e; } return a/b;} n public static void main (String args[]) { w. CheckedException e = new CheckedException(); try ww { e.myMethod (0, 1); } CKR Java Notes 128
  • 402. catch (MyException me) om { System.out.println (me.exception_num); } } } .c • The above program will NOT compile if DF – the throw clause is removed from myMethod, or – the catch clause is removed from main (and no throws clause is provided to aP main) vi n ee w. ww CKR Java Notes 129
  • 403. Catch all exception handler om • Since all exceptions are subclasses of Exception, – To catch all exceptions, one uses the .c catch-all exception handler with Exception as the type DF catch (Exception e) { //catch block } aP • Since one exception is handled by at most one catch block, – if there is more than one catch block, – and a catch-all, vi • then the catch-all error handler must appear last – for the first catch block which fits the ee exception will be executed. • Similarly, if there are two catch blocks one n involving a base type and one a derived type, – then the catch block with base type must w. appear last – since a base type will fit a derived type, but not vice versa. ww CKR Java Notes 130
  • 404. Exceptions: Miscellaneous om • Try blocks may be nested. – In this case, if the first try block does not have an appropriate handler for the .c exception, the exception will be passed to the outer block, and so on. DF – The exception can be handled by both inner and outer catch block, by making the inner catch block rethrow what it has caught. aP • A finally clause may be associated with each try block, and this is guaranteed to execute. – The JVM achieves this by checking all vi possible exits to the try block. n ee w. ww CKR Java Notes 131
  • 405. Program 29 om import java.io.*; public class NestedCatch { public static void main(String args[]) { .c int a; int b; DF try { try aP { System.out.println (“a = ”); DataInputStream in = new vi DataInputStream(System.in); String inString = in.readLine(); a = Integer.parseInt (inString); ee System.out.println (“b = ”); b = Integer.parseInt (in.readLine()); int c = a/b; n } catch(ArithmeticException e) w. { System.out.println (“Caught Arithmetic exception”); ww throw e; //rethrow } CKR Java Notes 132
  • 406. catch (IOException i) om { System.out.println (“Caught i/o exception”); } finally .c { System.out.println (“Exiting inner try”); DF } } catch(Exception e) { aP System.out.println (“Caught something”); } System.out.println (“Program exit”); } vi } • input: a=2 ee b=2 • output: Exiting inner try n Program exit w. • input: a=* • output: ww Exiting inner try Caught something Program exit CKR Java Notes 133
  • 407. Threads om • A multitasking OS, such as UNIX or Widows, handles several processes at the same time. .c • Each process is an independently executing program, which may be – running DF – ready, or – blocked (waiting for input) • A thread is a subsequential flow of control within a single sequential program. aP – That is, a thread is a “lightweight” process (or a sub-process) that runs from within a program. • That is, a thread is a process, where the vi overheads involved in switching from one thread to another are small, since – a thread runs from within the program ee – a thread shares the existing memory space allocated to the program – Inter-thread communication is easier. n • From a logical point of view, however, threads w. are best thought of in terms of Hoare’s paradigm of – communicating sequential processes. ww – since only one processor, and one program is involved, the operational overheads are small in practice. CKR Java Notes 134
  • 408. Threads (contd.) om • Logically, the CSP (Communicating Sequential Processes) model applies to – parallel processing .c – multi-tasking – threads DF • However, the goals in each case are different. – In parallel processing, the goal is to improve performance at low cost, by aP increasing the number of processors, each of which runs a separate process. – In multi-tasking, the goal is to make more vi efficient use of a single processor (CPU), by running other processes when the CPU is idle because a given process is ee either blocked or idle, or does not need all the system resources. n • Java uses threads to permit part of a program to execute, even when another part of the program w. is – blocked (waiting for input) – or running in an infinite loop. ww CKR Java Notes 135
  • 409. Threads (contd) om • Thus, animation typically requires an infinite loop. – if a program has only one thread, it can .c perform animation, but do no other task. – Typically, however, one wants an DF animation, as a background, while some other process runs in the foreground. • Similarly, GUI typically involves event driven aP programming. – A particular text box (window) is in an infinite loop, – waiting for events, or vi – handling events. • Without threads, nothing else could execute ee until a particular event handler returns. – With multi-threading, one thread can wait for events or handle events without n blocking other parts of the program. w. • Finally, network download times are uncertain, so threads are essential for a complex program. ww • Thus, though Java is architecture-neutral it can run only in a multi-tasking environment! CKR Java Notes 136
  • 410. Threads om • Like a process, a thread can exist in various states – running .c – ready – suspended – resumed DF – blocked • In any of the above states the thread is alive. A thread an be terminated, in which case it is no aP longer alive. • Some key concepts associated with threads are the following. vi • Priority, decides how much of the process time the thread will consume. ee • Synchronization: – if one thread updates names, and n – another updates addresses the two threads must be synchronized to ensure that w. names and addresses match! • Deadlock:If two threads simultaneously access ww the same resource, this can result in a deadlock. – e.g. two people speaking simultaneously in an international call. CKR Java Notes 137
  • 411. Threads: implementation om • Every Java program has a Main thread. – The main thread is the first thread to start .c – and it must be the last thread to finish – since other threads are spawned or DF forked from the main thread. • Threads may be implemented in two ways. – implement the Runnable interface aP – extend the Thread class. • The interface Runnable has the run method which has the prototype vi public void run(); • There is no major difference between these two ee methods, since the Thread class extends Object and implements Runnable. – If the Thread object is created by n passing it a Runnable object then the run method of the Runnable object is w. invoked. – Else the run method of the thread class ww does nothing. CKR Java Notes 138
  • 412. Hence, in both cases, the run method must be om overridden. • In both cases, the entry point for the thread is the run method. .c • In both cases, one must create a Thread object. DF • The Thread class has several constructors. Some common constructors are given below. Thread(); aP Thread (Runnable, String); Thread (String) • The String passed to Thread decides the name of vi the thread. – Two distinct threads can have the same name. ee – Or a thread may not have a name – (the system will provide an internal name) n • The Runnable object passed to the Thread decides the run method which will be invoked. w. • After the Thread is created one must explicitly call its start method, upon which the JVM will call ww the Thread’s run method. CKR Java Notes 139
  • 413. Program 30 om class MyThread implements Runnable { Thread t; //instantiate Thread MyThread(int id)//define constructor { .c String myThreadName = new String (“mythread” + id); DF t = new Thread (this, myThreadName); System.out.println (“Child thread"+ “starting” + t); aP t.start(); //New thread must be explicitly started } vi public void run() //start calls run { try ee { for (int i=0; i<10; i++) { n System.out.println (“Child awake: ”+ i); t.sleep(100); //sleep for 100 ms w. //method sleep throws InterruptedException } } catch (InterruptedException e) ww { System.out.println (“Child interrupted”); } CKR Java Notes 140
  • 414. om System.out.println (“Child thread done”); } } public class ThreadMain .c { public static void main (String args[]) DF { //get a reference to the main thread //currentThread is a static method of //the Thread class aP Thread t = Thread.currentThread(); System.out.println (“Started ” + t); //start two new threads vi MyThread n1 = new MyThread (1); MyThread n2 = new MyThread (2); ee try { for (int i=10; i>0; i—) n System.out.println (“Main thread going to” + “sleep ” + i); w. //sleep is a static method //the second argument is nanosecond! Thread.sleep(2000, 2); ww //if 2000 is changed a deadlock may result } catch (InterruptedException e) { CKR Java Notes 141
  • 415. System.out.println (“Main thread om interrupted”); } System.out.println (“Main thread done”); } } .c DF • Output: Started Thread [main, 5, main] Child thread starting Thread [mythread1, 5, main] Child thread starting Thread [mythread2, 5, main] aP Child awake: 0 Main thread going to sleep 10 Main thread going to sleep 9 Main thread going to sleep 8 vi Main thread going to sleep 7 Main thread going to sleep 6 Main thread going to sleep 5 ee Child awake: 0 Main thread going to sleep 4 Main thread going to sleep 3 n Main thread going to sleep 2 Main thread going to sleep 1 w. Child awake: 1 Child awake: 1 ... ww Child thread done Child thread done Main thread done CKR Java Notes 142
  • 416. Threads (contd) om • In the above, the synchronization between the main thread and the child threads is dicey. .c • This has been accomplished by putting the main thread to sleep for a longer time. DF • To ensure more reliable synchronization, we use the join method. • The join method is the opposite of fork. aP – the child threads were forked from the main thread, – the thread which calls join() waits until the other thread joins it (i.e., dies) vi • To use this method, add the following code, and reduce the sleeping time of the main method) ee //improved synchronization System.out.println ( “Main waiting for children to finish”); n try{ n1.t.join(); w. n2.t.join(); } catch (InterruptedException e) { System.out.println ( ww “Child thread interrupted”); } System.out.println (“Main thread done”); CKR Java Notes 143
  • 417. Threaded applets om • Threaded applets can be created in exactly the same way. .c • A threaded applet will extend Applet and implement Runnable. DF • An example is given below. Program 31 //A parametrized banner aP import java.awt.*; import java.applet.*; /* vi applet code="Parmc" width = 300 height = 50 param name=message value="Time never stops!" ee param name=fontName value="Times New Roman" param name=fontSize value="18" /applet n */ w. public class Parmc extends Applet implements Runnable { ww String msg; String fN; int fS; CKR Java Notes 144
  • 418. Font f; om Thread t = null; //Set colors and initialize thread public void init() .c { setBackground (Color.cyan); DF setForeground (Color.red); f=new Font (“Courier”, Font.PLAIN, 12); //Create space for font setFont (f); //set new font. aP t = new Thread (this); //create new thread t.start(); //start thread running t.suspend(); //Suspend until applet fully initialized vi //this is the old suspend method now //deprecated. } ee public void start() { n String param; msg = getParameter (“message”); w. if (msg == null) msg = “Message not found.”; msg = “ ”+ msg + “ ”; ww fN = getParameter (“fontName”); if (fN == null ) CKR Java Notes 145
  • 419. fN = “Courier”; om param = getParameter (“fontSize”); try { if (param!= null ) .c fS = Integer.parseInt (param); else DF fS = 12; } catch (NumberFormatException e) { fS = -1; aP } f = new Font (fN, Font.PLAIN, fS); setFont (f); t.resume(); vi } //Entry point for the thread that runs the ee banner. public void run() n { char ch; w. //Displays banner until stopped ww for (; ; ) { try CKR Java Notes 146
  • 420. { om repaint(); Thread.sleep (500); ch = msg.charAt(0); msg = msg.substring (1, msg.length()); msg += ch; .c } catch (InterruptedException e) { DF } } aP } //Pause the Banner vi public void stop() { t.suspend(); ee }r //Kill thread when applet is terminated n public void destroy() w. { if (t != null) { ww t.stop(); t = null; } CKR Java Notes 147
  • 421. } om //Display the banner public void paint (Graphics screen) { .c screen.drawString (msg, 50, 30); } DF } aP vi n ee w. ww CKR Java Notes 148
  • 422. Thread priorities om • Threads can have different priorities on a scale of 1-10. .c • The average thread has a priority of 5. • Technically, the priority scale ranges from DF MIN_PRIORITY to MAX_PRIORITY, which numbers are currently 1 and 10 respectively. – The average priority is defined by the number NORM_PRIORITY. aP – These numbers are defined as final variables in the Thread class • When a thread is created, its priority is set equal to the priority of the thread which created it. vi • Thread priority may be determined or changed using the methods ee final void setPriority ( int P_level) final int getPriority () n – p_level must be an int in the priority w. scale of 1-10. – The actual priority set will the minimum of p_level and the priority of the calling ww thread. CKR Java Notes 149
  • 423. Thread priorities (contd) om • Thread priorities only provide a rough indication of how much time the thread will get. .c • The same priority thread may get different amount of time slices from run to run. DF • These considerations are demonstrate by the following example program. class Ticker implements Runnable aP { int tick = 0; Thread t; private volatile boolean isRunning = true; vi //define constructor public Ticker (int p_level) ee { t = new Thread (this); t.setPriority(p_level); n } w. public void run() { while (isRunning) ww { tick++; } CKR Java Notes 150
  • 424. } The owner om Entry set void stop() public Wait set { isRunning = false; } .c public void start() DF { t.start(); } } aP public class Priority { public static void main(String args[]) vi { Thread.currentThread().setPriority (Thread.MAX_PRIORITY); ee Ticker high = new Ticker (Thread.NORM_PRIORITY + 2); Ticker low = new Ticker n (Thread.NORM_PRIORITY - 2); w. high.start(); //call to thread.start() low.start(); //JVM will call run() ww try { Thread.sleep (5000); CKR Java Notes 151
  • 425. /*causes the thread to sleep (cease om execution) for the specified number of milliseconds*/ } catch(InterruptedException e) /*Derived from Exception */ { .c System.out.println("Main thread interrupted"); DF } int pLow = low.t.getPriority(); int pHigh = high.t.getPriority(); low.stop(); aP high.stop(); try { /*wait for other threads to end*/ vi high.t.join(); low.t.join(); } catch(InterruptedException e) ee {} System.out.println(pLow + " priority thread got: " + low.tick + " clock ticks"); n System.out.println (pHigh + " priority thread got: " + high.tick + " clock w. ticks"); } } ww • Output: varies from run to run. CKR Java Notes 152
  • 426. ww CKR w. nee vi aP Java Notes DF .c om 153
  • 427. Thread synchronization om • Since it is not clear when the system will switch from executing one thread to executing another, various peculiarities may arise. .c • Race conditions: Different threads may all manipulate the same object, and may race to DF finish execution. • To avoid this, Java has a synchronized statement. aP synchronized (objectref) { /*Synchronized block*/ } • Java’s synchronization model uses monitors to support two kinds of thread synchronization. vi – mutual exclusion – cooperation ee • Cooperation is achieved through inter-thread communication, using the – wait(), and n – notify() – notifyall() w. methods of Object, implemented as final methods. – These methods can be called only within ww a synchronized block. • Mutual exclusion is achieved through locks imposed by the JVM. CKR Java Notes 154
  • 428. Thread synchronization (contd) om • A monitor is like – a building – which has a a special room (toilet?) .c Only one person can use the special room at a time. • From the time the thread enters the special DF room to the time it leaves the special room, it has exclusive access to the data in the room. • Entering the building is called “entering the aP monitor”. • Entering the special room is called “acquiring the monitor”. vi • Occupying the special room is called “owning the monitor”. ee • Leaving the special room is called “releasing the monitor”. n • Leaving the entire building is called “exiting the w. monitor”. • A monitor is also associated with a bit of code ww called a monitor region. – A monitor region is a code that is executed as one indivisible operation. CKR Java Notes 155
  • 429. Thread synchronization (contd) om • When one thread is executing a monitor region, associated with a given monitor, no other thread can execute any part of that region. .c • A thread can only enter a monitor by arriving at the beginning of a monitor region, associated DF with that monitor. • At this point the thread is placed in the entry set for the associated monitor. aP • The only way a thread can move forward and execute the monitor region is by acquiring the monitor. vi • If the monitor is not owned by any other thread, the thread can acquire the monitor, execute the ee monitor region, exit and release the monitor. • If the monitor is currently owned by another n thread the given thread must wait, until that monitor is released. w. • After that, it must compete with any other threads also waiting in the entry set. ww • Only one thread form the entry set will win the competition and acquire the monitor. CKR Java Notes 156
  • 430. While exclusion keeps threads from interfering om with one another, cooperation helps the threads to work towards a common goal. – e.g. a "read" thread which is reading data from a buffer filled by a "write" thread. .c DF aP Enter Release Acquire Acquire vi ee Release & Exit n Waiting thread w. Active thread ww CKR Java Notes 157
  • 431. Thread synchronization (contd) om • The JVM uses a "wait and notify" model of cooperation. .c • A thread that currently owns a monitor voluntarily relinquishes it by executing a wait() command. DF • The thread will stay suspended, in the wait set, until after another thread executes a notify command. aP • The thread issuing the notify command continues to own the monitor, until it releases the monitor of its own accord. vi • A waiting thread can optionally issue a timeout to the JVM. ee • At the end of the timeout, even if no other thread notifies it, it will be automatically resurrected by n a notify message from the JVM. w. • JVM implementers are free to make FIFO or LIFO queues or some more complex orderings to decide which of the waiting threads will acquire ww the monitor. • Thus, e.g. use notifyall() rather than notify() for there may be more than one thread waiting. CKR Java Notes 158
  • 432. Thread synchronization (contd.) om • The JVM coordinates multithreaded access to two kinds of data: – Instance variables .c – Class variable • The JVM does NOT coordinate access to local DF variables which reside on the stack and are private to the thread to which the stack belongs. • Every object and every class is associated with a aP monitor. – For classes, the monitor protects the class variables. – For objects, the monitor protects the vi instance variables. • To implement mutual exclusion, the JVM associates a lock with each object and class. ee • A single thread is permitted to lock an object any number of times. n – In that case the object must be unlocked as many times for it to be released. w. • Programmers however need be concerned only with the synchronized statement. ww CKR Java Notes 159
  • 433. These considerations are illustrated by the om following sample program . /*Aim: To illustrate the asynchronous operation of threads. .c One thread attempts to update data in the same object from which another thread DF is trying to retrieve data. This may result in garbled output, which varies from run to run. */ aP class Student { String name;//class Student has two data int marks; //members which can be updated vi //or printed. Student (String n, int m) ee { name = n; marks = m; n } w. void Update (String n, int m) { name = n; ww /*after doing the above suppose the thread is descheduled. To simulate this, we artificially CKR Java Notes 160
  • 434. put the thread to sleep. */ om try { Thread.sleep (1000); } catch (InterruptedException e){} /*The thread now resumes*/ .c marks = m; } DF void Print () { System.out.println ( name); aP /*after doing the above suppose the thread is descheduled. To simulate this, we artificially put the thread to sleep. */ vi try { Thread.sleep (1000); ee } catch (InterruptedException e){} /*The thread now resumes*/ System.out.println (" " + marks); n w. } } ww class Interact implements Runnable { CKR Java Notes 161
  • 435. Student s; om Thread t; int iType; int newMarks = 0; String newName; Interact (Student std, int i) //define .c constructor { DF s = std; iType = i; newName=" "; t = new Thread (this); aP t.start(); } Interact (Student std, int i, String str, vi int m) { //define a second construtor s = std; ee iType = i; newName = str; newMarks = m; n t = new Thread (this); t.start(); w. } ww CKR Java Notes 162
  • 436. public void run() om { //either update or print switch (iType) { case 1: s.Print(); break; .c case 2: s.Update (newName, newMarks); break; DF default: break; } } } aP public class Async { public static void main(String args[]) vi { Student s = new Student ("Ram" , 40); Interact i1 =new Interact (s, 2, "Shyam", ee 50); Interact i2 = new Interact (s, 1); try n { //wait for threads to finish i1.t.join(); w. i2.t.join(); } catch (InterruptedException e){} ww } } CKR Java Notes 163
  • 437. /*Possible output: Shyam om 40 Note: Output may vary from run to run */ • Only two changes are needed in the preceding program. .c • The method run should be synchronized on the DF student object, as follows. • 1. Change the run function aP public void run() { synchronized (s) { switch (iType) vi { //... } } ee } • 2. Change the name of the class to SyncAsync n • In this case the output is not jumbled up. w. • 3. To experiment further, change the thread priorities, as in the following sample program. • ww /*Aim: To illustrate how threads may be synchronized. In the earlier code Async.java CKR Java Notes 164
  • 438. one thread attempted to update data in om the same object from which another thread was trying to retrieve data. This sometimes resulted in garbled output, which varied from run to run. The present code changes this by using synchronization. The earlier .c code is changed in just two places*/ DF class Student { String name;//class Student has two data aP int marks; //members which can be updated //or printed. Student (String n, int m) vi { name = n; marks = m; ee } void Update (String n, int m) n { name = n; w. /*after doing the above suppose the thread is descheduled. To simulate this, we artificially ww put the thread to sleep. */ try { CKR Java Notes 165
  • 439. Thread.sleep (1000); om } catch (InterruptedException e){} /*The thread now resumes*/ marks = m; } .c void Print () { DF System.out.println ( name); /*after doing the above suppose the thread is descheduled. To simulate this, we artificially aP put the thread to sleep. */ try { Thread.sleep (1000); vi } catch (InterruptedException e){} /*The thread now resumes*/ System.out.println (" " + marks); ee } n } w. class Interact implements Runnable { ww Student s; Thread t; int iType; CKR Java Notes 166
  • 440. int newMarks = 0; om String newName; Interact (Student std, int i) //define constructor { s = std; .c iType = i; newName=" "; DF t = new Thread (this); t.setPriority (4); t.start(); } aP Interact (Student std, int i, String str, int m) { //define a second construtor vi s = std; iType = i; newName = str; ee newMarks = m; t = new Thread (this); t.setPriority(1); n t.start(); } w. public void run() ww { //either update or print synchronized (s) /*1. operation on s is synchronized*/ CKR Java Notes 167
  • 441. { om switch (iType) { case 1: s.Print(); break; case 2: s.Update (newName, newMarks); .c break; default: break; DF } } } } aP public class SyncAsync /*2. Name of the class is changed*/ { vi public static void main(String args[]) { Student s = new Student ("Ram" , 40); ee Interact i1 =new Interact (s, 2, "Shyam", 50); Interact i2 = new Interact (s, 1); n try { //wait for threads to finish w. i1.t.join(); i2.t.join(); } catch (InterruptedException e){} ww } } CKR Java Notes 168
  • 442. Output: Ram om 40 • Note: Output may vary from run to run, and with thread priorities, but the output will be either Ram 40 or Shyam 50. .c DF aP vi n ee w. ww CKR Java Notes 169
  • 443. i/0: Streams and Files in C om • We recollect that C uses the two abstractions – streams, and – files .c • C was developed in the context of Unix, and in Unix everything is a file: console, keyboard, disk DF files, tape drives etc. • A stream provides a level of abstraction between the programmer and the physical device, viz. file. aP (i.e., represented by the file abstraction). • There are two kinds of streams – text streams vi – binary streams • A text stream is a sequence of characters. ee – text streams are organized into lines separated by the newline character. n – in a text stream certain character translations may occur as required by w. the host environment, e.g. – a newline may be converted to a carriage ww return/linefeed pair on a printer. CKR Java Notes 170
  • 444. Thus, there is NOT a on-to-one om relationship between the characters that are read (or written) to a text stream, and the characters stored on the external device. .c • A binary stream is a sequence of bytes – no character translations are permitted DF in a binary stream. • Hence in a binary stream there is a one to one correspondence between aP – the characters written to the stream, and – the characters stored in the external device. vi – However, an implementation dependent number of null bytes may be appended ee to the end of a binary stream, to fill up the sectors on a disk, for example. n • Correspondingly there are two types of files w. – text files, and – binary files ww CKR Java Notes 171
  • 445. A file may be any device om – a terminal – a keyboard – a printer • Streams are associated with files by performing .c an open operation. DF • Streams are dissociated with files by performing a close operation. • While all streams are the same, all files are not. aP – A disk file can support random access. – A printer typically cannot. • Certain types of files (e.g. disk files) may support vi position requests – Opening such a file also initializes the file position indicator to the beginning of ee the file. • Files are represented in a C program by a FILE n structure. – A FILE * variable is called a file pointer. w. • Streams may contain a buffer, which stores characters before they are actually written to a file. ww – Such buffers improve execution speed. – writing the buffer is called flushing. CKR Java Notes 172
  • 446. C-style i/o: standard streams om • Whenever a program starts, it usually needs to be able to – input data from the keyboard .c – output data to the screen – inform the user of some error conditions. DF • Accordingly, three predefined streams are available, to any program – stdin (keyboard) – stdout (screen) aP – stderr (screen) • stdin is the standard input device, usually connected to the keyboard. vi – remember this is a file which has to be opened. ee – The availability of this predefined stream means that the programmer does not have to do this manually,. n –however, input may be redirected and w. taken from a disk file, using < myprogram < myfile – This may be achieved since the ww programmer is dealing with an abstraction. CKR Java Notes 173
  • 447. C-style i/o (contd) om • stdout is the standard output device, usually the screen – however, output may be redirected to a .c disk file using > myprogram > myfile DF • stderr is usually the screen. • File i/o is not fundamentally different from console i/o. aP • The only difference is that a file pointer must be available for file i/o. vi • This file pointer can be obtained by means of a file open call as in the program above, using the open function, and ee – supplying a file name – supplying an open mode n FILE * DataFile = fopen(szFileName, szMode); w. • The open mode can be – r (read) ww – w (write) – a (append) – rb (open binary file for reading) etc. CKR Java Notes 174
  • 448. C file i/o om • One difference between console i/o and file i/o is that diskfiles support random access i/o, and hence indicate position in the file. .c • This is accomplished by using the function fseek which has the prototype DF int fseek (FILE *fp, long numbytes, int whence); aP • The fseek function takes three parameters – FILE *fp (the file pointer returned by the call to fopen vi – numbytes indicates the number of bytes to move ee – whence is the position indicator, and could be – SEEK_SET (0) Beginning of file n – SEEK_CUR (1) Current position – SEEK_END (2) End of file. w. • To seek the nth item of a data which set numbytes to n*sizeof(datatype) in a binary file. ww • stdout can be internally redirected by using freopen(const char* filename, , const char* mode, FILE *stream) CKR Java Notes 175
  • 449. om • if one is at the end of the file, one should use rewind() to return to the beginning of the file. • To know one’s current position in the file, one .c uses the function ftell(), which has the prototype long ftell (FILE *fp); DF • For formatted file i/o one uses the functions – fprintf() – fscanf() aP • In addition to – console i/o, and – file i/o vi C supports a third form of i/o • character array based i/o ee – where reading and writing can be done to a character array in memory. n – this uses the family of functions w. beginning with s, e.g. – sprintf ww – sscanf – etc. CKR Java Notes 176
  • 450. i/o (contd.) : Difference between text and binary streams om • The following example demonstrates some of these concepts. Program 32 .c /* TXTFILE.c * This program demonstrates how text and * binary files DF * differ */ #include <stdio.h> aP #include <string.h> /* For string functions */ #include <conio.h> /* For console getch(), getche(), etc. */ vi #include <ctype.h> /*For character-conversion functions tolower() */ ee #define MAX_LINES 25 #define MAX_LENGTH 80 n char szSaying[MAX_LINES][MAX_LENGTH] = { /*ALL strings below should be coded to fit into w. one line AND padded to cover 64 characters*/ “nFirestone’s Law of Forecasting: n", “n Chicken Little has to be right only once. n”, “n ww nn”, “nManly’s Maxim: n”, “n Logic is a systematic method of coming to n”, CKR Java Notes 177
  • 451. “n the wrong conclusion with confidence. n”, om “n nn”, “nMoer’s truism: n”, “n The trouble with most jobs is the job holder’sn”, .c “n resemblance to being one of a sled dog team. No one n”, “n gets a change of scenery except the lead dog. DF n”, “n nn”, “nCannon’s Comment: n”, “n If you tell the boss you were late for work aP because you n”, “n had a flat tire, the next morning you will have a flat tire.n”, “n nn”, vi }; ee int main(void); n int main() w. { FILE *DataFile = NULL; ww char szFileName[25]; /*string to hold filename*/ CKR Java Notes 178
  • 452. char szMode[5] = “w00"; om /*to hold file mode*/ int i; int nNumberRecords = 0; int nRecord = 0; .c int nResult = 0;r DF long lNewPosition = 0; long lOldPosition = 0; /* Prompt the user to supply the mode, aP * either lowercase t * for a text file or lowercase b for a * binary file. */ vi while (DataFile == NULL) { ee while(szMode[1] != ’b’ && szMode[1] != ’t’) { printf(”nEnter ’t’ for text file, n "’b’ for binary: “); szMode[1] = tolower(getche()); w. } printf( ww ”nEnter the name of file to write: “); gets(szFileName); if ((DataFile = fopen(szFileName, CKR Java Notes 179
  • 453. szMode))==NULL) om { printf(”n ERROR: opening file ’%s’.n", szFileName); } } .c printf(“n”); DF switch(szMode[1]) { case ’t’: printf(“This is a text filenn”); aP break; case ’b’: printf(“This is a binary filenn”); vi break; } ee for (i = 0; strlen(szSaying[i]); i++) { lOldPosition = ftell(DataFile); n /*store current file position*/ w. fwrite(szSaying[i], /*Saying number to write*/ strlen(szSaying[i]), ww /*size (in bytes) to write*/ 1, /*No of items of above size to write*/ DataFile); /*where to write*/ CKR Java Notes 180
  • 454. lNewPosition = ftell(DataFile); om /*get new file position*/ printf( “Start position %5ld ” “end %5ld, ” .c “strlen(...) %d but ” “wrote %5ld bytes’n”, DF lOldPosition, /*start position*/ lNewPosition, /*end position*/ strlen(szSaying[i]), /*string length*/ (long)lNewPosition - lOldPosition); /*file aP position change*/ } fclose(DataFile); vi printf(“n”); ee switch(szMode[1]) { case ’t’: n printf(“Note the bytes written do NOT” “ equal the string lengthnn”); w. break; case ’b’: ww printf(“Note the bytes written DO” “ equal the string lengthnn”); break; CKR Java Notes 181
  • 455. } om getch(); return (0); } • Input: t • output: Bytes written do not match string length .c • Input b DF • Output: Bytes written match string length aP vi n ee w. ww CKR Java Notes 182
  • 456. Java i/o om • Java i/o resembles C i/o. • The key difference is that Java is designed to be .c completely object-oriented, so that – Java i/o is object oriented. DF • This is achieved through wrapper classes. • Wrapper classes have been created for – streams aP – files – data types • This has the effect of making Java i/o somewhat vi complicated. – This complication may be unavoidable, if the aim is to have platform ee independence rather than merely portability. n • Java i/o is internally byte-oriented. w. • However, classes are provided to support character streams. ww CKR Java Notes 183
  • 457. Predefined Streams om • The three standard predefined streams of C – stdin – stdout .c – stderr • are available in Java as the three members of the DF static System class – in – out – err aP • The System class cannot be instantiated since it has a private constructor. vi • However, it is a static class, so we can refer to its members simply by using the class name. ee • Thus, instead of stdin, stdout, stderr we respectively use n – System.in – System.out w. – System.err ww CKR Java Notes 184
  • 458. Byte and Character i/o om • In C there are two types of streams – binary – character .c • Correspondingly, Java has two types of i/o classes DF – byte oriented i/o classes – character-oriented i/o classes • Additional complications are introduced by the aP need for – Unicode characters – platform independence vi • The byte-stream oriented class hierarchy begins with two abstract classes ee – InputStream – OutputStream n • The character-stream oriented class hierarchy also begins with two abstract classes w. – Reader – Writer ww • These classes define basic methods such as read() and write(). CKR Java Notes 185
  • 459. Java Character i/o: Input om • Since Reader and Writer are abstract classes, we need to use subclasses which implement all their methods. .c • To Read a character we need to use the class InputStreamReader DF • The InputStreamReader class converts bytes to characters. aP • However, since i/o access is time-consuming, to improve efficiency, we should use the InputStreamReader class in combination with a class which provides a buffer. Such a class is vi the class BufferedReader ee • The BufferedReader class is a direct subclass of Reader. It has two constructors BufferedReader (Reader in) n BufferedReader (Reader in, int buff_size) w. • Since Reader is an abstract class, we cannot instantiate it. So how do we get a reference to a Reader type ? ww CKR Java Notes 186
  • 460. To get a reference to a Reader type, we use, the om InputStreamReader, which is also a direct subclass of the class Reader. – Hence an object of type InputStreamReader can be used as a reference to a Reader type. .c • The InputStreamReader has two constructors: DF InputStreamReader (InputStream in) InputStreamReader (InputStream in, String encoding) aP • The second construtor specifies the name of the character encoding to be used. • For the default encoding, we use only the first vi constructor. • Since InputStream is also an abstract class, how ee do we get a reference to an InputStream type? • For this we can use n – either a concrete subclass of InputStream, or w. – System.in (which is a reference of type InputStream) ww CKR Java Notes 187
  • 461. Reading a character om • With all this wrapping, we can finally read a single character using Java! .c • Step 1: Create a new BufferedReader BufferedReader br = new BufferedReader DF (new InputStreamReader (System.in) ); • Step 2: Read a character using the newly created br object and the read() method of the aP BufferedReader class. – One form of read() reads a single character, and returns an int. – This int must be typecast to char. vi char c = (char) br.read(); ee • We can check the input, by printing it, using a call to the println() method of the System class. System.out.println(c); n • Note: Unlike the getch() function, and like the w. getchar() function, since System.in is line buffered, no input is actually passed to it, until a carriage return is pressed. The call to println() ww places a carriage return and flushes the buffers. CKR Java Notes 188
  • 462. Reading a string om • To read an entire string, use the readln() method of the BufferedReader class. – The readln() method throws an .c IOException (which is a checked exception). DF • To adjust the efficiency manually, we can explicitly specify the size of the buffer, by using the second form of the constructor BufferedReader(Reader in , int buff_size); aP Output to console • For output to console, we have been using the vi out member of the System class. ee • The out and err members are of type PrintStream. – PrintStream is a character-based output class. n – It converts its byte- arguments to 8-bit ASCII Representations. w. – The constructor for this class is deprecated in JDK 1.2 – Thus, one should avoid constructing ww new PrintStream objects. CKR Java Notes 189
  • 463. Output to Console om • The alternative is to use the PrintWriter class, which directly subclasses Writer, and converts its arguments to 16-bit Unicode representation. .c • The Printwriter class supports output for all primitive data types (and even Object), and it can DF be used exactly like System.out. • The constructor for Printwriter requires a reference to either aP – OutputStream, or – Writer • In addition, a second boolean parameter may be supplied . If set to true, this will flush buffers on a vi call to a println() method. • E.g. ee PrintWriter (OutputStream out, boolean flush); • Since PrintStream is a subclass of n OutputStream, we can use the System.out for a reference to OutputStream. w. • Note: In PrintWriter, unlike PrintStream, the buffer will NOT be flushed on newline, but only ww on use of a println method. – Error in Java 2 Complete Reference, p 323. CKR Java Notes 190
  • 464. • These considerations are illustrated by the om following program. Program 33 //java i/o supports both byte and char //streams, though the i/o is primarily .c //byte based. //character streams are supported by the DF //abstract Reader class //which has a concrete subclass //InputStreamReader //and BufferedReader aP //Output is preferably done via the //PrintWriter class rather than a //call to System vi import java.io.*; public class TestIO { ee public static void main (String args[]) throws IOException { //Creating a BufferedReader object n BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); w. //Creating a PrintWriter object //The second parameter indicates whether line //is to be flushed on encountering n ww PrintWriter pw = new PrintWriter (System.out, true); pw.println ("Enter a character: ’q’ to CKR Java Notes 191
  • 465. quit"); om char c; do { c = (char) br.read(); pw.println (c); } while (c !=’q’); .c //Reading a string String str; DF pw.println ( "Enter a line of text or data"); pw.println ("Enter ’end’ to quit"); do { aP str = br.readLine(); pw.println (str); } while (!str.equals ("end")); } vi } • Input: abcdq ee • Output: a b n c d w. • Input: The quick brown fox ... end • Output: The quick brown fox ... ww CKR Java Notes 192
  • 466. File i/o om • We see that the Java philosophy is to separate – byte streams and – character streams .c into two separate class hierarchies, starting from – InputStream, OutputSream – Reader, Writer DF • Similarly, for stream-based file i/o, Java provides two sets of classes. – FileInputStream, FileOutputStream aP – FileReader, FileWriter • All these classes have constructors which take the filename (inclusive of full path) as a String vi FileInputStream(String fileName) FileoutputStream (String fileName) FileReader (String fileName) ee FileWriter (String fileName) • All the above constructors throw a FileNotFound n Exception, if the input file cannot be found or the output file cannot be created. w. • If the output file exists it is overwritten. To avoid this one can use the alternative constructors FileOutputStream (String fileName, boolean ww append) FileWriter (String fileName, boolean append) CKR Java Notes 193
  • 467. File i/o (contd) om Program 34 /*Java file i/o may be done using the .c classes FileInputStream (String filename) FileOutputStream (String filename) DF FileOutputStream (String filename, boolean append) all of which constructors throw a FileNotFoundException aP */ import java.io.*; vi public class TestFileIO { public static void main(String args[]) ee //throws IOException { if (args.length <= 1) n { System.out.println ( "Usage: java TestFileIO fromFileName w. toFileName"); return; } ww FileInputStream fin; FileOutputStream fout; CKR Java Notes 194
  • 468. try om { fin = new FileInputStream (args[0]); } catch (FileNotFoundException e) { System.out.println ("Input file not" + .c "found"); return; DF } try { aP fout = new FileOutputStream (args[1]); } catch (FileNotFoundException e) { System.out.println ("Error opening " + vi "output file"); return; } ee catch (IOException e) { System.out.println ("Error opening " n "output file"); return; w. } int i; try ww { do { CKR Java Notes 195
  • 469. i = fin.read(); om if (i!=-1) //if not end of file fout.write (i); /*Note: Only low-order 8 bits are written Thus above code works for text or binary.*/ .c /* Print the same text to screen.*/ } while (i!= -1); DF } catch (IOException e) { System.out.println ("Error reading or" + "writing file"); aP //No return call here } finally { try vi { fin.close(); ee fout.close(); } catch (IOException e) n { System.out.println ("Error closing files"); w. } } } ww } CKR Java Notes 196
  • 470. File i/o : Filename separators om • In the above example program, the filenames were taken as parameters passed to the main method. .c • What if one wants to specify the filename internally. DF • At this point the issue of platform independence again crops up. – Unix uses / as a file name separator aP – DOS/Win use as a file name separator – C uses for escape characters (to escape the ordinary meaning of a character, e.g. n = newline) vi – To print one must use in C. • Thus, the preferred method is to use / or use to ee specify the path. • Java resolves this correctly, depending on the n system. w. • E.g. FileReader = new FileReader ("C:mydirmyfile.ext"); ww FileWriter = new FileWriter ("C:mydiryourfile.ext", true); CKR Java Notes 197
  • 471. File i/o : Random Access Files om • Finally, Java distinguishes completely between streams and random access files which support position requests. .c • Thus, Java defines a class called RandomAccessFile DF – which is NOT derived from InputStream or OutputStream, – but is derived directly from Object aP public class RandomAccessFile extends Object implements DataOutput DataInput • DataInput and DataOutput are abstract interfaces vi which have methods to convert all of Java primitive data types from/to a sequence of bytes, and to read/write these to a binary stream . ee • One constructor for this class is RandomAccessFile (String fileName, String n mode) w. • Here mode must be either – "r" (for reading only) or – "rw" (both reading and writing) ww • The constructor throws a FileNotFound Exception, which is a subclass of IOException. CKR Java Notes 198
  • 472. File i/o: Random Access Files (contd.) om • Additionally, the RandomAccessFile constructors may throw the following Exceptions .c • IllegalArgumentException if the mode is anything other than "r" or "rw". DF • SecurityException if read/write permission for the file is not available (e.g. in Unix systems) • These exceptions are unchecked exceptions, so aP the programmer is not obliged to bother about them. • A random access file is implicitly a large array of vi bytes. – The position in this implicit array is given by the file pointer. ee – To get the current position use the method (instead of tell) n long getFilePointer(); w. – To set the current position use the method void seek (long pos); ww • As already stated, various methods are available for reading and writing the primitive data types. CKR Java Notes 199
  • 473. Program 35 om import java.io.*; public class CompareFile { public static void main (String args []) .c throws IOException { DF String s1 = "Files differ in size by : "; String s2 = "Files differ at offset: : "; /*Prepare initial string table */ aP if (args.length < 2) { System.out.println ( "Usage: java CompareFile fromFileName " vi + "toFileName"); return; } ee RandomAccessFile fFrom = new RandomAccessFile (args[0], "r"); n RandomAccessFile fTo = new RandomAccessFile (args [1], "r"); w. RandomAccessFile fRes = new RandomAccessFile ("c:kawaresult", "rw"); ww long fsize1 = fFrom.length(); long fsize2 = fTo.length(); CKR Java Notes 200
  • 474. om int bufsize = (int) Math.min (fsize1, fsize2); int fmaxsize = (int) Math.max (fsize1, fsize2); .c System.out.println ("bufsize = " + bufsize); DF System.out.println ("fmaxsize = " + fmaxsize); if (fsize1 != fsize2) { aP fRes.writeChars (s1); fRes.writeInt ((fmaxsize - bufsize)); } vi byte buf1 [] = new byte [bufsize]; byte buf2 [] = new byte [bufsize]; ee /*allocate buffers to hold files as byte-arrays in memory */ n fFrom.readFully (buf1, 0, bufsize); fTo.readFully (buf2, 0, bufsize); w. /*args to readFully are buf, from, to */ ww CKR Java Notes 201
  • 475. for (int i=0; i bufsize; i++) om { if (buf1 [i] != buf2 [i]) { fRes.writeChars (s2); fRes.writeInt (i); .c //fRes.writeChars (s3); } DF } fFrom.close(); fTo.close(); aP long fp = fRes.getFilePointer(); System.out.println ("Length of result = " + fp); /*1*/fRes.seek((long)2*s1.length()); vi fp = fRes.getFilePointer(); System.out.println ("Currently at: " + fp); ee int i = fRes.readInt (); System.out.println (s1 + i); n fRes.close(); } w. } • Note: /*1*/ : s1.length() returns the number of ww characters in the string s, but for position we need the number of bytes into the file, hence the factor of 2. CKR Java Notes 202
  • 476. File i/o: the File class om • Somewhat like the File structure in C, Java has a File class. .c • However, in Java, this class is used exclusively – to create files and directories, – to query and change their properties DF • The File class does NOT incorporate any read/write methods. aP • As in Unix, a directory is simply a special type of file. • The key issue is platform independence and the vi matter of the separator character: / or • To achieve this, Java uses the notion of an ee abstract pathname. While pathname strings are system dependent, abstract pathnames are not. n • An abstract pathname consists of – An optional prefix (such as / for root dir in w. Unix or a drive specification – A sequence of zero or more String names. ww • Each name, except the last must be a directory. • The last can be either a directory or a file. CKR Java Notes 203
  • 477. File i/o: File class (contd) om • The File class has three constructors: File (String pathname) .c File (File parent, String child) File (String parent, String child) DF • It defines a variety of methods. All the following return a boolean value. – exists() – canRead() aP – canWrite() – isDirectory() – isFile() – isHidden() vi – isAbsolute() – delete() – setReadOnly ee – mkdir() • The following method returns a URL – toURL() throws n MalformedURLException w. • For various other methods consult the documentation. ww • An example follows. CKR Java Notes 204
  • 478. Program 36 om import java.io.*; public class FileDemo { public static void main (String args[]) .c { if (args.length < 1) DF { System.out.println ("Usage: FileDemo pathname/filename"); return; aP } File f = new File (args[0]); String s1 = f.exists() ? "Yes" : "No"; vi String s2 = f.isFile() ? "Yes" : "No"; String s3 = f.isDirectory ()? "yes" : "No"; String s4 = f.canRead() ? "Yes" : "No"; ee String s5 = f.isAbsolute() ? "Yes" : "No"; System.out.println ("Exists : "+s1); n System.out.println("Is File : " + s2); System.out.println("Is Directory : " + s3); w. System.out.println("Can Read : " + s4); System.out.println("Is Absolute : " + s5); }} ww • Input: experiment CKR Java Notes 205
  • 479. Numeric i/o:Type Wrapper classes om • apart from – character i/o and – byte i/o .c Java implements a third type of – object i/o which we shall not, however, examine here. DF • The above i/o techniques still do not tell us how to read a numeric value, such as an int or float. aP • For a language which claims to be simple, numeric i/o in Java is remarkably complex. • Java follows the old C-method of doing things: vi to read and write numbers one must first convert them to strings. ee • The programmer is expected to carry out these conversions explicitly. n • To write a numeric value, we must first convert it to a string by concatenating using + w. • To read a numeric value we must first read in a string and convert it to a numeric value by going ww via type-wrapper classes. CKR Java Notes 206
  • 480. Numeric i/o and type-wrapper classes (contd) om • The type wrapper classes wrap the primitive type into classes, so that they can be treated as objects. .c • Some of the type wrapper classes are the following (note the capitals) DF – Byte – Short – Integer – Long aP – Float – Double • All the above are derived by subclassing the vi abstract class – Number which subclasses Object. ee • All the above types have constructors which take a string and return the wrapped object. n • Alternatively, one may use the static member w. function – valueOf(String str) for Float etc. – parseInt(String str) for Integer. ww • Both the above methods may throw a NumberFormatException (which is derived from CKR Java Notes 207
  • 481. RunTimeException and so is unchecked). om • All the above types have member functions – byteValue(), intValue(), floatValue() etc. which return the equivalent primitive type. .c • These considerations are illustrated by the following program. DF Program 37 /*This program illustrates how data types aP may be converted to and from strings this is a pre-requisite for i/o involving primitive datatypes. vi For a language which claims to be simple i/o involving primitive data types is remarkably complex in Java. ee To convert from data type to string, use valueOf n (double/float/int/long/char/char[]/boolean/ Object/...) .of the String class w. Note that the valueOf function of the Float class (or Number class) is ww different. it returns a Float object. */ CKR Java Notes 208
  • 482. /* Summary: om To read in an int, float etc. read in a string, convert the string to a wrapper class, and then extract the data type from the wrapper class. .c Step 1: Read in a string DF Step 2: (String to Wrapper class) convert the string to a wrapper class by (a) passing the string to the aP constructor of that wrapper class or (b) use the valueOf vi static member function of the corresponding class, for Float etc. and ee parseInt() for Integer. n Step 3: (Wrapper class to DataType) Extract the data type from w. the wrapper class by converting the wrapper class to the data type using ww intValue()/floatValue() CKR Java Notes 209
  • 483. etc. member functions (abstract functions om of the Number class). There is also a booleanValue() .c function of DF the Boolean class which subclasses Object. II. Datatype to String. For the reverse process use either aP (a) concatenation with a string, using +, as in println or (b) convert datatype to a string, using vi the valueOf (datatype) ee function of the STRING class. n III. To convert Datatype to Wrapper class pass the datatype to the w. appropriate constructor of the Wrapper class. ww IV. Wrapper class to String: e.g. go via datatype */ CKR Java Notes 210
  • 484. import java.io.*; om public class Convert { public static void main (String args[]) throws IOException { .c int myInt = 2; long myLong = 40000; DF float myFloat = 2.01f; double myDouble = 2.01; byte myByte = 1; boolean myBoolean = true; aP BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); String str; vi System.out.println ("Enter a line of text" + "or data"); System.out.println ("Enter ’stop’ to" + ee "quit"); do { n //Step 1: Read in string. str = br.readLine(); w. // System.out.println (str); //Step 2: Convert the String to a ww //wrapper class. try CKR Java Notes 211
  • 485. { om Integer myInteger = new Integer (str); /*Or Integer myInteger = Integer.parseInt (str); */ //Step 3: Convert the wrapper class to int .c myInt = myInteger.intValue(); DF //Step 4: Convert the int to a string to //print System.out.println (" " + myInt); aP } catch (NumberFormatException e) { System.out.println ("Could not convert string to Integer"); vi } } while (!str.equals ("stop")); ee } } n w. ww CKR Java Notes 212
  • 486. Servlets om • A servlet is to a server what an applet is to a browser. .c – A servlet may be almost thought of as an applet which runs on a web server. DF • Formally, a servlet is a body of Java code that runs inside a network service, such as a web server. aP • A servlet helps to build interactive web based applications – by receiving and responding to requests vi from clients. • For example, a servlet may do the following ee tasks. • A servlet may process data POSTed by an HTTP n client, using an HTML form. w. – Such a servlet might work together with a database and an online payment system. ww • A servlet can also forward requests to other servers, to balance load between servers. CKR Java Notes 213
  • 487. Servles (contd) om • Since a servlet can handle multiple requests concurrently, i.e., it is multi-threaded, it can support systems like online conferencing/chat. .c • Since a servlet can dynamically generate HTTP responses DF – servlets serves as a replacement for CGI (Common Gateway Interface)scripts (server side scripting) used to generate aP web pages dynamically. • Servlets have some advantages over CGI vi – CGI uses the process model: with CGI a separate process is created for each client request. ee – Servlets handle multiple client requests using a thread model: so performance is n faster. w. – Full functionality of Java is available, including the security manager used to protect resources on the server. ww CKR Java Notes 214
  • 488. Servlets work with the Servlet API. om – This is a standard Java extension API . – Hence, unlike CGI, servlets may be run on different servers (which support .c servlets) in a platform independent way. DF – Many webservers support the servlet API. – These include Apache, iPlanet, and aP Microsoft IIS. – For a full list of third party products that run servlets, see vi http://java.sun.com/ products/servlets/ ee – For examples of real life servlet implementations try n – ecampus.com, SiliconInvestor.com etc. w. • Java has enhanced Servlet technology through Java Server Pages: JSP, which serves as a substitute for the proprietary ASP.. ww CKR Java Notes 215
  • 489. Servlets: initial preparations om • Preparations: To test and run servlets, one needs – The Java servlet development kit, which .c contains the requisite class libraries. – The servletrunner utility, which can be DF used to test servlets. • Step 1: Download and install the Java servlet development kit. aP • Step 2: Update the CLASSPATH variable, to include the path where the servlet class libraries are installed. E.g. vi set CLASSPATH=.;d:jdk1.2.2servletslibjsdk.jar ee • Step 3: Update the PATH variable to include the path in which the servletrunner utility is located. n E.g. w. set PATH=%path%;d:jdk1.2.2servletsbin • We can now start writing the first servlet program. ww CKR Java Notes 216
  • 490. Servlet Lifecycle om • Servlet lifecycle: A servlet is – initialised – provides service .c – is destroyed (depending upon server on which it is running) DF • Correspondingly,writing a servlet involves writing three key methods. – init – service aP – destroy • The init method is invoked exactly once for each servlet. vi • The service method is MULTITHREADED. – It is typically expected to concurrently ee handle requests from multiple clients. • The destroy method should n – typically undo whatever initialization has been performed, by closing files and w. database connections. – ensure that all service threads are ww complete before the servlet is destroyed. CKR Java Notes 217
  • 491. Hello Servlet om • All servlets must implement the servlet interface – either directly – or by extending a class which .c implements the interface. • The HelloServlet class extends GenericServlet, DF which is a class which implements the Servlet interface. Program 38 aP import java.io.*; import javax.servlet.*; vi public class HelloServlet extends GenericServlet { ee public void service (ServletRequest rq, ServletResponse rp) throws ServletException, IOException n { rp.setContentType ("text/html"); w. PrintWriter pw = rp.getWriter(); pw.println ("<B>Hello Servlet"); pw.close(); ww } } CKR Java Notes 218
  • 492. HelloServlet: Analysis of code om • The HelloServlet class implements only the service method. .c • The service method has the prototype public void service ( DF ServletRequest rq, ServletResponse rp); • involving the public interfaces, aP – Servlet Request and – ServletResponse vi • These interfaces incorporate a number of methods for handling MIME (Multipurpose Internet Mail Extension) bodies. ee • MIME bodies are either – text, or n – binary data w. • Correspondingly, one must – first get/set contentType ww – then get an Input/OutputStream or Reader and Writer CKR Java Notes 219
  • 493. MIME types om S. MIME type Origin No. 1 application/octet-stream Generic byte stream .c Adobe Acrobat portable 2. application/pdf document format files DF 3. application/postscript Postscript 4. application/rtf Rich text format 5. application/x-tex TeX 6. text/plain .txt, .c, .cpp, .java, .h etc, aP 7. text/html .htm, .html 8. image/gif .gif 9. image/jpeg JPEG vi 10. image/tiff TIFF 11. video/mpeg .mpg ee .mov or .qt Apple 12. video/quicktime QuickTime files 13. video/x-sgi-movie .movie Silicon Graphics n 14. audio/basic .snd or .au sound clip 15. audio/x-wav .wav file w. • More info: RFC 2045/2046. (RFC = Request for ww Comments. Many Internet standards are evolved in this way. MIME is an evolving standard. CKR Java Notes 220
  • 494. Hello Servlet: Analysis of code (contd) om • Thus, the HelloServlet class – first set the MIME type to text/html, since .c we want to output HTML, and – then gets a PrntWriter, using the DF getWriter method provided by the ServletResponse Interface • The page to be generated can is now written in aP standard HTML – More Info on HTML1.1: RFC2068 http://infor.internet.isi.edu:80/in-notes/ vi rfc/files/rfc2068.txt • The HTML code to be generated can be as ee complex or as simple as we want. – To generate this code we simply use the n various methods available with PrintWriter, such as the println method. w. – After completing the write, we close the stream through a call to the close ww method of PrintWriter. CKR Java Notes 221
  • 495. HelloServlet: Testing the code om • Step 1: Compile the code as usual. • (The javax package must be located so that it .c can be found using the set CLASSPATH. The default installation will put javax in the right directory. ) DF • Step 2: Start servletrunner. – PATH and CLASSPATH should have been set as described earlier. aP – servletrunner invoked with -h will provide help. vi –servletrunner invoked with -d will set the servlet directory servletrunner -d c:javakawa ee • Step 3: Start a webbrowser. n • Step 4: Request the servlet using the following URL w. http://localhost:80/servlet/HelloServlet or ww http://127.0.0.1:8080/servlet/HelloServlet • Output:Helloservlet in the browser. CKR Java Notes 222
  • 496. Servlets (contd) om • An IOException may be thrown by the call to the getWriter method. .c • The ServletException indicates a servlet problem. DF • The above servlet did not use the init or destroy methods. • The destroy method has the prototype aP public void destroy(); • The init method has the prototype vi public void init (ServletConfig cfg) throws ServletException ee • ServletConfig is a public interface, which defines various abstract methods like n getInitParameters( String name) getInitParameterNames() w. ServletContext getServletContext() • ServletContext is an interface with various ww useful methods, which enable one to get the MIME type, server name, real path etc,, for which check the documentation. CKR Java Notes 223
  • 497. Servlet architecture (summary) om • Thus, servlets involve the following interfaces • Servlet Interface .c – implemented by all servlets, directly or indirectly – defines the three key public methods DF – void init (ServletConfig cfg) – void service (ServletRequest rq, ServletResponse rp) – void destroy() aP • ServletRequest Interface – passed as an argument to the service method. vi – defines the getInputStream() and ee getReader() methods which return n – ServletInputStream, and w. BufferedReader objects, respectively. ww – ServletInputStream extends InputStream, and is used to handle binary data. CKR Java Notes 224
  • 498. ServletResponse Interface om – passed as an argument to the service method – defines the .c getOutputStream(), and getWriter() DF – methods which return ServletOutputStream, and PrintWriter aP objects, respectively. – ServletOutputStream extends OutputStream, and is used to handle vi binary data. • ServletConfig Interface and ServletContext ee Interface used to get various parameters associated with the servlet. n • SingleThreadModel Interface – This interface has no constants or w. methods. – A servlet implements this interface only to indicate that the service method of the ww servlet can handle only one client at a time. CKR Java Notes 225
  • 499. Servlets: initialization om • A servlet may be named, and initialization parameters may be provided for the servlet, in the .c – servlet.properties file • The default location for this file is in DF – servletsexamples, – i.e., in .examples relative to the directory in which servletrunner starts – to set it some other location, use the -p aP option with servletrunner • The sample servlet.properties file, provided by Sun, as part of the JDK, looks as follows (next vi page): – This is self-explanatory. – # is used for comments ee – The name of the servlet may be optionally set to something other than its class name through the line n servlet.<name>.code=codename (foo or w. foo.class) – the initial arguments may be provided by ww servlet.name.initArgs=pname1=pvalue1,pname 2=pvalue2 CKR Java Notes 226
  • 500. Sun’s sample servlet properties file om # @(#)servlets.properties 1.86 97/11/14 # # Servlets Properties .c # # servlet.<name>.code=class name (foo or #foo.class) DF # servlet.<name>.initArgs=comma-delimited #list of {name, value} pairs # that can be accessed by the servlet #using the aP # servlet API calls # # session servlet vi servlet.session.code=SessionServlet ee # simple servlet servlet.simpleservlet.code=SimpleServlet n # snoop servlet servlet.snoop.code=SnoopServlet w. # survey servlet servlet.survey.code=SurveyServlet ww servlet.survey.initArgs= resultsDir=/tmp CKR Java Notes 227
  • 501. Servlet initialization example om • These considerations are illustrated by the following sample code. Program 39 .c import java.io.*; import javax.servlet.*; DF public class GetProps extends GenericServlet { public void service (ServletRequest rq, aP ServletResponse rp) throws ServletException, IOException { ServletConfig sc = getServletConfig(); vi //first set content type rp.setContentType ("text/html"); ee //then get i/o stream PrintWriter pw = rp.getWriter(); n pw.println ("<B>State = </B"> + sc.getInitParameter("State") ) ; w. pw.println (" <BR><B>City = </B>" + sc.getInitParameter("City") ); ww pw.close(); }} CKR Java Notes 228
  • 502. Compile the code om • Add the following lines to the servlet.properties file #props servlet servlet.props.code=GetProps .c servlet.props.initArgs= State=M.P., DF City=Bhopal • Start servletrunner utility (remember -d for the servlet source files, and -p for the properties file) aP • Open a webbrowser, and request the URL http://localhost:8080/servlet/props vi • Output: State=M.P. ee City=Bhopal n w. ww CKR Java Notes 229
  • 503. Servlets: More examples om • Instead of overriding the GenericServlet class, it is often more useful to override the HttpServlet class, which is specially adapted to http actions, .c with methods like – doGet HTTP Get – doPost HTTP Post DF – doPut HTTP Put – doDelete HTTP Delete – doTrace HTTP Trace – doOptions HTTP Options aP – and – getLastModified • In this case, the service method has the vi prototype void service (HttpServletRequest rq, ee HttpServletResponse rp); • The use of these functions is illustrated by the n sample code given by Sun along with servlets. w. • The following code reads a form, and writes the results to file. ww • The key issue is the question of synchronization: hence the method implements the single thread model. CKR Java Notes 230
  • 504. code in file JDcSurvey.html om <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">r <html> <head> .c <title>JdcSurvey</title> </head> DF <body> <form action=http://localhost:8080/servlet/survey aP method=POST> <input type=hidden name=survey value=Survey01Results> <BR><BR>How Many Employees in your vi Company?<BR> <BR>1-100<input type=radio name=employee value=1-100> ee <BR>100-200<input type=radio name=employee value=100-200> <BR>200-300<input type=radio n name=employee value=200-300> <BR>300-400<input type=radio w. name=employee value=300-400> <BR>500-more<input type=radio name=employee value=500-more> ww <BR><BR>General Comments?<BR> <BR><input type=text name=comment> <BR><BR>What IDEs do you use?<BR> CKR Java Notes 231
  • 505. <BR>JavaWorkShop<input om type=checkbox name=ide value=JavaWorkShop> <BR>J++<input type=checkbox name=ide value=J++> <BR>Cafe’<input type=checkbox name=ide value=Cafe’> .c <BR><BR><input type=submit><input type=reset> DF </form> </body> </html> aP vi n ee w. ww CKR Java Notes 232
  • 506. /* om * @(#)SurveyServlet.java * * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved. * .c */ import java.io.*; DF import java.util.*; import javax.servlet.*; import javax.servlet.http.*; aP /** * A sample single-threaded servlet that takes input from a form vi * and writes it out to a file. It is single threaded to serialize * access to the file. After the results ee are written to the file, * the servlet returns a "thank you" to the user. n * * <p>You can run the servlet as provided, w. and only one thread will run * a service method at a time. There are no thread synchronization ww * issues with this type of servlet, even though the service method * writes to a file. (Writing to a file CKR Java Notes 233
  • 507. within a service method om * requires synchronization in a typical servlet.) * * <p>You can also run the servlet without using the single thread .c * model by removing the <tt>implements</tt> statement. Because the DF * service method does not synchronize access to the file, multiple * threads can write to it at the same time. When multiple threads try aP * to write to the file concurrently, the data from one survey does not * follow the data from another survey in an orderly fashion. vi * * <p>To see interaction (or lack of interaction) between threads, use ee * at least two browser windows and have them access the servlet as * close to simultaneously as possible. n Expect correct results (that * is, expect no interference between w. threads) only when the servlet * implements the <code>SingleThreadedModel</code> interface. ww */ CKR Java Notes 234
  • 508. om public class SurveyServlet extends HttpServlet implements SingleThreadModel { String resultsDir; .c public void init(ServletConfig config) DF throws ServletException { super.init(config); resultsDir = aP getInitParameter("resultsDir"); if (resultsDir == null) { Enumeration initParams = getInitParameterNames(); vi System.err.println("The init parameters were: "); while (initParams.hasMoreElements()) { ee System.err.println(initParams.nextElement()) ; } n System.err.println("Should have seen one parameter name"); w. throw new UnavailableException (this, "Not given a directory to write survey results!"); ww } } CKR Java Notes 235
  • 509. /** om * Write survey results to output file in response to the POSTed * form. Write a "thank you" to the client. */ .c public void doPost(HttpServletRequest req, HttpServletResponse res) DF throws ServletException, IOException { // first, set the "content type" header of the response aP res.setContentType("text/html"); //Get the response’s PrintWriter to return text to the client. vi PrintWriter toClient = res.getWriter(); ee try { //Open the file for writing the survey results. n String surveyName = req.getParameterValues("survey")[0]; w. FileWriter resultsFile = new FileWriter(resultsDir + ww System.getProperty("file.separator") + surveyName + ".txt", true); PrintWriter toFile = new CKR Java Notes 236
  • 510. PrintWriter(resultsFile); om // Get client’s form data & store it in the file toFile.println("<BEGIN>"); Enumeration values = .c req.getParameterNames(); DF while(values.hasMoreElements()) { String name = (String)values.nextElement(); String value = aP req.getParameterValues(name)[0]; if(name.compareTo("submit") != 0) { toFile.println(name + vi ": " + value); } } ee toFile.println("<END>"); //Close the file. n resultsFile.close(); w. // Respond to client with a thank you toClient.println("<html>"); toClient.println("<title>Thank ww you!</title>"); toClient.println("Thank you for participating"); CKR Java Notes 237
  • 511. toClient.println("</html>"); om } catch(IOException e) { e.printStackTrace(); toClient.println( "A problem occured while recording your .c answers. " + "Please try again."); DF } // Close the writer; the response is done. aP toClient.close(); } } vi n ee w. ww CKR Java Notes 238
  • 512. Elements of Java GUI om • GUI programmingn is event-based. • An event is a change of state in a source. .c • A source of events can be – keyboard DF – mouse – internal state of the machine, such as a clock, – a programme, when it completes some aP job. • Hence, GUI programming needs an event model . vi • Java 1.0, 1.1 and 1.2 have used somewhat different approaches. ee • It is necessary to understand the earlier approach, since – most of the programmer’s time is spent n in maintaining code, rather than in developing code. w. • Legacy code uses the Java 1.0 model. ww CKR Java Notes 239
  • 513. Java GUI elements om • The GUI elements such as – buttons – lists .c – icons – scroll panes – menus DF • are all Windows. • Java’s problem is to model these Windows in a aP platform independent way. • Java being object oriented, all these elements are modeled using classes and objects. vi • These elements are intuitively seen as components put within a container. ee – However, in Java the Component class is at the top of the awt hierarchy, and Container is a subclass. n • Also, intuitively one tends to think of a Frame as w. a rectangular box, with nothing in it, and one thinks of a Window as something which has a title, can be resized etc. ww • This terminology is reversed in Java, with Window being the rectangular box, and Frame CKR Java Notes 240
  • 514. being a subclass with title bar etc. om • Applets are an important aspect of Java. • Applets are subclasses of Panel, which is a concrete implementation of the abstract .c Container class. DF Component aP Container vi Window ee Panel n Frame w. ww CKR Java Notes 241
  • 515. Java event models om • The key difference between the two event models is this. .c • In the 1.0 event model, the GUI elements were stacked hierarchically, and DF – any event was despatched to all elements. • A GUI element could handle the event if it so aP desired, or it could ignore it. • This method was found to be inefficient and time-consuming. vi • Accordingly, the 1.1 model adopts the usual MS-Windows technique: ee • A GUI must notify all event sources, by registering an event handler. n • Events are then despatched only to registered w. handlers. • Such event handlers are called listeners ww • The model is known as the Delegation Event Model. CKR Java Notes 242
  • 516. a user interface element is able to om delegate the processing of events to a separate piece of code. • The source which generates the event sends to each registered listener, .c • Some events may not be handled by more than a DF specified number of listeners. – In this case registering an additional listener leads to an exception. aP • Like UI elements, Events too are modeled by classes and objects. • EventObject is the superclass of all events vi • AWTEvent is the superclass of all AWT events. ee • Various types of events are defined – ActionEvent (when a button is pressed, n or a list or menu item is selected) w. – ItemEvent (when a checkbox or list item is clicked, or a choice is made etc.) ww – AdjustmentEvent (when a scroll bar is manipulated) CKR Java Notes 243
  • 517. ComponentEvent (when a component om changes its state and becomes visible or is hidden or moved or resized etc.) – ContainerEvent (when a component is added or removed from a container) .c – KeyEvent (when input is received from DF the keyboard) – MouseEvent (when the mouse is moved, or clicked, or dragged etc.) aP – TextEvent (when the text in a TextField or TextArea is changed) vi – WindowEvent (when a Window is closed, minimised etc.) ee • Corresponding to this there are listener interfaces. – ActionListener for ActionEvents n – ItemListener for ItemEvents – AdjustmentListener for w. AdjustmentEvents – ComponentLIstener – ContainerListener ww – KeyListener – MouseListener – TextListener, etc. CKR Java Notes 244
  • 518. Java GUI (contd) om • These considerations are illustrated by the following examples. .c Program 40 /*An applet illustrating the 1.0 event model */ DF import java.applet.*; import java.awt.*; aP public class SillyButton extends Applet { public void init() { vi //add two buttons labeled red and blue add (new Button ("Red")); add (new Button ("Blue")); ee } //older action method is deprecated n public boolean action (Event evt, Object w. act) { //check nature of event ww if (!(evt.target instanceof Button)) { return false; CKR Java Notes 245
  • 519. } om String btLabel = (String)act; if (btLabel == "Red") { setBackground (Color.red); .c } else if (btLabel == "Blue") DF { setBackground (Color.blue); } aP repaint(); //show changed background return true; } } vi n ee w. ww CKR Java Notes 246
  • 520. Program 41 om /*This applet illustrates the revised Java 1.1 event model which has been carried over into Java 1.2 */ import java.applet.*; .c import java.awt.*; import java.awt.event.*; DF class BackSet extends Object implements ActionListener aP { Component cmp; Color clr; //define constructor vi BackSet(Component cmp, Color clr) { this.cmp = cmp; ee this.clr = clr; } n public void actionPerformed (ActionEvent evt) w. { cmp.setBackground (clr); cmp.repaint(); ww } } CKR Java Notes 247
  • 521. public class SillyButton2 om extends Applet { public void init() { Button red = new Button ("Red"); .c add (red); red.addActionListener DF (new BackSet (this, Color.red)); Button blue = new Button ("Blue"); add (blue); aP blue.addActionListener (new BackSet (this, Color.blue)); } vi } n ee w. ww CKR Java Notes 248
  • 522. Choice om • The following program illustrates an applet which uses a choice. The choices are grouped to make them mutually exclusive. .c Program 42 import java.applet.*; import java.awt.*; DF import java.awt.event.*; public class SillyChoice extends Applet aP { static char ch=’B’; public void init() { vi //create a choice menu Choice c = new Choice(); ee //add items to menu c.addItem ("Red"); c.addItem ("Blue"); n c.addItem ("Green"); w. //mark one item as selected c.select ("Blue"); ww //add choice to applet add (c); CKR Java Notes 249
  • 523. om //create an ItemListener object ItemListener l = new chkItemListener(); //add a listener interface to each .c //checkbox DF c.addItemListener(l); } aP public void paint(Graphics g) { switch (ch) { vi case ’R’: setBackground (Color.red); break; case ’B’: setBackground (Color.blue); ee break; case ’G’: setBackground (Color.green); break; n default: break; } w. repaint(); } ww } //define an item listener CKR Java Notes 250
  • 524. //ItemListener is an abstract interface om //to implement which, one method must be //defined. //This method decides what is done when //a certain checkbox is selected class chkItemListener .c implements ItemListener { DF public void itemStateChanged (ItemEvent evt) { aP if (evt.getStateChange() == ItemEvent.SELECTED) { vi Choice cb = (Choice) evt.getItemSelectable(); String sb = new String ee (cb.getSelectedItem()); SillyChoice.ch = sb.charAt (0); /*alternatively use int ch in place of n char ch and use w. SillyChoice.ch=cb.getSelectedIndex() 0=Red, 1=Blue, 2=Green etc. */ ww } } } CKR Java Notes 251
  • 525. Check boxes and Radio buttons om /* Grouping checkboxes makes them radio buttons */ .c import java.applet.*; import java.awt.*; DF import java.awt.event.*; public class SillyRadio aP extends Applet { static char ch=’B’; public void init() vi { //create a group CheckboxGroup cbg = new CheckboxGroup(); ee //create checkboxes, state, to group Checkbox cb1 = new Checkbox ("Red", false, n cbg); Checkbox cb2 = new Checkbox ("Blue", true, w. cbg); Checkbox cb3 = new Checkbox ("Green", false, cbg); ww //add checkboxes to applet CKR Java Notes 252
  • 526. add (cb1); om add (cb2); add (cb3); //create an ItemListener object .c ItemListener l = new chkItemListener(); DF //add a listener interface to each //checkbox cb1.addItemListener(l); aP cb2.addItemListener (l); cb3.addItemListener (l); } vi public void paint(Graphics g) { switch (ch) ee { case ’R’: setBackground (Color.red); break; n case ’B’: setBackground (Color.blue); break; w. case ’G’: setBackground (Color.green); break; default: break; ww } repaint(); } CKR Java Notes 253
  • 527. } om //define an item listener //ItemListener is an abstract interface //to implement which, one method must be //defined. .c //This method decides what is done when //a certain checkbox is selected DF class chkItemListener implements ItemListener { aP public void itemStateChanged (ItemEvent evt) { vi if (evt.getStateChange() == ItemEvent.SELECTED) { ee Checkbox cb = (Checkbox) evt.getItemSelectable(); String sb = new String (cb.getLabel()); n SillyRadio.ch = sb.charAt (0); } w. } } ww CKR Java Notes 254
  • 528. Lists as applications om Program 43 /*This runs as both an application and an applet*/ .c import java.applet.*; import java.awt.*; import java.awt.event.*; DF class SillyList extends Applet aP { static int ti; static int [] si = new int[3]; List l; vi public void init() { //create a List with 3 elements ee //permitting multiple selections //the default constructor does //not permit multiple selections n l = new List(3, true); w. //add items to list //note that the function is add ww //not addItem //The addItem function still exists //but is deprecated CKR Java Notes 255
  • 529. om l.add ("Red"); l.add ("Blue"); l.add ("Green"); //mark two items as selected .c l.select (1); l.select (0); DF //if the list does not permit //multiple selections //then the second call aP //will de-select //make a selected item visible vi l.makeVisible (1); //add list to applet ee add (l); n //create an ItemListener object w. ItemListener ls = new chkItemListener(); ww //add a listener interface to each //checkbox CKR Java Notes 256
  • 530. l.addItemListener(ls); om } public void paint (Graphics g) { .c for (int i=0; i<= 3; i++) if (l.isIndexSelected(i) ) DF g.drawString ("Selected " + i, 10, 30+20*i); //repaint(); //don’t call this //resize the applet to force aP //repaint() } } vi ee //define an item listener //ItemListener is an abstract interface //to implement which, one method must be n //defined. //This method decides what is done when w. //a certain list box item is selected class chkItemListener implements ItemListener ww { public void itemStateChanged CKR Java Notes 257
  • 531. (ItemEvent evt) om { if (evt.getStateChange() == p ItemEvent.SELECTED) { .c List lb = (List) evt.getItemSelectable(); //Note the plural in the next line DF SillyList.si = lb.getSelectedIndexes(); SillyList.ti = lb.getSelectedIndexes().length; aP } } } vi public class SillyListApplication { public static void main (String args[]) ee { //create a Frame object Frame f = new Frame ("Applet as an n application"); w. //create an applet object SillyList sl = new SillyList(); ww //add applet to frame f.add (sl); CKR Java Notes 258
  • 532. //set size of frame and om f.setSize (100, 120); //make frame visible f.show(); .c //call the applets methods sl.init(); DF sl.start(); //add a listener to make the //windows close work aP //using an inner class f.addWindowListener ( /*WindowListener is an abstract interface vi which extends EventListener. However we do not want ee to implement all methods in this interface. Hence we choose an Adapter class with empty n methods and override the method of interest*/ w. new WindowAdapter() { public void windowClosing ww (WindowEvent wevt) { System.exit(0); CKR Java Notes 259
  • 533. } //end of method def om }//end of inner class def ); //end of listener def } //end of main } //end of SillyList class def .c DF aP vi n ee w. ww CKR Java Notes 260
  • 534. Networking om • The key networking classes are in the package java.net .c • The package aims to facilitate communication across the network using – HTTP DF – TCP/IP – UDP (Datagrams) • Corresponding classes are provided. aP – InetAddress – URL – Socket (client socket) – ServerSocket vi – DatagramSocket – DatagramPacket ee • The following programs demonstrate the use of these classes. n Getting an Internet address: Factory methods w. • To get an IP address we use the InetAddress class. ww • The InetAddress class has no visible constructors. CKR Java Notes 261
  • 535. An object of the class must be constructed using om one of the so-called "factory methods" – A factory method is merely a convention where a static method in a class returns an instance of the class. .c – Factory methods are substitutes for overloaded constructors. DF – In the case of InetAddress, factory methods are more appropriate than constructors: one gets an address. aP • Some of these factory methods are – getLocalHost() vi – getByName() – getAllByName() ee • These methods have the prototypes static InetAddress getLocalHost() throws n UnknownHostException w. static InetAddress getByName (String hostName) throws Unknown HostException ww static InetAddress[]getAllByName (String hostName) throws UnknownHostException CKR Java Notes 262
  • 536. The following program demonstrates the use of om these factory methods. Program 44 import java.net.* ; class InetTest { public static void main(String args[]) .c throws UnknownHostException { InetAddress Address = DF InetAddress.getLocalHost(); System.out.println("local host: " + Address); Address = aP InetAddress.getByName("msn.com"); System.out.println ("msn.com" + Address); InetAddress MSN[] = InetAddress.getAllByName ("www.msn.com"); vi for (int i=0; i MSN.length; i++) System.out.println ("www.msn.com" + MSN[i]); ee } } • output: localhost: 127.0.0.1 msn.com: 207.46.176.152 n www.msn.com: 207.46.185.138 www.msn.com: 207.46.185.140 w. www.msn.com: 207.46.209.218 www.msn.com: 207.46.209.243 www.msn.com: 207.46.179.134 ww www.msn.com: 207.46.179.143 www.msn.com: 207.46.179.71 Application Exit... CKR Java Notes 263
  • 537. Getting a URL om • A URL is a Uniform Resource Locator: a pointer to a resource on the web. .c • A "resource" may be – a file – a directory, DF – a query to a database – or other information generated on the fly. • The public final class URL encapsulates a URL. aP • To get a URL, we use the URL class. • The URL class has several constructors vi • The simplest constructor uses a URL specified by means of a string. ee URL (String urlSpecifier); n • We can also break up the URL into its components, and specify w. – the protocol – the host name – the port name (optional) ww – path to obtain a URL object. CKR Java Notes 264
  • 538. That is, we can also use the following two om constructors. URL (String protocolName, String hostName, int portNumber, .c String path) DF URL (String protocolName, String hostName, String path) aP • The following program builds a URL object from the string form of the URL vi n ee w. ww CKR Java Notes 265
  • 539. Program 45 om import java.net.*; class URLTest { public static void main (String args[]) throws MalformedURLException { URL url = new URL .c ("http://www.hotmail.com"); System.out.println("Protocol: " + DF url.getProtocol()); System.out.println ("Port: " + url.getPort()); System.out.println ("Host: " + aP url.getHost()); System.out.println ("File: " + url.getFile()); System.out.println ("String: " + vi url.toString()); } } ee • Output: Protocol: http n Port: -1 (getPort returns - 1 if port not explicitly set) w. Host: www.hotmail.com File: / String: http: //www.hotmail.com/ ww CKR Java Notes 266
  • 540. Connecting to a URL om • Once we have created a URL object we can connect to it using the – openConnection method. .c • This method returns an object of the – URLConnection class DF • Once we have connected to a URL, we can query its properties, using methods (of the URLConenction class) such as – getDate() aP – getLastModified() – getContentType() – getContentLength() vi • A URL connection can be used for input and output. ee • Having connected to a URL we can also read from it, using – getInputeStream method n which returns an InputStream object from which we can read and write using standard i/o techniques. w. • We can also write to the URL, using the – getOutputStream method ww and standard i/o techniques to the OutputStream object that it returns. CKR Java Notes 267
  • 541. Connecting to a URL and transferring a file om import java.net.*; import java.io.*; import java.util.Date; class UConnect { .c public static void main (String args[]) throws Exception //so declared, to avoid DF //exception handling logic { int c=0; URL url = new aP /*URL("http://www.ncsa.uiuc.edu/demoweb/url- primer.html"); */ //no more accessible URL( vi "http://www.w3.org/Addressing/URL/url-spec.t xt"); URLConnection urlCon = ee url.openConnection(); System.out.println ("Date: " + new Date (urlCon.getDate() )); n System.out.println ("Content type: " + urlCon.getContentType()); w. System.out.println ("Last Modified: " + new Date (urlCon.getLastModified()) ); int len = urlCon.getContentLength(); ww System.out.println ("Content length: " + len); CKR Java Notes 268
  • 542. if (len == 0 ) om { System.out.println ("No content to transfer"); return; } .c if (len == -1) { DF System.out.println ("Content length not known"); } InputStream in = aP urlCon.getInputStream(); FileOutputStream fout = new FileOutputStream ("c:kawaurl-spec.txt"); vi while ( ((c=in.read()) != -1) ) { fout.write(c);} ee in.close(); fout.close(); } } n • Output w. Date: Wed Jun 13 06:34:31 GMT+05:30 2001 Content type: text.plain; Last Modified: Thu Mar 31 20:18:08 GMT+05:30 ww 1994 Content length: 46204 CKR Java Notes 269
  • 543. Sockets om • A URL is for relatively high-level communication. • Sometimes one must communicate with another .c machine at a lower level. • For this, one uses sockets. DF • The socket concept was evolved with BSD Unix. • The purpose of sockets is to permit aP inter-process communication. • A socket is one end of such an inter-process communication. vi • Thus, a socket is like a telephone instrument which permits two persons to talk to each other. ee • A socket may concurrently handle several processes. n • Thus, a more precise analogy is that a socket is w. like an EPABX: – there is only one telephone number – But there are several lines, so that ww – several people can simultaneously converse using that one number. CKR Java Notes 270
  • 544. Sockets (contd) om • More precisely, a socket is one endpoint of a two-way communication link between two processes (running on a computer or a network). .c – A socket is tied to a port number (to enable the TCP layer to identify the DF application with which data is being exchanged). • From the user point of view, to create a socket, aP or communicate with a socket one needs – the IP address vi – the port number – An InputStream/OutputStream object or ee BufferedReader/PrintWriter object. – Communication is subsequently like n normal i/o via the i/o object. w. • The IP address must be specified by the programmer or the user. ww CKR Java Notes 271
  • 545. The port number depends upon the service. om • For example: – FTP: 21 – Telnet: 23 .c – SMTP: 25 (Simple Mail Transfer Protocol) – Timeserver: 37 DF – Nameserver: 42 – Whois: 43 – MTP: 57 – HTTP: 80 aP – Servlets: 8080 • For more details on Port Numbers, see RFC 1700. vi • The java.net package contains various classes encapsulating sockets in a platform independent ee way. • A key class which the programmer will use is the n class Socket, which implements client sockets. w. • (For serverside-sockets there is a separate class called ServerSockets) ww CKR Java Notes 272
  • 546. Sockets (contd) om • The Socket class has several constructors, one of which has the following prototype: .c public Socket (InetAddress address, int Portno) throws IOException DF • The uses of this constructor are demonstrated in the following example which sends email, using SMTP. aP • (For more details on SMTP see RFC 821.) Program 46 /*Program EMail.java vi Function: to send email across a socket*/ import java.net.*; ee import java.io.*; public class EMail n { public static void main (String args[]) w. throws Exception { Socket s; ww //InetAddress Address = InetAddress.getByName ("mail.hotmail.com"); InetAddress Address = CKR Java Notes 273
  • 547. InetAddress.getByName ("mail.vsnl.net"); om System.out.println ("Address: " + Address); try { s = new Socket (Address, 25); //Port 25 is for SMTP: Simple Mail Transfer Protocol .c } DF catch (Exception e) { System.out.println ("Error opening socket"); aP return; } System.out.println ("Opened socket"); if (s==null) { return; } vi try{ ee PrintWriter out = new PrintWriter ( new OutputStreamWriter (s n .getOutputStream()), true); BufferedReader in = new w. BufferedReader ( new InputStreamReader ( s. getInputStream() )); ww if (out==null || in==null) {System.out.println ("Failed to open stream to socket"); CKR Java Notes 274
  • 548. return; om } String hostName = InetAddress.getLocalHost().getHostName(); //String hostName = "Ghost"; .c System.out.println ("Obtained i/o stream"); String initID = in.readLine(); DF System.out.println (initID); out.println ("HELO " + hostName); System.out.println ("HELO " + hostName); aP String resp = in.readLine(); System.out.println (resp); vi out.println ("MAIL FROM:<"+ "c_k_raju@hotmail.com"+">"); ee String senderOK = in.readLine(); System.out.println (senderOK); n out.println ("RCPT TO:<" + "c_k_raju@vsnl.net"+">"); w. String recptOK = in.readLine(); System.out.println (recptOK); ww out.println ("DATA"); out.println ("The quick brown fox has sent CKR Java Notes 275
  • 549. you mail"); om out.println ("."); out.flush(); s.close(); } catch (IOException ex) .c { System.out.println ("IO Exception"); DF } } } aP • Output: Address: mail.vsnl.net/203.197.12.5 vi Opened socket Obtained i/o stream 220 mail02.vsnl.net ESMTP service ee (Netscape Messaging Server 4.15 Patch 2 (built May 30 2000)) HELO c n 250 mail02.vsnl.net 250 Sender <c_k_raju@hotmail.com> Ok w. 250 Recipient <c_k_raju@vsnl.net> Ok Application Exit... ww CKR Java Notes 276
  • 550. JDBC om • JDBC stands for Java Data Base Connectivity. • JDBC is different from ODBC in that .c – JDBC is written in Java (hence is platform independent, object oriented robust etc.), while DF – ODBC is written in C, is not object oriented. aP • However, both JDBC and ODBC are based on the X/Open SQL Command Level Interface (CLI). • Sun provides a JDBC ODBC bridge, which vi enables one to connect painlessly to ODBC data sources. ee • The following steps are involved. • Step 1: Set up a Data Source Name, using the n ODBC administrator. – It is assumed that you already know how w. to do this. – The following example used Oracle 8 ww Personal Edition, setting up a Data Source Name called Test on the local computer. CKR Java Notes 277
  • 551. But this would work just as well with om Access or DBase or FoxPro. • Step 2: Load and Register the JDBC driver. – The following example supposes that .c one is using the jdbc-odbc bridge driver supplied by sun. DF – Loading and registering the driver is done using the single statement. aP Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); • java.lang.Class is a public final class which vi descends directly from java.lang.Object (and implements Serializable) ee • The forName method of class Class has the following prototype n public static Class forName (String className) throws ClassNotFoundException w. • The exception is thrown if the class representing the driver is not found. ww • For the class name of other drivers, check the driver documentation. CKR Java Notes 278
  • 552. JDBC (contd) om • Step 3: Connect to the database. Once the driver has been loaded, one must connect to the database (specified in the DSN) .c • This is again achieved using a single statement DriverManager.getConnection( DF url, user_login, user_password) aP • DriverManager is a public class which extends Object. – This class is located in the java.sql package. vi • getConnection is a public static method of the DriverManager class, with the following prototype ee public static Connection getConnection (String url, String user, String password) n throws SQLException w. • This method is appropriately overloaded. – example one overloaded version will take only the url, for databases which do ww not have a user login or user password (such as DBaseIII) CKR Java Notes 279
  • 553. The meaning of user_login and user_password om is obvious. • String url is specified as follows: "jdbc:subprotocol:DSN" .c • For the present case of ODBC, if the Data Source Name is Test, the url would be specified as DF "jdbc:odbc:Test" • Connection is an interface defined in the aP java.sql package. • Step 4: Create an SQL statement. vi • This is done using the createStatement method of the Connection object returned by the getConnection method of Step 3. ee • The createStatement method (appropriately overloaded) has a prototype n public Statement createStatement () throws SQLException() w. • Statement is an interface defined in the java.sql package: ww – it is intended to represent an SQL statement. CKR Java Notes 280
  • 554. JDBC (contd) om • Step 5: Execute a given SQL statement – using the executeUpdate method of the Statement object .c – returned by createStatement method in Step 4. DF • Step 6: Close – the statement, and – the connection. – using the respective close methods. aP • This is demonstrated by the following example, which sets up a connection to a DSN called Test, and uses a simple SQL statement to create a vi table called TEAS. Program 47 ee import java.sql.*; public class JDBCMakeTea { n public static void main (String args[]) { w. String myDriverName = "sun.jdbc.odbc.JdbcOdbcDriver"; //the above is the fully qualified name of ww the sun //jdbc-odbc bridge driver class. CKR Java Notes 281
  • 555. String url = "jdbc:odbc:test"; om //the above string has the form //protocol:subprotocol:datasourcename //Thus test is the user DSN specified //in the ODBC administrator .c String myLogin = "DEMO"; //user name String myPassword = "demo"; //password DF String sqlString = "create table TEAS " + "(TEA_NAME VARCHAR (32), " + aP "SUP_ID INTEGER, " + "PRICE FLOAT, " + "SALES INTEGER, " + "TOTAL INTEGER)"; vi try { ee Class.forName (myDriverName); //the forName method of java.lang.Class //will load and register the driver. n } w. catch (ClassNotFoundException e) { ww System.err.println ("Error loading driver"); return; CKR Java Notes 282
  • 556. } om try { Connection con = DriverManager.getConnection .c (url, myLogin, myPassword); //connect to database DF Statement stmt = con.createStatement(); stmt.executeUpdate (sqlString); aP stmt.close(); con.close(); } vi catch (SQLException ex) { ee System.err.println ("SQLException " + ex.getMessage()); } n } } w. • Output: if no error messages – a table called teas is created under the ww database connection called Test. CKR Java Notes 283
  • 557. JDBC: Executing a query om • To summarise: the basic procedure is – set up a DSN .c – Load and Register the JDBC driver – Connect to the DSN – Create a SQL statement DF – execute the SQL statement – close the statement and the connection. • To execute a query a change is required only in aP Step 5. – Instead of the executeUpdate method used to execute a SQL statement, we will vi use the executeQuery method of the statement object. ee – The executeUpdate method, returns an int, and so is restricted to INSERT, UPDATE and DELETE statements, n – or SQL statements that return nothing w. such as SQL DDL (Data Definition Language) statements, such as CREATE, ALTER, DROP ww CKR Java Notes 284
  • 558. A query however, returns a result set. om – A result set is encapsulated in the interface ResultSet of the java.sql package. .c • A ResultSet object maintains a cursor pointing to the current row of data. DF – It is initially set to point before the first row. aP • The next method of the ResultSet object moves the cursor to the next row. • Various getXXX methods return the values of the vi columns in the ResultSet. • These considerations are illustrated by the ee following program. Program 48 n import java.sql.*; w. public class JDBCAddTea { public static void main (String args[]) ww { String myDriverName = "sun.jdbc.odbc.JdbcOdbcDriver"; CKR Java Notes 285
  • 559. //the above is the fully qualified name of om the sun //jdbc-odbc bridge driver class. String url = "jdbc:odbc:test"; //the above string has the form .c //protocol:subprotocol:datasourcename6 //Thus test is the user DSN specified DF //in the ODBC administrator String myLogin = "DEMO"; //user name String myPassword = "demo"; //password6 aP String sqlString; Connection con; //Connection is an interface vi Statement stmt; //Statement is an interface try ee { Class.forName (myDriverName); //the forName method of java.lang.Class n //will load and register the driver. w. } catch (ClassNotFoundException e) ww { System.err.println ("Error loading driver"); CKR Java Notes 286
  • 560. return; om } try { con = .c DriverManager.getConnection (url, myLogin, myPassword); DF //connect to database stmt = con.createStatement(); //so far this is standard for any aP //JDBC program. //we now change the sql command. sqlString = "insert into TEAS " + vi "values (’Darjeeling’, 201, 400.5, 0, 0)"; stmt.executeUpdate (sqlString); ee sqlString = "insert into TEAS " + n "values (’Assam’, 202, 56.3, 0, 0)"; w. stmt.executeUpdate (sqlString); sqlString = ww "insert into TEAS " + "values (’Nilgiri’, 203, 100.5, 0, 0)"; CKR Java Notes 287
  • 561. stmt.executeUpdate (sqlString); om sqlString = "insert into TEAS " + "values (’Sri Lanka’, 501, 200.4, 0, 0)"; .c stmt.executeUpdate (sqlString); DF //We now execute a query String query = "select TEA_NAME, PRICE from TEAS"; aP //The results of the query are put into //an object of type result set. //ResultSet is an interface in java.sql vi ResultSet rs = stmt.executeQuery (query); ee System.out.println ("Tea Break: Teas and their prices: "); n while (rs.next()) w. { String s = rs.getString ("TEA_NAME"); float f = rs.getFloat ("PRICE"); ww System.out.println (s + " " + f); } CKR Java Notes 288
  • 562. //now put in the standard JDBC om //closing process. stmt.close(); con.close(); } .c catch (SQLException ex) { DF System.err.println ("SQLException " + ex.getMessage()); } } aP } • Output: vi Tea Break: Teas and their prices: Darjeeling 400.5 ee Assam 56.3 Nilgiri 100.5 Sri Lanka 200.4 n w. ww CKR Java Notes 289
  • 563. JDBC: New Features of the Java 2.0 API om • Certain new features are incorporated in the JDBC API available with JDK1.2 .c • ResultSets are scrollable both backward and forward. DF – In JDK 1.0 one could only move forward using the next() method. – We now have the previous() aP absolute(int) relative (int) methods, along with other methods. vi – One can now declare the ResultSet to be of type TYPE_FORWARD_ONLY ee TYPE_SCROLL_INSENSITIVE (changes are not reflected while the result set is open) n TYPE_SCROLL_SENSITIVE (changes are reflected immediately) w. • Updates can be made to database tables using Java API methods instead of using SQL ww commands. CKR Java Notes 290
  • 564. For example insertRow() method will om insert a row in the present location. • Multiple SQL statements can be sent to the database, as a unit or a batch. .c • The new SQL3 datatypes can be used as column values. DF – These include BLOB (Binary Large Object) CLOB (Character Large Object) Array aP Struct to map SQL user defined types. • For further information on using these methods, vi consult the API documentation. n ee w. ww CKR Java Notes 291
  • 565. Remote Method Invocation om • So far, all applications have been running on one (local) Java Virtual Machine. .c • The RMI technology makes it possible to have an object distributed across JVM’s. DF • RMI applications typically take the form of client-server applications. • When combined with the standard polymorphic aP features, this can lead to a situation where – a fast server executes a task – which it does not know about at compile time. vi • The following program provides an example of how this "RMI magic" is achieved. ee • Basically, the server downloads from the client, the byte code of the class to be executed. n • After completing execution, it uploads the code w. back again. • This is done in a platform independent way. ww • It is also done in a secure way, as follows. CKR Java Notes 292
  • 566. RMI: Security om • Due attention has to be paid to the security aspects. .c • An RMI program will NOT run, until a security manager has been installed, – and a policy file has been created DF – with the appropriate permissions. • A security manager is installed through a single line of code: aP System.setSecurityManager (new RMISecurityManager()); vi • The policy file typically has the name – java.policy – and is located in the C:windows file ee – but could be located anywhere. • A sample file is provided in JRElibjava.policy. n • This file may be edited with the policytool w. which is a part of the JDK. – and the appropriate permissions must ww be granted. CKR Java Notes 293
  • 567. RMI: Stubs and Skeletons om • Classes capable of being invoked remotely have stubs and skeletons. .c • Stubs and Skeletons are surrogates (proxies) – Stubs are client side, and – Skeletons are server side DF surrogates (proxies) for RMI capable classes. • From Java 1.2 onwards, Skeletons are no longer used. Related methods are fully deprecated, with aP no substitute. • However, stubs and skeletons must still be generated, vi – for backward compatibility with Java 1.1, which may be running on the remote machine. ee • Stubs and skeletons are generated from the compiled classes by using the Java rmi n compiler tool – rmic w. which is part of the JDK toolkit. • (This tool is to be used after javac has been used ww to compile the program and create the relevant classes. ) CKR Java Notes 294
  • 568. RMI: registration om • Before an RMI class can be invoked, it must be – (a) started – (b) registered in a special registry called .c the RMI registry. • This is achieved through DF – API calls, and – the rmiregistry tool The foregoing considerations are illustrated by the aP following example. vi n ee w. ww CKR Java Notes 295
  • 569. RMI: Example om • This example creates a server process which – accepts tasks from clients – returns the results to the clients. .c • The server process involves three pieces of code. DF • (1) an interface definition – interface RMIdoTask – in package rmitask aP • (2) a second interface used in the first interface – interface Task – in package rmitask. vi • (3) an implementation of the interface defined in the code in (1) above. ee – class MyRMI – in package rmiclass. n • The client process involves two pieces of code. w. • (4) A class Pi which implements the interface Task – and knows how (has a method ) to ww calculate the value of Pi. • (5) A class CalcPI which invokes the remote method. CKR Java Notes 296
  • 570. RMI Example (contd): RMIDoTask.java om • Step 1: Define the first remote interface . • The key idea is that a remotely accessible object .c must extend the interface java.rmi.Remote. • The code is as follows. DF • File: rmitask/RMIDoTask.java package rmitask; aP import java.rmi.Remote; import java.rmi.RemoteException; //all remotely accessible interfaces must vi //have the above two import statements. //An object declares itself as Remote //by extending java.rmi.Remote. ee public interface RMIDoTask extends Remote n { Object doTask (Task t) throws RemoteException; w. } • java.rmi.RemoteException is a subclass of ww IOException, and is, hence, a checked exception. • Task is an interface to be defined. CKR Java Notes 297
  • 571. RMI Example (contd): Interface Task om • The interface Task used in the previous piece of code is defined as follows. .c • The key idea is that RMi uses Serialization to transport the object from one Java Virtual Machine to another. DF – by converting the object into a byte stream, and reconverting the stream back into an object. – Hence RemoteException is a kind of aP IOException. • Serialization or object persistence is achieved through extending the interface Serializable. vi • The Serializable interface has no methods, and this is mainly a matter of the object ee semantics to declare that the object is persistent. • This interface must be defined in a separate file, n since all remote interfaces have to be public. w. package rmitask; import java.io.Serializable; public interface Task extends Serializable ww { Object execute(); } CKR Java Notes 298
  • 572. RMI Example (contd): Class MyRMI om • To make a remote object, one simply implements a remote interface. .c • This is done in the file MyRMI.java, which is put into a separate package rmiclass, to separate the interface definition from its implementation. DF • The public class MyRMI – implements the interface RMIDoTask. aP – It also extends the class UnicastRemoteObject vi • Extending this class is NOT mandatory. (Error in Java 2 Complete Reference, p 834) . ee – However, this is a convenience class which provides appropriate rmi implementations of the methods n – which override the methods of the object w. class. – A class which does not extend ww UnicastRemoteObject, e.g. it simply extends RemoteObject CKR Java Notes 299
  • 573. must provide its own implementation of om the methods in the Object class. • Additionally, this class must – (i) construct at least one instance of the remote object .c – (ii) register it – (iii) declare a security policy. DF • The code in rmiclass/MyRMI.java is as follows. package rmiclass; aP import java.rmi.*; import java.rmi.server.*; vi import rmitask.*; public class MyRMI extends ee UnicastRemoteObject implements RMIDoTask n { //define a constructor w. public MyRMI () throws RemoteException { ww super(); //optionally a port no. can //be specified. CKR Java Notes 300
  • 574. //call to super also "exports’ the om //rmi object: i.e., makes it listen //to remote calls on port 1099. } .c //implement the remote interface DF public Object doTask (Task t) { return t.execute(); } aP //start at least one instance //of the remote object //register it vi //and declare a security policy. public static void main (String args[]) ee { //install a standard rmi security manager //if none is installed. n if (System.getSecurityManager()==null) w. { System.setSecurityManager( new RMISecurityManager ()); ww } try { CKR Java Notes 301
  • 575. //declare an instance of the remote object om RMIDoTask rm = new MyRMI(); //decide a name for it String name = " RMITask"; .c //name must have the above form DF //optionally a port no. may be specified //host:porno. //if no port number is specified //port 1099 is used. aP //register (bind) the name in the //rmiRegistry vi Naming.rebind (name, rm); //we use rebind instead of bind to ee //avoid exceptions, if name is already //bound //report success n System.out.println ("RMITask registered"); w. } catch (Exception e) { ww System.err.println ("MyRMI exception:" + e.getMessage()); }}} CKR Java Notes 302
  • 576. RMIExample (contd): The client class CalcPI om • The RMI Client must also set up a security manager. .c • It simply looks up the name of the rmi object in the rmiregistry. DF • and passes the task to it. • The task in this case is to calculate pi to an arbitrary number of decimal places. aP • Hence the class java.math.BigDecimal is used to permit arbitrary precision arithmetic. vi • The code for the RMI client CalcPI (main method) is as follows. package rmiclient; ee import java.rmi.*; import java.math.*; n import rmitask.*; w. public class CalcPi { public static void main (String args[]) { ww //load rmisecurity manager //else rmi call will fail. CKR Java Notes 303
  • 577. if (System.getSecurityManager()==null) om System.setSecurityManager (new RMISecurityManager() ); try { String name = "//"+args[0]+"/RMITask"; .c //args[0] is the host name: portno //if nothing is specified DF //local host is used on port 1099. RMIDoTask rm1 = ((RMIDoTask) Naming.lookup (name)); aP Pi myPi = new Pi (Integer.parseInt (args[1])); //The class Pi is defined elsewhere. vi //args[1] is the number of decimal places //to which the value of Pi should be //computed. ee BigDecimal pivalue = (BigDecimal) (rm1.doTask (myPi)); n System.out.println (pivalue); } w. catch (Exception e) { System.err.println ("CalcPi exception: " ww + e.getMessage() ) ; e.printStackTrace(); } }} CKR Java Notes 304
  • 578. RMIExample (contd): the client class Pi om • The last piece of code is the class Pi, which actually calculates the value of Pi. .c • This is done using the power series expansion for the arctangent function. DF • This expansion was first put forward by Madhava of Sangamagrama, and is found in the MSS of Neelkantha Somayajulu’s TantraSangraha, and Jyeshtadeva’s Yuktibhasa. aP • This class implements the task interface. • The rest of the code for this class is vi straightforward, and does not require much explanation. ee • package rmiclient; n import rmitask.*; import java.math.*; w. public class Pi implements Task ww { private static final BigDecimal ZERO = BigDecimal.valueOf(0); CKR Java Notes 305
  • 579. //class BigDecimal implements om //arbitrary precision arithmetic. private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal FOUR = .c BigDecimal.valueOf(4); DF private static final int roundingMode = BigDecimal.ROUND_HALF_EVEN; //specifies rounding mode aP //The above mode rounds to nearest neighbour //or the even number if both neighbours //are equidistant. vi private int precision; ee public Pi (int precision) { this.precision = precision; n } //define the execute method w. //of the Task interface public Object execute() ww { return findPi (precision); } CKR Java Notes 306
  • 580. om /* find the value of pi using the formula so called "Machin’s formula" pi/4 = 4*arctan (1/5) - arctan (1/239) and the power series expansion for .c arctan */ DF public static BigDecimal findPi (int precision) aP { int scale = precision + 5; BigDecimal arctan_1by5 = arctani (5, scale); vi BigDecimal arctan_1by239 = arctani (239, scale); ee BigDecimal pivalue = arctan_1by5.multiply (FOUR). subtract( arctan_1by239).multiply(FOUR); n return pivalue.setScale (precision, w. BigDecimal.ROUND_HALF_UP); } ww /*The power series for the arctangent is arctan (x) = x - (x^3)/3 + (x^5)/5 CKR Java Notes 307
  • 581. - (x^7)/7 om + (x^9)/9 - ... */ public static BigDecimal arctani .c (int inverseX, int scale) //calculates arctan of the inverse of DF //inverseX //to precision scale. { aP BigDecimal result, numerator, term; BigDecimal invX = BigDecimal.valueOf (inverseX); BigDecimal invX2 = vi BigDecimal.valueOf(inverseX * inverseX); numerator = ONE.divide(invX, scale, roundingMode); ee result = numerator; n int i=1; do w. { numerator = numerator.divide (invX2, scale, ww roundingMode); int denominator = 2*i+1; term = CKR Java Notes 308
  • 582. numerator.divide(BigDecimal.valueOf om (denominator), scale, roundingMode); if ((i%2) == 0) { result = result.add(term); } .c else { DF result = result.subtract(term); } i++; } while (term.compareTo(ZERO) != 0 ) ; aP return result; } } vi n ee w. ww CKR Java Notes 309
  • 583. RMI example: Compiling and running the code om • Step 1: Compile all the .java files into classes. • This must be done in the following order. .c – rmitask/Task.java – rmitask/RMIDoTask.java • The resulting classes should be available in the DF classpath before the following is compiled. – rmiclass/MyRMI.java. • Step 2: To make the classes available, put them aP in a jar file, by using the command jar cvf rmitask.jar rmitask/*.class vi • and add the file rmitask.jar in the CLASSPATH. set CLASSPATH=C:KAWArmitask.jar;%CLASSPATH% ee • now the file rmiclass/MyRMI.java can be compiled. n • Step 3: Create the stub and skeleton class by w. using the following command. rmic -d . rmiclass rmiclass.MyRmi ww • The -d option will place the resulting classes in the rmiclass directory. CKR Java Notes 310
  • 584. RMI Example: Compiling and running (contd) om • Step 4: Build the client classes, using the above set CLASSPATH. .c • Step 5: Declare a security policy. – a sample security policy file exists in the DF jdk1.2.2/jre/lib/security/java.policy file. – This file could be copied to any convenient location, such as aP c:windows. • invoke policytool vi – Open the c:windowsjava.policy file. – choose codebase <ALL> – Add permission: SocketPermission ee – Target: *:1024-65535 – Actions: accept, connect, listen, resolve n – Add permission: File permissions – Target: c:kawa- w. – Actions: read – Add permission: File Permission ww – Target: c:kawarmitask.jar – Actions: read CKR Java Notes 311
  • 585. This will add the following lines of code in the om policy file. grant { permission java.net.SocketPermission .c "*:1024-655535, "accept, connect, listen, resolve"; DF /* This grants permission to processes using non-privileged ports above 1024. Recall that rmi uses port 1099 by default*/ aP permission java.io.FilePermission "c:kawa-", "read"; } vi • The above lines could be added by hand as well. ee • Basically, the first line grants permission to processes to use non-privileged ports (with port n numbers above 1024. w. • The second line grants permission to processes to read all files in the c:kawa directory. ww CKR Java Notes 312
  • 586. RMI Example: compiling and running the code (contd) om • Step 6: – (a) Unset the classpath, and – (b) start the rmiregistry. .c • This is achieved through the following commands. DF set CLASSPATH= start rmiregistry aP • Step 7: Next one must start the server process. • This may be done using a batch file (since the command line buffer may not contain the entire vi command) • The batch file rmstart.bat has the following ee contents. set n CLASSPATH=.;C:kawa;c:kawarmitask.jar java w. -Djava.rmi.server.codebase=file:c:kawa/ -Djava.rmi.server.hostname=127.0.0.1 -Djava.security.policy= ww c:windowsjava.policy rmiclass.MyRMI 127.0.0.1 10 CKR Java Notes 313
  • 587. Step 8: Finally start the client process, and om request a value of pi correct to 10 decimal places. • This may be done through the batch file rmicli.bat which has the following contents. .c set CLASSPATH=.;C:KAWA;C:KAWArmitask.jar DF java -Djava.rmi.server.codebase=file:c:kawa/ -Djava.security.policy= c:windowsjava.policy aP rmiclient.CalcPi 127.0.0.1 10 • Output: 3.1415926536 vi n ee w. ww CKR Java Notes 314
  • 588. JFC and Swing om • Since java aims to be platform independent. • And, since the behaviour of windows is different .c on different platforms (Mac, X, MSWindows) – this presents a problem. DF • The AWT (abstract Windows toolkit) was the first answer to this problem. aP • The Swing API is the second answer to this problem. • Swing API are "lightweight" since they are vi written entirely in Java. • Nevertheless, they offer many of the GUI ee features of, say, MS-Windows programming. • In this respect, Java Foundation Classes are like n Microsoft Foundation classes: – They make windowed programs much w. easier to write. • Before proceeding further, let us take a few ww examples. CKR Java Notes 315
  • 589. Java Swing: Hello World om /*First JFC program */ import java.awt.*; .c import java.awt.event.*; import javax.swing.*; DF public class JHelloWorld extends JPanel { static JFrame jf; aP public JHelloWorld () { JLabel lb = new JLabel ("Hello JFC World"); vi add (lb); } ee public static void main ( String args[] ) { n jf = new JFrame ("Hello JFC World"); JHelloWorld jHello = new JHelloWorld(); w. jf.getContentPane().add("Center", jHello); jf.setSize (250, 150); jf.addWindowListener ww (new WindowAdapter() { public void windowClosing CKR Java Notes 316
  • 590. (WindowEvent e) om { System.exit(0); } } ); .c jf.setVisible (true); } DF } • This program has the following output. aP • vi n ee w. ww CKR Java Notes 317
  • 591. More Swing om • To get a better feel for some of the features of Swing, try the following program. import java.awt.*; .c import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; DF import javax.swing.border.*; public class JSwingStart extends Frame { public static int WIDTH = 450; aP public static int HEIGHT = 450; public static String TITLE = "SwingStart"; // Swing components vi JTabbedPane tabbedPane = new JTabbedPane(); JPanel buttonPanel = new JPanel(); ee JPanel barPanel = new JPanel(); JPanel listPanel = new JPanel(); JPanel tablePanel = new JPanel(); n JPanel[] panels = {buttonPanel,barPanel,listPanel,tablePanel}; w. Icon worldIcon = new ImageIcon("world.gif"); ww Icon printerIcon = new ImageIcon("printer.gif"); Icon leaf1Icon = new CKR Java Notes 318
  • 592. ImageIcon("leaf1.gif"); om Icon leaf2Icon = new ImageIcon("leaf2.gif"); Icon leaf3Icon = new ImageIcon("leaf3.gif"); Icon[] leaves = {leaf1Icon, leaf2Icon, .c leaf3Icon}; JButton printerButton = new DF JButton("Print",printerIcon); JToggleButton worldButton = new JToggleButton("Connect",worldIcon,true); JList leafList = new JList(leaves); aP JSlider slider = new JSlider(JSlider.VERTICAL, 0, 100, 60); JProgressBar progressBar = new JProgressBar(); vi String[] columns = {"Product ID","Description","Price"}; Object[][] cells = ee {columns,{"zvga-1234","Video Card","$50"}, {"56m-11","56K Modem","$315"}, {"dc-10","Net Card","$499"}}; n JTable table = new JTable(cells,columns); w. public JSwingStart() { super(TITLE); addWindowListener(new WindowHandler()); ww buildGUI(); setSize(WIDTH,HEIGHT); setBackground(Color.darkGray); CKR Java Notes 319
  • 593. show(); om } void buildGUI() { // Set up tabbed pane String[] tabs = .c {"Buttons","Bars","Lists","Table"}; String[] tabTips = {"A Button and a DF Toggle Button", "A Slider and a Progress Bar", "An Icon List", "A Cost Table"}; aP for(int i=0;iabs.length;++i) { panels[i].setBackground(Color.lightGray); panels[i].setBorder(new vi TitledBorder(tabTips[i])); tabbedPane.addTab(tabs[i],null,panels[i],tab ee Tips[i]); } addComponentsToTabs(); n add("Center",tabbedPane); } w. void addComponentsToTabs() { setupButtonPanel(); ww setupBarPanel(); setupListPanel(); setupTablePanel(); CKR Java Notes 320
  • 594. } om void setupButtonPanel() { printerButton.setBackground(Color.white); worldButton.setBackground(Color.white); buttonPanel.add(printerButton); .c buttonPanel.add(worldButton); } DF void setupBarPanel() { slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(5); aP slider.setPaintTicks(true); slider.addChangeListener(new SliderHandler()); vi progressBar.setOrientation(JProgressBar.HORI ZONTAL); progressBar.setMinimum(0); ee progressBar.setMaximum(100); progressBar.setValue(60); progressBar.setBorderPainted(true); n barPanel.add(new JLabel("Slider")); barPanel.add(slider); w. barPanel.add(new JLabel("Progress Bar")); barPanel.add(progressBar); } ww void setupListPanel() { leafList.setFixedCellHeight(123); CKR Java Notes 321
  • 595. listPanel.add(leafList); om } void setupTablePanel() { tablePanel.add(table); } .c public static void main(String[] args) { DF JSwingStart app = new JSwingStart(); } public class WindowHandler extends WindowAdapter { aP public void windowClosing(WindowEvent e) { System.exit(0); } vi } public class SliderHandler implements ChangeListener { ee public void stateChanged(ChangeEvent e) { progressBar.setValue(slider.getValue()); } n } } w. • This program has the following output. ww CKR Java Notes 322
  • 596. ww CKR w. nee vi aP Java Notes DF .c om 323
  • 597. DF aP vi ee Packages and .n Class path w ww 1
  • 598. DF What are Packages? aP ● A package is a grouping of related types providing vi access protection and name space management Note that types refers to classes, interfaces, – ee enumerations, and annotation types. – Types are often referred to simply as classes and .n interfaces since enumerations and annotation types are special kinds of classes and interfaces, respectively, so w types are often referred to simply as classes and interfaces. ww 2
  • 599. DF Benefits of Packaging aP ● You and other programmers can easily determine that vi these classes and interfaces are related. ee ● You and other programmers know where to find classes and interfaces that can provide graphics- related functions. .n ● The names of your classes and interfaces won't conflict with the names in other packages because the w package creates a new namespace. ww ● You can allow classes within the package to have unrestricted access to one another yet still restrict access for types outside the package. 3
  • 600. DF aP vi ee .n w Creating a Package ww 4
  • 601. DF Creating a Package aP ● To create a package, you choose a name for the vi package and put a package statement with that name at the top of every source file that contains the types ee (classes, interfaces, enumerations, and annotation types) that you want to include in the package .n ● If you do not use a package statement, your type ends up in an unnamed package w – Use an unnamed package only for small or temporary ww applications 5
  • 602. DF Placing a Class in a Package aP ● To place a class in a package, we write the following as vi the first line of the code (except comments) ee package <packageName>; package myownpackage; w .n ww 6
  • 603. DF Example Package aP ● Suppose you write a group of classes that represent vi graphic objects, such as circles, rectangles, lines, and points ee ● You also write an interface, Draggable, that classes implement if they can be dragged with the mouse .n //in the Draggable.java file public interface Draggable {} //in the Graphic.java file w public abstract class Graphic {} //in the Circle.java file ww public class Circle extends Graphic implements Draggable {} //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable { } //in the Point.java file public class Point extends Graphic implements Draggable {} //in the Line.java file public class Line extends Graphic implements Draggable {} 7
  • 604. DF Example: Placing StudentRecord aP class in SchoolClasses pacakge package SchoolClasses; vi public class StudentRecord { ee private String name; private String address; .n private int age; : w ww 8
  • 605. DF aP vi ee .n Importing and Using w classes from other ww Packages 9
  • 606. DF Using Classes from Other aP Packages ● To use a public package member (classes and vi interfaces) from outside its package, you must do one of the following ee – Import the package member using import statement – Import the member's entire package using import .n statement w – Refer to the member by its fully qualified name (without using import statement) ww 10
  • 607. DF Importing Packages aP ● To be able to use classes outside of the package you are vi currently working in, you need to import the package of those classes. ee ● By default, all your Java programs import the java.lang.* package, that is why you can use classes like String and .n Integers inside the program even though you haven't imported any packages. w ● The syntax for importing packages is as follows: import <nameOfPackage>; ww 11
  • 608. DF Example: Importing a Class or a aP Package // Importing a class vi import java.util.Date; ee // Importing all classes in the .n // java.util package import java.util.*; w ww 12
  • 609. DF Using Classes of other packages aP via fully qualified path vi public static void main(String[] args) { ee java.util.Date x = new java.util.Date(); } w .n ww 13
  • 610. DF Package & Directory Structure aP ● Packages can also be nested. In this case, the Java vi interpreter expects the directory structure containing the executable classes to match the package hierarchy. ee ● There should have same directory structure, ./myowndir/myownsubdir/myownpackage directory for .n the following package statement package myowndir.myownsubdir.myownpackage; w ww 14
  • 611. DF aP vi ee .n w Managing Sources ww & Class files 15
  • 612. DF Managing Source and Class Files aP ● Create a *.java file for the class you want to create vi // in the Rectangle.java file package graphics; ee public class Rectangle() { ... .n } ● Place the source file in a directory whose name reflects w the name of the package to which the class belongs – .....graphicsRectangle.java ww 16
  • 613. DF Directory Structure of Java Source aP Files ● The qualified name of the class file and the path name vi to the Java source file are parallel ee ● Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name .n ● Example w class name: graphics.Rectangle pathname to source file: graphics/Rectangle.java ww pathname to the class file: graphics/Rectangle.class 17
  • 614. DF Directory Structure of Java Source aP Files ● However, the path to the .class files does not have to vi be the same as the path to the .java source files. You can arrange your source and class directories ee separately, as: <path_one>sourcescomexamplegraphicsRectangle.java .n <path_two>classescomexamplegraphicsRectangle.class ● By doing this, you can give the classes directory to w other programmers without revealing your sources ww ● You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses 18
  • 615. ww w .n ee vi aP DF Class path 19
  • 616. DF What is a class path? aP ● It is a set of directories where Java class files are vi located ee ● Java runtime searches for class files in the directories specified in the class path in the order specified w .n ww 20
  • 617. DF Setting the CLASSPATH aP ● Now, suppose we place the package schoolClasses vi under the C: directory. ee ● We need to set the classpath to point to that directory so that when we try to run it, the JVM will be able to see .n where our classes are stored. w Before we discuss how to set the classpath, let us take ww ● a look at an example on what will happen if we don't set the classpath. 21
  • 618. DF Setting the CLASSPATH aP ● Suppose we compile and then run the StudentRecord vi class we wrote in the last section, ee C:schoolClasses>javac StudentRecord.java C:schoolClasses>java StudentRecord Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecord .n (wrong name: schoolClasses/StudentRecord) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) w at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) ww at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) 22
  • 619. DF Setting the CLASSPATH aP ● To set the classpath in Windows, we type this at the vi command prompt, ee C:schoolClasses> set classpath=C: – assuming C: is the directory in which we have placed the packages meaning there is a directory C:schoolClasses .n and there is a C:schoolClassesStudentRecord.class w ● After setting the classpath, we can now run our ww program anywhere by typing, C:schoolClasses> java schoolClasses.StudentRecord 23
  • 620. DF Setting the CLASSPATH aP ● For Unix base systems, suppose we have our classes vi in the directory /usr/local/myClasses, we write, ee export classpath=/usr/local/myClasses w .n ww 24
  • 621. DF Setting the CLASSPATH aP ● Take note that you can set the classpath anywhere. vi You can also set more than one classpath, we just have to separate them by ;(for windows) and : (for Unix ee based systems). For example, set classpath=C:myClasses;D:;E:MyProgramsJava .n ● and for Unix based systems, w export classpath=/usr/local/java:/usr/myClasses ww 25
  • 622. DF aP vi ee Java Threads .n w ww 1
  • 623. DF Topics aP ● What is a thread? vi ● Thread states ● Thread priorities ee ● Thread class Two ways of creating Java threads .n ● – Extending Thread class w – Implementing Runnable interface ThreadGroup ww ● ● Synchronization ● Inter-thread communication ● Scheduling a task via Timer and TimerTask 2
  • 624. DF aP vi ee .n w What is a Thread? ww 3
  • 625. DF Threads aP ● Why threads? vi – Need to handle concurrent processes ee ● Definition – Single sequential flow of control within a program .n – For simplicity, think of threads as processes executed by a program w – Example: ● Operating System ww ● HotJava web browser 4
  • 626. ww w.n ee vi aP DF Threads 5
  • 627. DF Multi-threading in Java Platform aP ● Every application has at least one thread — or several, if you count "system" threads that do vi things like memory management and signal ee handling ● But from the application programmer's point of .n view, you start with just one thread, called the main thread. This thread has the ability to create w additional threads ww 6
  • 628. DF aP vi ee .n w Thread States ww 7
  • 629. DF Thread States aP ● A thread can in one of several possible states: 1. Running vi ● Currently running In control of CPU ● ee 2. Ready to run ● Can run but not yet given the chance .n 3. Resumed ● Ready to run after being suspended or block w 4. Suspended ww ● Voluntarily allowed other threads to run 5. Blocked ● Waiting for some resource or event to occur 8
  • 630. DF aP vi ee .n w Thread Priorities ww 9
  • 631. DF Thread Priorities aP ● Why priorities? vi – Determine which thread receives CPU control and gets to be executed first ee ● Definition: – Integer value ranging from 1 to 10 .n – Higher the thread priority → larger chance of being executed first w – Example: ww ● Two threads are ready to run ● First thread: priority of 5, already running ● Second thread = priority of 10, comes in while first thread is running 10
  • 632. DF Thread Priorities aP ● Context switch vi – Occurs when a thread snatches the control of CPU from another ee – When does it occur? ● Running thread voluntarily relinquishes CPU control .n ● Running thread is preempted by a higher priority thread More than one highest priority thread that is ready w ● to run ww – Deciding which receives CPU control depends on the operating system – Windows 95/98/NT: Uses time-sliced round-robin – Solaris: Executing thread should voluntarily relinquish CPU control 11
  • 633. DF aP vi ee .n w Thread Class ww 12
  • 634. DF The Thread Class: Constructor aP ● Has eight constructors vi ee w .n ww 13
  • 635. DF The Thread Class: Constants aP ● Contains fields for priority values vi ee w .n ww 14
  • 636. DF The Thread Class: Methods aP ● Some Thread methods vi ee w .n ww 15
  • 637. DF aP vi ee .n w Two Ways of Creating ww Java Threads 16
  • 638. DF Two Ways of Creating and Starting aP a Thread 1.Extending the Thread class vi 2.Implementing the Runnable interface ee w .n ww 17
  • 639. DF aP vi ee .n w Extending Thread ww Class 18
  • 640. DF Extending Thread Class aP ● The subclass extends Thread class vi – The subclass overrides the run() method of Thread class ee ● An object instance of the subclass can then be created .n ● Calling the start() method of the object instance starts the execution of the thread w – Java runtime starts the execution of the thread by calling run() method of object instance ww 19
  • 641. DF Two Schemes of starting a thread aP from a subclass 1.The start() method is not in the constructor of the vi subclassee – The start() method needs to be explicitly invoked after object instance of the subclass is created in order to start the thread .n 2.The start() method is in the constructor of the subclass w – Creating an object instance of the subclass will start the ww thread 20
  • 642. DF Scheme 1: start() method is Not in the constructor of subclass aP 1 class PrintNameThread extends Thread { PrintNameThread(String name) { vi 2 3 super(name); ee 4 } 5 public void run() { 6 String name = getName(); .n 7 for (int i = 0; i < 100; i++) { System.out.print(name); w 8 9 } ww 10 } 11 } 12 //continued 21
  • 643. DF Scheme 1: start() method needs to be called explicitly aP 14 class ExtendThreadClassTest1 { public static void main(String args[]) { vi 15 16 PrintNameThread pnt1 = ee 17 new PrintNameThread("A"); 18 pnt1.start(); // Start the first thread 19 PrintNameThread pnt2 = .n 20 new PrintNameThread("B"); pnt2.start(); // Start the second thread w 21 22 ww 23 } 24 } 22
  • 644. DF Scheme 2: start() method is in a constructor of the subclass aP 1 class PrintNameThread extends Thread { PrintNameThread(String name) { vi 2 3 super(name); ee 4 start(); //runs the thread once instantiated 5 } 6 public void run() { .n 7 String name = getName(); for (int i = 0; i < 100; i++) { w 8 9 System.out.print(name); ww 10 } 11 } 12 } 13 //continued 23
  • 645. DF Scheme 2: Just creating an object instance starts a thread aP 14 class ExtendThreadClassTest2 { public static void main(String args[]) { vi 15 16 PrintNameThread pnt1 = ee 17 new PrintNameThread("A"); 18 PrintNameThread pnt2 = 19 new PrintNameThread("B"); .n 20 } w 21 22 } ww 24
  • 646. DF Scheme 2: Just creating an object aP instance starts a thread ● Can modify main method as follows: vi 14 class ExtendThreadClassTest3 { ee 15 public static void main(String args[]) { 16 new PrintNameThread("A"); 17 new PrintNameThread("B"); .n 18 } } w 19 ww 25
  • 647. DF aP vi ee .n w Implementing ww Runnable Interface 26
  • 648. DF Runnable Interface aP ● The Runnable interface should be implemented by vi any class whose instances are intended to be executed as a thread ee ● The class must define run() method of no arguments .n – The run() method is like main() for the new thread w ● Provides the means for a class to be active while not subclassing Thread ww – A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target 27
  • 649. DF Two Ways of Starting a Thread For aP a class that implements Runnable 1.Caller thread creates Thread object and starts it vi explicitly after an object instance of the class that implements Runnable interface is created ee – The start() method of the Thread object needs to be explicitly invoked after object instance is created .n 2.The Thread object is created and started within the constructor method of the class that implements w Runnable interface ww – The caller thread just needs to create object instances of the Runnable class 28
  • 650. DF Scheme 1: Caller thread creates a Thread object and starts it explicitly aP // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { vi String name; ee PrintNameRunnable(String name) { this.name = name; } .n // Implementation of the run() defined in the w // Runnable interface. public void run() { for (int i = 0; i < 10; i++) { ww System.out.print(name); } } } 29
  • 651. DF Scheme 1: Caller thread creates a Thread object and starts it explicitly aP public class RunnableThreadTest1 { public static void main(String args[]) { vi PrintNameRunnable pnt1 = new PrintNameRunnable("A"); ee Thread t1 = new Thread(pnt1); t1.start(); .n } } w ww 30
  • 652. DF Scheme 2: Thread object is created and started within a constructor aP // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { vi Thread thread; ee PrintNameRunnable(String name) { thread = new Thread(this, name); thread.start(); } .n // Implementation of the run() defined in the w // Runnable interface. public void run() { ww String name = thread.getName(); for (int i = 0; i < 10; i++) { System.out.print(name); } } } 31
  • 653. DF Scheme 2: Thread object is created and started within a constructor aP public class RunnableThreadTest2 { public static void main(String args[]) { vi // Since the constructor of the PrintNameRunnable ee // object creates a Thread object and starts it, // there is no need to do it here. new PrintNameRunnable("A"); .n new PrintNameRunnable("B"); new PrintNameRunnable("C"); w } } ww 32
  • 654. DF aP vi ee .n Extending Thread Class w ww vs. Implementing Runnable Interface 33
  • 655. DF Extending Thread vs. Implementing aP Runnable Interface ● Choosing between these two is a matter of taste vi ● Implementing the Runnable interface ee – May take more work since we still ● Declare a Thread object .n ● Call the Thread methods on this object – Your class can still extend other class w ● Extending the Thread class – Easier to implement ww – Your class can no longer extend any other class 34
  • 656. DF aP vi ee .n w ThreadGroup ww 35
  • 657. DF ThreadGroup Class aP ● A thread group represents a set of threads vi ● In addition, a thread group can also include other ee thread groups – The thread groups form a tree in which every thread group except the initial thread group has a parent .n ● A thread is allowed to access information about its w own thread group, but not to access information about its thread group's parent thread group or any ww other thread groups. 36
  • 658. DF Example: ThreadGroup aP 1 // Start three threads 2 new SimpleThread("Jamaica").start(); vi 3 new SimpleThread("Fiji").start(); 4 new SimpleThread("Bora Bora").start(); ee 5 6 ThreadGroup group .n 7 = Thread.currentThread().getThreadGroup(); 8 w 9 Thread[] tarray = new Thread[10]; 10 int actualSize = group.enumerate(tarray); ww 11 for (int i=0; i<actualSize;i++){ 12 System.out.println("Thread " + 13 tarray[i].getName() + " in thread group " 14 + group.getName()); 15 } 37
  • 659. DF aP vi ee .n w Synchronization ww 38
  • 660. DF Race condition & How to Solve it aP ● Race conditions occur when multiple, vi asynchronously executing threads access the same object (called a shared resource) returning ee unexpected (wrong) results ● Example: .n – Threads often need to share a common resource ie a file, with one thread reading from the file while another w thread writes to the file ww ● They can be avoided by synchronizing the threads which access the shared resource 39
  • 661. DF An Unsynchronized Example aP 1 class TwoStrings { 2 static void print(String str1, String str2) { vi 3 System.out.print(str1); 4 try { ee 5 Thread.sleep(500); 6 } catch (InterruptedException ie) { .n 7 } 8 System.out.println(str2); w 9 } 10 } ww 11 //continued... 40
  • 662. DF An Unsynchronized Example aP 12 class PrintStringsThread implements Runnable { 13 Thread thread; vi 14 String str1, str2; 15 PrintStringsThread(String str1, String str2) { ee 16 this.str1 = str1; 17 this.str2 = str2; .n 18 thread = new Thread(this); 19 thread.start(); w 20 } 21 public void run() { ww 22 TwoStrings.print(str1, str2); 23 } 24 } 25 //continued... 41
  • 663. DF An Unsynchronized Example aP 26 class TestThread { 27 public static void main(String args[]) { vi 28 new PrintStringsThread("Hello ", "there."); 29 new PrintStringsThread("How are ", "you?"); ee 30 new PrintStringsThread("Thank you ", 31 "very much!"); .n 32 } 33 } w ww 42
  • 664. DF An Unsynchronized Example aP ● Sample output: Hello How are Thank you there. vi you? very much! ee w .n ww 43
  • 665. DF Synchronization: aP Locking an Object ● A thread is synchronized by becoming an owner of vi the object's monitor ee – Consider it as locking an object ● A thread becomes the owner of the object's monitor in one of three ways .n – Option 1: Use synchronized method w – Option 2: Use synchronized statement on a common object ww 44
  • 666. DF Option 1: Use synchronized method aP 1 class TwoStrings { vi 2 synchronized static void print(String str1, 3 ee String str2) { 4 System.out.print(str1); 5 try { Thread.sleep(500); .n 6 7 } catch (InterruptedException ie) { } w 8 9 System.out.println(str2); ww 10 } 11 } 12 //continued... 45
  • 667. DF Option 1: Use synchronized method aP 13 class PrintStringsThread implements Runnable { 14 Thread thread; vi 15 String str1, str2; 16 PrintStringsThread(String str1, String str2) { ee 17 this.str1 = str1; 18 this.str2 = str2; .n 19 thread = new Thread(this); 20 thread.start(); w 21 } 22 public void run() { ww 23 TwoStrings.print(str1, str2); 24 } 25 } 26 //continued... 46
  • 668. DF Option 1: Use synchronized method aP 27 class TestThread { 28 public static void main(String args[]) { vi 29 new PrintStringsThread("Hello ", "there."); new PrintStringsThread("How are ", "you?"); 30 ee 31 new PrintStringsThread("Thank you ", 32 "very much!"); .n 33 } 34 } w ww 47
  • 669. DF Option 1: Executing Synchronized Method aP ● Sample output: Hello there. vi How are you? ee Thank you very much! w .n ww 48
  • 670. DF Option 2: Use synchronized statement on a common object aP 1 class TwoStrings { 2 static void print(String str1, String str2) { vi 3 System.out.print(str1); try { 4 ee 5 Thread.sleep(500); 6 } catch (InterruptedException ie) { .n 7 } 8 System.out.println(str2); w 9 } ww 10 } 11 //continued... 49
  • 671. DF Option 2: Use synchronized statement on a common object aP 12 class PrintStringsThread implements Runnable { 13 Thread thread; vi 14 String str1, str2; TwoStrings ts; 15 ee 16 PrintStringsThread(String str1, String str2, 17 TwoStrings ts) { .n 18 this.str1 = str1; 19 this.str2 = str2; w 20 this.ts = ts; thread = new Thread(this); ww 21 22 thread.start(); 23 } 24 //continued... 50
  • 672. DF Option 2: Use synchronized statement on a common object aP 25 public void run() { 26 synchronized (ts) { vi 27 ts.print(str1, str2); 28 } ee 29 } 30 } .n 31 class TestThread { 32 public static void main(String args[]) { w 33 TwoStrings ts = new TwoStrings(); 34 new PrintStringsThread("Hello ", "there.", ts); ww 35 new PrintStringsThread("How are ", "you?", ts); 36 new PrintStringsThread("Thank you ", 37 "very much!", ts); 38 }} 51
  • 673. DF aP vi ee .n w Inter-thread ww Synchronization 52
  • 674. DF Inter-thread Communication: aP Methods from Object Class vi ee .n w ww 53
  • 675. DF wait() method of Object Class aP ● wait() method causes a thread to release the lock it vi is holding on an object; allowing another thread to run ee ● wait() method is defined in the Object class wait() can only be invoked from within synchronized .n ● code w ● it should always be wrapped in a try block as it throws IOExceptions ww ● wait() can only invoked by the thread that own's the lock on the object 54
  • 676. DF wait() method of Object Class aP ● When wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things vi occur:ee – another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread – another thread invokes the notifyAll() method for this .n object – another thread interrupts this thread w – the specified wait() time elapses ww ● When one of the above occurs, the thread becomes re- available to the Thread scheduler and competes for a lock on the object ● Once it regains the lock on the object, everything resumes as if no suspension had occurred 55
  • 677. DF notify() method aP ● Wakes up a single thread that is waiting on this object's monitor vi – If any threads are waiting on this object, one of them is chosen to be awakened ee – The choice is arbitrary and occurs at the discretion of the implementation .n ● Can only be used within synchronized code ● The awakened thread will not be able to proceed w until the current thread relinquishes the lock on this object ww 56
  • 678. DF aP vi ee Inter-thread .n w Communication: ww Producer-Consumer Example 57
  • 679. DF Inter-thread Communication aP vi ee .n w ww 58
  • 680. DF Producer-Consumer aP ● Imagine a scenario in which there exists two vi distinct threads both operating on a single shared data area ee ● One thread, the Producer inserts information into the data area whilst the other thread, the .n Consumer, removes information from that same area w ● In order for the Producer to insert information into ww the data area, there must be enough space – The Producer's sole function is to insert data into the data-area, it is not allowed to remove any data from the area. 59
  • 681. DF Producer-Consumer aP ● For the Consumer to be able to remove information vi from the data area, there must be information there in the first place ee – The sole function of the Consumer is to remove data from the data area .n ● The solution of the Producer-Consumer problem lies with devising a suitable communication protocol w through which the two processes may exchange ww information. ● The definition of such a protocol is the main factor that makes the Producer-Consumer problem interesting in terms of concurrent systems 60
  • 682. DF Unsynchronized Producer-Consumer Example: CubbyHole.java aP 1 public class CubbyHole { 2 private int contents; vi 3 public int get() { 4 ee 5 return contents; 6 } .n 7 8 public synchronized void put(int value) { w 9 contents = value; } ww 10 11 } 61
  • 683. DF Unsynchronized Producer- Consumer Example: Producer.java aP 1 public class Producer extends Thread { 2 private CubbyHole cubbyhole; vi 3 private int number; 4 public Producer(CubbyHole c, int number) { 5 ee 6 cubbyhole = c; 7 this.number = number; 8 } .n 9 10 public void run() { w 11 for (int i = 0; i < 10; i++) { 12 cubbyhole.put(i); System.out.println("Producer #" + this.number ww 13 14 + " put: " + i); 15 try { 16 sleep((int)(Math.random() * 100)); 17 } catch (InterruptedException e) { } 18 } 19 } 62 20 }
  • 684. DF Unsynchronized Producer-Consumer Example: Consumer.java aP 1 public class Consumer extends Thread { 2 private CubbyHole cubbyhole; vi 3 private int number; 4 public Consumer(CubbyHole c, int number) { 5 ee 6 cubbyhole = c; 7 this.number = number; 8 } .n 9 10 public void run() { w 11 int value = 0; 12 for (int i = 0; i < 10; i++) { value = cubbyhole.get(); ww 13 14 System.out.println("Consumer #" + this.number 15 + " got: " + value); 16 } 17 } 18 } 19 63
  • 685. DF Unsynchronized Producer- Consumer Example: Main program aP 1 public class ProducerConsumerUnsynchronized { 2 vi 3 public static void main(String[] args) { 4 ee 5 CubbyHole c = new CubbyHole(); 6 .n 7 Producer p1 = new Producer(c, 1); 8 Consumer c1 = new Consumer(c, 1); w 9 p1.start(); ww 10 11 c1.start(); 12 } 13 } 64
  • 686. DF Result of Unsynchronized aP Producer-Consumer ● Results are unpredictable vi – A number may be read before a number has been produced ee – Multiple numbers may be produced with only one or two being read w .n ww 65
  • 687. DF Result of Unsynchronized aP Producer-Consumer Consumer #1 got: 0 vi Producer #1 put: 0 Consumer #1 got: 0 Consumer #1 got: 0 ee Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 .n Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 w Producer #1 put: 1 Producer #1 put: 2 ww Producer #1 put: 3 Producer #1 put: 4 Producer #1 put: 5 Producer #1 put: 6 Producer #1 put: 7 Producer #1 put: 8 Producer #1 put: 9 66
  • 688. DF Synchronized Producer-Consumer Example: CubbyHole.java aP 1 public class CubbyHole { 2 private int contents; vi 3 private boolean available = false; 4 ee 5 public synchronized int get() { 6 while (available == false) { .n 7 try { 8 wait(); w 9 } catch (InterruptedException e) { } } ww 10 11 available = false; 12 notifyAll(); 13 return contents; 14 } 67 15 // continued
  • 689. DF Synchronized Producer-Consumer Example: CubbyHole.java aP 1 vi 2 public synchronized void put(int value) { 3 while (available == true) { ee 4 try { 5 wait(); .n 6 } catch (InterruptedException e) { } 7 } w 8 contents = value; available = true; ww 9 10 notifyAll(); 11 } 12 } 68
  • 690. DF Result of Synchronized Producer- aP Consumer Producer 1 put: 0 vi Consumer 1 got: 0 Producer 1 put: 1 Consumer 1 got: 1 ee Producer 1 put: 2 Consumer 1 got: 2 Producer 1 put: 3 Consumer 1 got: 3 .n Producer 1 put: 4 Consumer 1 got: 4 Producer 1 put: 5 w Consumer 1 got: 5 Producer 1 put: 6 ww Consumer 1 got: 6 Producer 1 put: 7 Consumer 1 got: 7 Producer 1 put: 8 Consumer 1 got: 8 Producer 1 put: 9 Consumer 1 got: 9 69
  • 691. DF aP vi ee .n Scheduling a task w via Timer & ww TimerTask Classes 70
  • 692. DF Timer Class aP ● Provides a facility for threads to schedule tasks for future execution in a background thread vi Tasks may be scheduled for one-time execution, or ● ee for repeated execution at regular intervals. ● Corresponding to each Timer object is a single .n background thread that is used to execute all of the timer's tasks, sequentially w ● Timer tasks should complete quickly ww – If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes. 71
  • 693. DF TimerTask Class aP ● Abstract class with an abstract method called run() vi ● Concrete class must implement the run() abstract method ee w .n ww 72
  • 694. DF Example: Timer Class aP public class TimerReminder { Timer timer; vi public TimerReminder(int seconds) { timer = new Timer(); ee timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { .n public void run() { System.out.format("Time's up!%n"); w timer.cancel(); //Terminate the timer thread } ww } public static void main(String args[]) { System.out.format("About to schedule task.%n"); new TimerReminder(5); System.out.format("Task scheduled.%n"); } 73 }
  • 695. ww w.n ee vi aP DF Thank You! 74