java_comb

695
1 Object Computing, Inc. AWT Event Handling JDK 1.1 AWT Event Handling ===================== www.neeviaPDF.com

Upload: arjun-shanka

Post on 20-May-2015

1.774 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java_Comb

1Object Computing, Inc. AWT Event Handling

JDK 1.1 AWTEvent Handling

=====================

ww

w.n

eevi

aPDF.

com

Page 2: Java_Comb

2Object Computing, Inc. AWT Event Handling

AWT

• Abstract Windowing Toolkit package– java.awt

• Easier to learn than Motif/X and MFC• Not as easy as using graphical GUI

builders– several companies are creating them for Java– will output Java code that uses the AWT package

• AWT classes fall in four categories– components– containers– layout managers– event handling

ww

w.n

eevi

aPDF.

com

Page 3: Java_Comb

3Object Computing, Inc. AWT Event Handling

Steps To Use AWT

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

• Select a LayoutManager– Flow, Border, Grid, GridBag, Card, none (null)

• Create components– Button, Checkbox, Choice, Label, List, TextArea,

TextField, PopupMenu

• Add components to container• Specify event handling (changed in 1.1)

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

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

ComponentEvent, FocusEvent, ItemEvent, KeyEvent,MouseEvent, TextEvent, WindowEvent

– implement methods of listener interfacesin listener classes

• an event object is passed to the methods• ActionListener, AdjustmentListener, ComponentListener,

FocusListener, ItemListener, KeyListener, MouseListener,MouseMotionListener, TextListener, WindowListenerw

ww

.nee

viaP

DF.co

m

Page 4: Java_Comb

4Object Computing, Inc. AWT Event Handling

Event Sources,Listeners, and Objects

Event Source• generates events• ex. Button

Event Listener• any object can implement these interfaces• ex. ActionListener has method actionPerformed()

Event Object• describes an event• ex. ActionEvent holds state of Shift key

creates

passes to listener method

ww

w.n

eevi

aPDF.

com

Page 5: Java_Comb

5Object Computing, Inc. AWT Event Handling

Simple AWTExample

import java.awt.*;import java.awt.event.*;

public class SimpleAWT extends java.applet.Appletimplements ActionListener, ItemListener {

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

public void init() {button.addActionListener(this);checkbox.addItemListener(this);choice.addItemListener(this);

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

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

Panel panel = new Panel();panel.add(button);panel.add(checkbox);panel.add(choice);

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

}ww

w.n

eevi

aPDF.

com

Page 6: Java_Comb

6Object Computing, Inc. AWT Event Handling

Simple AWT Example(Cont’d)

public void actionPerformed(ActionEvent e) {if (e.getSource() == button) {

label.setText("The Button was pushed.");}

}

public void itemStateChanged(ItemEvent e) {if (e.getSource() == checkbox) {

label.setText("The Checkbox is now " + checkbox.getState() + ".");

} else if (e.getSource() == choice) {label.setText(choice.getSelectedItem() + “ was selected.”);

}}

}

ww

w.n

eevi

aPDF.

com

Page 7: Java_Comb

7Object Computing, Inc. AWT Event Handling

Event Classes

• Hierarchyjava.util.EventObject– java.awt.AWTEvent

• java.awt.event.ComponentEvent– java.awt.event.FocusEvent– java.awt.event.InputEvent

• java.awt.event.KeyEvent• java.awt.event.MouseEvent

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

• Can create custom, non-AWT eventclasses– extend java.util.EventObject

ww

w.n

eevi

aPDF.

com

Page 8: Java_Comb

8Object Computing, Inc. AWT Event Handling

Event Object Contents

• java.util.EventObject– source holds a reference to the object that fired the event

– java.awt.AWTEvent• id indicates event type

– 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)

keys– actionCommand holds the action specific command

string• usually the label of a Button or MenuItem

• java.awt.event.AdjustmentEvent– for Scrollbars– value holds value– adjustmentType is unit +/-, block +/-, track

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

• java.awt.event.TextEvent– 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

used forcheckboxes andradio buttons

ww

w.n

eevi

aPDF.

com

Page 9: Java_Comb

9Object Computing, Inc. AWT Event Handling

Event Object Contents(Cont’d)

• java.awt.AWTEvent– java.awt.event.ComponentEvent

• 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

removed• java.awt.event.FocusEvent

– id indicates gained or lost– temporary indicates temporary or permanent

(see documentation in source)• java.awt.event.WindowEvent

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

brought to front

ww

w.n

eevi

aPDF.

com

Page 10: Java_Comb

10Object Computing, Inc. AWT Event Handling

Event Object Contents(Cont’d)

• java.awt.AWTEvent– java.awt.event.InputEvent

• 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– probably should have been put in java.util.EventObject!

• java.awt.event.KeyEvent– 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)• java.awt.event.MouseEvent

– id indicates clicked, pressed, released, moved, entered,exited, or dragged

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

ww

w.n

eevi

aPDF.

com

Page 11: Java_Comb

11Object Computing, Inc. AWT Event Handling

Event Listener Interfaces

• Class hierarchy and methods– java.util.EventListener

• java.awt.event.ActionListener– actionPerformed

• java.awt.event.AdjustmentListener– adjustmentValueChanged

• java.awt.event.ComponentListener– componentHidden, componentMoved, componentResized,

componentShown• java.awt.event.FocusListener

– focusGained, focusLost• java.awt.event.ItemListener

– itemStateChanged• java.awt.event.KeyListener

– keyPressed, keyReleased, keyTyped• java.awt.event.MouseListener

– mouseEntered, mouseExited,mousePressed, mouseReleased, mouseClicked

• java.awt.event.MouseMotionListener– mouseDragged, mouseMoved

• java.awt.event.TextListener– textValueChanged

• java.awt.event.WindowListener– windowOpened, windowClosing, windowClosed,

windowActivated, windowDeactivated, windowIconified,windowDeiconifiedw

ww

.nee

viaP

DF.co

m

Page 12: Java_Comb

12Object Computing, Inc. AWT Event Handling

Event Sources andTheir Listeners

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

MouseListener, MouseMotionListener

• Dialog - WindowListener

• Frame - WindowListener

• Button - ActionListener

• Choice - ItemListener

• Checkbox - ItemListener

• CheckboxMenuItem - ItemListener

• List - ItemListener, ActionListener

• MenuItem - ActionListener

• Scrollbar - AdjustmentListener

• TextField - ActionListener, TextListener

• TextArea - TextListener

when an item isdouble-clicked

ww

w.n

eevi

aPDF.

com

Page 13: Java_Comb

13Object Computing, Inc. AWT Event Handling

Listener Adapter Classes

• Provide empty default implementations ofmethods in listener interfaces with morethan one method

• They include– java.awt.event.ComponentAdapter– java.awt.event.FocusAdapter– java.awt.event.KeyAdapter– java.awt.event.MouseAdapter– java.awt.event.MouseMotionAdapter– java.awt.event.WindowAdapter

• To use, extend from them– override methods of interest– usefulness is limited by single inheritance

• can’t do if another class is already being extended• implementation for methods that are not of interest could look

like this public void windowIconified(WindowEvent e) {}ww

w.n

eevi

aPDF.

com

Page 14: Java_Comb

14Object Computing, Inc. AWT Event Handling

Design For Flexibilityand Maintainability

• Can separate– application code– GUI code– event handling code

• Steps to achieve this separation– create a single class whose constructor creates the

entire GUI, possibly using other GUI-only classes– create the GUI by invoking this constructor from an

application class– create classes whose only function is to be notified of

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

objects whose methods they will invoke

– create event handling objects in a GUI class andregister them with the components whose events theywill handle

App

GUI

EventHandlers

passes self and

creates GUI

invokes app. methods

create

s han

dlers

and

passe

s App

ref.,

regist

ers ha

ndler

s as l

isten

ers

of co

mpone

nt ev

ents

ww

w.n

eevi

aPDF.

com

Page 15: Java_Comb

15Object Computing, Inc. AWT Event Handling

AWT Example

• FontTest allows specification of text to bedisplayed, font name, style, color and size

• It illustrates• creation of GUI components• use of the Canvas and PopupMenu• component layout using BorderLayout,

FlowLayout, and GridLayout• event handling

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

w.n

eevi

aPDF.

com

Page 16: Java_Comb

16Object Computing, Inc. AWT Event Handling

FontTest.java

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

public class FontTest extends java.applet.Appletimplements ActionListener, AdjustmentListener, ItemListener, MouseListener {

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

private static final int BOX_SIZE = 3; private static final int MIN_SIZE = 6; 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); private Checkbox italicRadio = new Checkbox("Italic", false, styleGroup); 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"); 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);w

ww

.nee

viaP

DF.co

m

Page 17: Java_Comb

17Object Computing, Inc. AWT Event Handling

FontTest.java (Cont’d)

public void init() { fontChoice.addItem("TimesRoman"); fontChoice.addItem("Helvetica"); fontChoice.addItem("Courier"); fontChoice.select(DEFAULT_FONT);

Panel fontPanel = new Panel(); fontPanel.add(new Label("Font:")); fontPanel.add(fontChoice);

Panel stylePanel = new Panel(); stylePanel.add(plainRadio); stylePanel.add(boldRadio); stylePanel.add(italicRadio); stylePanel.add(bothRadio);

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

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

Panel westPanel = new Panel(new GridLayout(0, 1)); westPanel.add(fontPanel); westPanel.add(stylePanel); westPanel.add(colorList); westPanel.add(sizePanel);

unknown # of rows,one columnw

ww

.nee

viaP

DF.co

m

Page 18: Java_Comb

18Object Computing, Inc. AWT Event Handling

FontTest.java (Cont’d)

setLayout(new BorderLayout()); add(myCanvas, "Center"); add(westPanel, "West"); add(textField, "North"); add(scrollbar, "South");

fontChoice.addItemListener(this); plainRadio.addItemListener(this); boldRadio.addItemListener(this); italicRadio.addItemListener(this); bothRadio.addItemListener(this); colorList.addItemListener(this); sizeField.addActionListener(this); textField.addActionListener(this); scrollbar.addAdjustmentListener(this); fontPanel.addMouseListener(this); stylePanel.addMouseListener(this); sizePanel.addMouseListener(this); myCanvas.addMouseListener(this);

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

w.n

eevi

aPDF.

com

Page 19: Java_Comb

19Object Computing, Inc. AWT Event Handling

FontTest.java (Cont’d) public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == textField) { myCanvas.setText(textField.getText()); } else if (source == sizeField) { int size = Integer.parseInt(sizeField.getText()); scrollbar.setValue(size); setFont(); } else if (source instanceof MenuItem) { MenuItem menuItem = (MenuItem) source; if (menuItem.getParent() == popup) { fontChoice.select(e.getActionCommand()); setFont(); } } }

public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == scrollbar) { sizeField.setText(String.valueOf(scrollbar.getValue())); setFont(); } }

public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source == fontChoice) { setFont(); } else if (source instanceof Checkbox) { Checkbox checkbox = (Checkbox) source; if (checkbox.getCheckboxGroup() == styleGroup) { setFont(); } } else if (source == colorList) { Color color = ColorMap.getColor(colorList.getSelectedItem()); myCanvas.setColor(color); } }w

ww

.nee

viaP

DF.co

m

Page 20: Java_Comb

20Object Computing, Inc. AWT Event Handling

FontTest.java (Cont’d)

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

public void mousePressed(MouseEvent e) { popup.show((Component) e.getSource(), e.getX(), e.getY()); }

private void setFont() { int style = Font.PLAIN;

Checkbox styleRadio = styleGroup.getSelectedCheckbox(); if (styleRadio == plainRadio) { style = Font.PLAIN; } else if (styleRadio == boldRadio) { style = Font.BOLD; } else if (styleRadio == italicRadio) { style = Font.ITALIC; } else if (styleRadio == bothRadio) { style = Font.BOLD + Font.ITALIC; }

Font font = new Font(fontChoice.getSelectedItem(), style, Integer.parseInt(sizeField.getText()));

myCanvas.setFont(font); }}w

ww

.nee

viaP

DF.co

m

Page 21: Java_Comb

21Object Computing, Inc. AWT Event Handling

FontTest.java (Cont’d)

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

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

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

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

public void paint(Graphics g) { g.setColor(color); g.setFont(font); g.drawString(text, 10, 200); }}

ww

w.n

eevi

aPDF.

com

Page 22: Java_Comb

22Object Computing, Inc. AWT Event Handling

ColorMap.java

package COM.ociweb.awt;

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

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

static { hashtable.put("White", Color.white); hashtable.put("Gray", Color.gray); hashtable.put("DarkGray", Color.darkGray); hashtable.put("Black", Color.black); 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); hashtable.put("Magenta", Color.magenta); hashtable.put("Cyan", Color.cyan); hashtable.put("Blue", Color.blue); }

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

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

ww

.nee

viaP

DF.co

m

Page 23: Java_Comb

23Object Computing, Inc. AWT Event Handling

Appendix A

JDK 1.0AWT

Event Handling

ww

w.n

eevi

aPDF.

com

Page 24: Java_Comb

24Object Computing, Inc. AWT Event Handling

1.0 Default Event Handling(delegation-based event handling was added in Java 1.1)

• Provided by Component class• handleEvent(Event evt)

– first method invoked when an event occurs– default implementation tests for specific types of

events and invokes the methods below

• Methods to handle specific types of events– default implementations do nothing– they are

• mouseDown and mouseUp• mouseDrag and mouseMove• mouseEnter and mouseExit• keyDown and keyUp• gotFocus and lostFocus

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

• All event handling methods return boolean– indicates whether they handled the event– if false, the event is handled recursively by

containersww

w.n

eevi

aPDF.

com

Page 25: Java_Comb

25Object Computing, Inc. AWT Event Handling

Overriding 1.0 DefaultEvent Handling

• Custom event handling methods other thanhandleEvent– created by overriding implementations in Component

which do nothing– invoked by the default handleEvent implementation

• Custom handleEvent method– created by overriding implementation in Component– can handle all events by comparing id field to

constants in Event class to see what kind of eventoccurred

– if overridden, other event handling methods will notbe invoked unless

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

• 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

handleEvent method– invoke with “return super.handleEvent(e);”– first superclass to implement handleEvent is typically

Component which disperses the event to methods whichhandle specific types of eventsw

ww

.nee

viaP

DF.co

m

Page 26: Java_Comb

26Object Computing, Inc. AWT Event Handling

1.0 Action Events

• Most user interface components generate“action” events– Label and TextArea don’t generate any events– List and Scrollbar generate events that are not

“action” events• must be handled in a handleEvent method,

not an action method

• Default handleEvent invokespublic boolean action(Event evt, Object what)

• Second argument varies based on thecomponent– Button

• String representing button label

– Checkbox (and radiobutton)• Boolean state (true for on, false for off)• generated when picked

– Choice (option menu)• String representing selected item

– TextField• null• generated when user presses return key• not when field is exited with mouse or tab key

– use lostFocus method to catch thatww

w.n

eevi

aPDF.

com

Page 27: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 1 of 12 6/15/99

Inheritance in Java

Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the baseclass or superclass) with another class (called the derived class or subclass). In Java,inheritance is used for two purposes:

1. class inheritance - create a new class as an extension of another class, primarily for the purposeof code reuse. That is, the derived class inherits the public methods and public data of thebase class. Java only allows a class to have one immediate base class, i.e., single classinheritance.

2. interface inheritance - create a new class to implement the methods defined as part of aninterface for the purpose of subtyping. That is a class that implements an interface “conformsto” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.

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

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

}

public class class-name implements interface-name {// class provides an implementation for the methods// as specified by the interface

}

www.neeviaPDF.com

Page 28: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 2 of 12 6/15/99

Example of class inhertiance

package MyPackage;

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

}

class Derived extends Base {private int y;public int f() { /* new implementation for Base.f() */ }public void h() { y = g(); ... }

}

In Java, the protected access qualifier means that the protected item (field or method) is visible to aany derived class of the base class containing the protected item. It also means that the protecteditem is visible to methods of other classes in the same package. This is different from C++.

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

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

www.neeviaPDF.com

Page 29: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 3 of 12 6/15/99

Order of Construction under Inheritance

Note that when you construct an object, the default base class constructor is called implicitly, beforethe body of the derived class constructor is executed. So, objects are constructed top-down underinheritance. Since every object inherits from the Object class, the Object() constructor is alwayscalled implicitly. However, you can call a superclass constructor explicitly using the builtin superkeyword, as long as it is the first statement in a constructor.

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

public class SomeException extends Exception {

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

}

public SomeException(String s) {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);

}}

www.neeviaPDF.com

Page 30: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 4 of 12 6/15/99

Abstract Base Classes

An abstract class is a class that leaves one or more method implementations unspecified bydeclaring one or more methods abstract. An abstract method has no body (i.e., no implementation). Asubclass is required to override the abstract method and provide an implementation. Hence, anabstract class is incomplete and cannot be instantiated, but can be used as a base class.

abstract public class abstract-base - class-name {// abstract class has at least one abstract method

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

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

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

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

... // other method implementations}

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

abstract-class-name obj = new abstract-class-name (); // ERROR!

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

www.neeviaPDF.com

Page 31: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 5 of 12 6/15/99

Example abstract class usage

abstract class Point {private int x, y;public Point(int x, int y) { this.x = x; this.y = y; }public void move(int dx, int dy){ x += dx; y += dy; plot(); }public abstract void plot(); // has no implementation

}

abstract class ColoredPoint extends Point {private int color;protected public ColoredPoint(int x, int y, int color){ super(x, y); this.color = color; }

}

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

}

Since ColoredPoint does not provide an implementation of the plot method, it must be declaredabstract. The SimpleColoredPoint class does implement the inherited plot method. It would be anerror to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Pointreference and initialize it with an instance of a subclass object that implements the plot method:

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

www.neeviaPDF.com

Page 32: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 6 of 12 6/15/99

Interfaces

An abstract class mixes the idea of mutable data in the form of instance variables, non-abstractmethods, and abstract methods. An abstract class with only static final instance variables and allabstract methods is called an interface. An interface is a specification, or contract, for a set ofmethods that a class that implements the interface must conform to in terms of the type signature ofthe methods. The class that implements the interface provides an implementation for each method,just as with an abstract method in an abstract class.

So, you can think of an interface as an abstract class with all abstract methods. The interface itselfcan have either public, package, private or protected access defined. All methods declared in aninterface are implicitly abstract and implicitly public. It is not necessary, and in fact consideredredundant to declare a method in an interface to be abstract.

You can define data in an interface, but it is less common to do so. If there are data fields defined inan interface, then they are implicitly defined to be:

• public.• static, and• final

In other words, any data defined in an interface are treated as public constants.

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?

www.neeviaPDF.com

Page 33: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 7 of 12 6/15/99

Interface declaration

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

public interface interface-name {

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

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

}

An interface declaraion is nothing more than a specification to which some class that purports toimplement the interface must conform to in its implementation. That is, a class the implements theinterface 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 someoperation to operate on objects that all conform to the same interface. So, you can define some code ina very general way, with a guarantee that by only using the methods defined in the interface, that allobjects 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 wouldexpect that any class that implements the Shape interface, would define an area method. So, if Ihave a list of references to objects that implement the Shape interface, I can legitimately invoke thearea method, abstractly, on each of these objects and expect to obtain as a result a value thatrepresents the area of some shape.

www.neeviaPDF.com

Page 34: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 8 of 12 6/15/99

Separation of Interface from Implementations

Interfaces are specifications for many possible implementations. Interfaces are used to define acontract for how you interact with an object, independent of the underlying implementation. Theobjective of an object-oriented programmer is to separate the specification of the interface from thehidden details of the implementation.

Consider the specification of a common LIFO stack.

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

}

Note that the methods in this interface are defined to operate on objects of type Object. Since a stackis a “container type”, it is very common to use the base class for all objects, namely Object, as thetype of the arguments and results to a container type. Since all objects ultimately inherit from classObject, we can always generically refer to any object in the system using an Object reference.However, when we pop from a stack, we have to explicitly type case from the very general typeObject 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(as opposed to implementing it ourselves) should we care?

www.neeviaPDF.com

Page 35: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 9 of 12 6/15/99

Stack implementation of the StackInterface

public class Stack implements StackInterface {

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

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

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

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

}

public Object peek() throws EmptyStackException { if (v.size() == 0)

throw new EmptyStackException(); return v.elementAt(v.size() - 1); }}

www.neeviaPDF.com

Page 36: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 10 of 12 6/15/99

Should a stack use or inherit from a vector?

The java.util.Stack class is defined as a subclass of the java.util.Vector class, rather than using aVector object as in the previous example. This sort of inheritance is not subtype inheritance, becausethe 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 contractby treating a stack object as a vector, and violating the LIFO specification of a stack.

public class Stack extends Vector { public Object push(Object item) {addElement(item); return item;} public Object pop() { Object obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } public Object peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } public boolean empty() { return size() == 0;}}

Vector v = new Stack(); // legal - base class reference to subclass objectv.insertElementAt(x, 2); // insert object x into Vector slot 2!!

www.neeviaPDF.com

Page 37: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 11 of 12 6/15/99

When to use an Interface vs when to use an abstract class

Having reviewed their basic properties, there are two primary differences between interfaces andabstract classes:

• an abstract class can have a mix of abstract and non-abstract methods, so some defaultimplementations can be defined in the abstract base class. An abstract class can also have staticmethods, static data, private and protected methods, etc. In other words, a class is a class, so itcan contain features inherent to a class. The downside to an abstract base class, is that since theiris 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 methodsingatures that a subclass is required to implement. An interfaces defines a set of typeconstraints, in the form of type signatures, that impose a requirement on a subclass to implementthe methods of the interface. Since you can inherit multiple interfaces, they are often a veryuseful mechanism to allow a class to have different behaviors in different situations of usage byimplementing multiple interfaces.

It is usually a good idea to implement an interface when you need to define methods that are to beexplicitly overridden by some subclass. If you then want some of the methods implemented withdefault implementations that will be inherited by a subclass, then create an implementation classfor the interface, and have other class inherit (extend) that class, or just use an abstract base classinstead of an interface.

www.neeviaPDF.com

Page 38: Java_Comb

Java Tutorial Extending Classes and Interfaces java-06.fm

Greg Lavender Slide 12 of 12 6/15/99

Example of default interface implementations

interface X {void f();int g();

}

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

}

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

}

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

X x = new Y();x.f();

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

www.neeviaPDF.com

Page 39: Java_Comb

1

Java ArrayJava Array

ww

w.n

eevi

aPDF.

com

Page 40: Java_Comb

2

Agenda● What is an array● Declaration of an array● Instantiation of an array● Accessing array element● Array length● Multi-dimensional array

ww

w.n

eevi

aPDF.

com

Page 41: Java_Comb

3

What is an Array?What is an Array?

ww

w.n

eevi

aPDF.

com

Page 42: Java_Comb

4

Introduction to Arrays● Suppose we have here three variables of type int with

different identifiers for each variable.

int number1; int number2; int number3;

number1 = 1; number2 = 2; number3 = 3;

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. ww

w.n

eevi

aPDF.

com

Page 43: Java_Comb

5

Introduction to Arrays● In Java and other programming languages, there is one

capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array.

● An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.

ww

w.n

eevi

aPDF.

com

Page 44: Java_Comb

6

Declaration ofDeclaration ofan Arrayan Arrayw

ww

.nee

viaP

DF.co

m

Page 45: Java_Comb

7

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

square brackets[], followed by the identifier name.

● For example, int []ages;

or int ages[];

ww

w.n

eevi

aPDF.

com

Page 46: Java_Comb

8

Instantiation of Instantiation of an Arrayan Arrayw

ww

.nee

viaP

DF.co

m

Page 47: Java_Comb

9

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

length with a constructor statement.

● Definitions:– Instantiation

● In Java, this means creation

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

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

ww

w.n

eevi

aPDF.

com

Page 48: Java_Comb

10

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

followed by the square brackets containing the number of elements you want the array to have.

● For example,//declaration int ages[];

//instantiate objectages = new int[100];

or, can also be written as, //declare and instantiate object int ages[] = new int[100];ww

w.n

eevi

aPDF.

com

Page 49: Java_Comb

11

Array Instantiationw

ww

.nee

viaP

DF.co

m

Page 50: Java_Comb

12

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

data.

● For example,int arr[] = {1, 2, 3, 4, 5};

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

ww

w.n

eevi

aPDF.

com

Page 51: Java_Comb

13

Sample Program1 //creates an array of boolean variables with identifier 2 //results. This array contains 4 elements that are 3 //initialized to values {true, false, true, false} 45 boolean results[] = { true, false, true, false }; 67 //creates an array of 4 double variables initialized 8 //to the values {100, 90, 80, 75}; 910 double []grades = {100, 90, 80, 75}; 1112 //creates an array of Strings with identifier days and 13 //initialized. This array contains 7 elements 1415 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,

“Sun”};

ww

w.n

eevi

aPDF.

com

Page 52: Java_Comb

14

Accessing Array Accessing Array ElementElementw

ww

.nee

viaP

DF.co

m

Page 53: Java_Comb

15

Accessing an Array Element● To access an array element, or a part of the array, you use

a number called an index or a subscript.

● index number or subscript– assigned to each member of the array, to allow the program to

access an individual member of the array.– begins with zero and progress sequentially by whole numbers to the

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

ww

w.n

eevi

aPDF.

com

Page 54: Java_Comb

16

Accessing an Array Element● For example, given the array we declared a while ago, we

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

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

ww

w.n

eevi

aPDF.

com

Page 55: Java_Comb

17

Accessing an Array Element● NOTE:

– once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data.

– 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.

ww

w.n

eevi

aPDF.

com

Page 56: Java_Comb

18

Accessing an Array Element● The following is a sample code on how to print all the

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

ww

w.n

eevi

aPDF.

com

Page 57: Java_Comb

19

Coding Guidelines1. It is usually better to initialize or instantiate the

array right away after you declare it. For example, the declaration,

int []arr = new int[100];

is preferred over,

int []arr; arr = new int[100];

ww

w.n

eevi

aPDF.

com

Page 58: Java_Comb

20

Coding Guidelines2. The elements of an n-element array have indexes

from 0 to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception.

3. Remember: You cannot resize an array.

ww

w.n

eevi

aPDF.

com

Page 59: Java_Comb

21

Array LengthArray Length

ww

w.n

eevi

aPDF.

com

Page 60: Java_Comb

22

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

use the length field of an array.

● The length field of an array returns the size of the array. It can be used by writing,

arrayName.length

ww

w.n

eevi

aPDF.

com

Page 61: Java_Comb

23

Array Length1 public class ArraySample { 2 public static void main( String[] args ){ 3 int[] ages = new int[100]; 45 for( int i=0; i<ages.length; i++ ){ 6 System.out.print( ages[i] ); 7 } 8 } 9 }

ww

w.n

eevi

aPDF.

com

Page 62: Java_Comb

24

Coding Guidelines1. When creating for loops to process the elements of an

array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays.

2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example,

final int ARRAY_SIZE = 1000; //declare a constant . . . int[] ages = new int[ARRAY_SIZE];

ww

w.n

eevi

aPDF.

com

Page 63: Java_Comb

25

Multi-DimensionalMulti-DimensionalArrayArrayw

ww

.nee

viaP

DF.co

m

Page 64: Java_Comb

26

Multidimensional Arrays● Multidimensional arrays are implemented as arrays of

arrays.

● Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.

ww

w.n

eevi

aPDF.

com

Page 65: Java_Comb

27

Multidimensional Arrays● For example,

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

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

// String array 4 rows x 2 columns String[][] dogs = {{ "terry", "brown" },

{ "Kristin", "white" }, { "toby", "gray"}, { "fido", "black"} };

ww

w.n

eevi

aPDF.

com

Page 66: Java_Comb

28

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

same as accessing the elements in a one dimensional array.

● For example, to access the first element in the first row of the array dogs, we write,

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

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

ww

w.n

eevi

aPDF.

com

Page 67: Java_Comb

29

Summary● Arrays

– Definition– Declaration– Instantiation and constructors (brief overview – to be discussed

more later)– Accessing an element– The length field– Multidimensional Arrays

ww

w.n

eevi

aPDF.

com

Page 68: Java_Comb

1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com

core

programming

Handling Mouse and Keyboard Events

www.neeviaPDF.com

Page 69: Java_Comb

Handling Mouse and Keyboard Events2 www.corewebprogramming.com

Agenda• General event-handling strategy• Handling events with separate listeners• Handling events by implementing interfaces• Handling events with named inner classes• Handling events with anonymous inner

classes• The standard AWT listener types• Subtleties with mouse events• Examples

www.neeviaPDF.com

Page 70: Java_Comb

Handling Mouse and Keyboard Events3 www.corewebprogramming.com

General Strategy• Determine what type of listener is of interest

– 11 standard AWT listener types, described on later slide. • ActionListener, AdjustmentListener,

ComponentListener, ContainerListener, FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, TextListener, WindowListener

• Define a class of that type– Implement interface (KeyListener, MouseListener, etc.)– Extend class (KeyAdapter, MouseAdapter, etc.)

• Register an object of your listener class with the window– w.addXxxListener(new MyListenerClass());

• E.g., addKeyListener, addMouseListener

www.neeviaPDF.com

Page 71: Java_Comb

Handling Mouse and Keyboard Events4 www.corewebprogramming.com

Handling Events with a Separate Listener: Simple Case

• Listener does not need to call any methods of the window to which it is attached

import java.applet.Applet;import java.awt.*;

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

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

}}

www.neeviaPDF.com

Page 72: Java_Comb

Handling Mouse and Keyboard Events5 www.corewebprogramming.com

Separate Listener: Simple Case(Continued)import java.awt.event.*;

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

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

}}

www.neeviaPDF.com

Page 73: Java_Comb

Handling Mouse and Keyboard Events6 www.corewebprogramming.com

Generalizing Simple Case

• What if ClickListener wants to draw a circle wherever mouse is clicked?

• Why can’t it just call getGraphics to get a Graphics object with which to draw?

• General solution:– Call event.getSource to obtain a reference to window or

GUI component from which event originated– Cast result to type of interest– Call methods on that reference

www.neeviaPDF.com

Page 74: Java_Comb

Handling Mouse and Keyboard Events7 www.corewebprogramming.com

Handling Events with Separate Listener: General Caseimport java.applet.Applet;import java.awt.*;

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

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

}}

www.neeviaPDF.com

Page 75: Java_Comb

Handling Mouse and Keyboard Events8 www.corewebprogramming.com

Separate Listener: General Case (Continued)import java.applet.Applet;import java.awt.*;import java.awt.event.*;

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

public void mousePressed(MouseEvent event) {Applet app = (Applet)event.getSource();Graphics g = app.getGraphics();g.fillOval(event.getX()-radius,

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

}}

www.neeviaPDF.com

Page 76: Java_Comb

Handling Mouse and Keyboard Events9 www.corewebprogramming.com

Separate Listener: General Case (Results)www.neeviaPDF.com

Page 77: Java_Comb

Handling Mouse and Keyboard Events10 www.corewebprogramming.com

Case 2: Implementing a Listener Interfaceimport java.applet.Applet;import java.awt.*;import java.awt.event.*;

public class CircleDrawer2 extends Appletimplements MouseListener {

private int radius = 25;

public void init() {setForeground(Color.blue);addMouseListener(this);

}

www.neeviaPDF.com

Page 78: Java_Comb

Handling Mouse and Keyboard Events11 www.corewebprogramming.com

Implementing a Listener Interface (Continued)public void mouseEntered(MouseEvent event) {}public void mouseExited(MouseEvent event) {}public void mouseReleased(MouseEvent event) {}public void mouseClicked(MouseEvent event) {}

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

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

}}

www.neeviaPDF.com

Page 79: Java_Comb

Handling Mouse and Keyboard Events12 www.corewebprogramming.com

Case 3: Named Inner Classesimport java.applet.Applet;import java.awt.*;import java.awt.event.*;

public class CircleDrawer3 extends Applet {public void init() {

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

}

www.neeviaPDF.com

Page 80: Java_Comb

Handling Mouse and Keyboard Events13 www.corewebprogramming.com

Named Inner Classes (Continued)

• Note: still part of class from previous slide

private class CircleListener extends MouseAdapter {

private int radius = 25;

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

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

}}

}

www.neeviaPDF.com

Page 81: Java_Comb

Handling Mouse and Keyboard Events14 www.corewebprogramming.com

Case 4: Anonymous Inner Classes

public class CircleDrawer4 extends Applet {public void init() {

setForeground(Color.blue);addMouseListener

(new MouseAdapter() {private int radius = 25;

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

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

}});

}}

www.neeviaPDF.com

Page 82: Java_Comb

Handling Mouse and Keyboard Events15 www.corewebprogramming.com

Event Handling Strategies: Pros and Cons

• Separate Listener– Advantages

• Can extend adapter and thus ignore unused methods• Separate class easier to manage

– Disadvantage• Need extra step to call methods in main window

• Main window that implements interface– Advantage

• No extra steps needed to call methods in main window

– Disadvantage• Must implement methods you might not care about

www.neeviaPDF.com

Page 83: Java_Comb

Handling Mouse and Keyboard Events16 www.corewebprogramming.com

Event Handling Strategies: Pros and Cons (Continued)

• Named inner class– Advantages

• Can extend adapter and thus ignore unused methods• No extra steps needed to call methods in main

window– Disadvantage

• A bit harder to understand• Anonymous inner class

– Advantages• Same as named inner classes• Even shorter

– Disadvantage• Much harder to understand

www.neeviaPDF.com

Page 84: Java_Comb

Handling Mouse and Keyboard Events17 www.corewebprogramming.com

Standard AWT Event Listeners(Summary)

Adapter ClassListener (If Any) Re

ActionListener addA AdjustmentListener addA ComponentListener ComponentAdapter addC ContainerListener ContainerAdapter addC FocusListener FocusAdapter addF ItemListener addI KeyListener KeyAdapter addK MouseListener MouseAdapter addM MouseMotionListener MouseMotionAdapter addM

TextListener addT WindowListener WindowAdapter addW

gistration Method ctionListener djustmentListener omponentListener ontainerListener ocusListener temListener eyListener ouseListener ouseMotionListener

extListener indowListener

www.neeviaPDF.com

Page 85: Java_Comb

Handling Mouse and Keyboard Events18 www.corewebprogramming.com

Standard AWT Event Listeners(Details)

• ActionListener– Handles buttons and a few other actions

• actionPerformed(ActionEvent event)• AdjustmentListener

– Applies to scrolling• adjustmentValueChanged(AdjustmentEvent event)

• ComponentListener– Handles moving/resizing/hiding GUI objects

• componentResized(ComponentEvent event)• componentMoved (ComponentEvent event)• componentShown(ComponentEvent event)• componentHidden(ComponentEvent event)

www.neeviaPDF.com

Page 86: Java_Comb

Handling Mouse and Keyboard Events19 www.corewebprogramming.com

Standard AWT Event Listeners(Details Continued)

• ContainerListener– Triggered when window adds/removes GUI controls

• componentAdded(ContainerEvent event)• componentRemoved(ContainerEvent event)

• FocusListener– Detects when controls get/lose keyboard focus

• focusGained(FocusEvent event)• focusLost(FocusEvent event)

www.neeviaPDF.com

Page 87: Java_Comb

Handling Mouse and Keyboard Events20 www.corewebprogramming.com

Standard AWT Event Listeners(Details Continued)

• ItemListener– Handles selections in lists, checkboxes, etc.

• itemStateChanged(ItemEvent event)• KeyListener

– Detects keyboard events• keyPressed(KeyEvent event) -- any key pressed

down• keyReleased(KeyEvent event) -- any key released• keyTyped(KeyEvent event) -- key for printable char

released

www.neeviaPDF.com

Page 88: Java_Comb

Handling Mouse and Keyboard Events21 www.corewebprogramming.com

Standard AWT Event Listeners(Details Continued)

• MouseListener– Applies to basic mouse events

• mouseEntered(MouseEvent event)• mouseExited(MouseEvent event)• mousePressed(MouseEvent event)• mouseReleased(MouseEvent event)• mouseClicked(MouseEvent event) -- Release without

drag– Applies on release if no movement since press

• MouseMotionListener– Handles mouse movement

• mouseMoved(MouseEvent event)• mouseDragged(MouseEvent event)

www.neeviaPDF.com

Page 89: Java_Comb

Handling Mouse and Keyboard Events22 www.corewebprogramming.com

Standard AWT Event Listeners(Details Continued)

• TextListener– Applies to textfields and text areas

• textValueChanged(TextEvent event)• WindowListener

– Handles high-level window events• windowOpened, windowClosing, windowClosed,

windowIconified, windowDeiconified, windowActivated, windowDeactivated

– windowClosing particularly useful

www.neeviaPDF.com

Page 90: Java_Comb

Handling Mouse and Keyboard Events23 www.corewebprogramming.com

Mouse Events: Details• MouseListener and MouseMotionListener

share event types• Location of clicks

– event.getX() and event.getY()• Double clicks

– Determined by OS, not by programmer– Call event.getClickCount()

• Distinguishing mouse buttons– Call event.getModifiers() and compare to

MouseEvent.Button2_MASK for a middle click and MouseEvent.Button3_MASK for right click.

– Can also trap Shift-click, Alt-click, etc.

www.neeviaPDF.com

Page 91: Java_Comb

Handling Mouse and Keyboard Events24 www.corewebprogramming.com

Simple Example: Spelling-Correcting Textfield

• KeyListener corrects spelling during typing• ActionListener completes word on ENTER• FocusListener gives subliminal hints

www.neeviaPDF.com

Page 92: Java_Comb

Handling Mouse and Keyboard Events25 www.corewebprogramming.com

Example: Simple Whiteboardimport java.applet.Applet;import java.awt.*;import java.awt.event.*;

public class SimpleWhiteboard extends Applet {protected int lastX=0, lastY=0;

public void init() {setBackground(Color.white);setForeground(Color.blue);addMouseListener(new PositionRecorder());addMouseMotionListener(new LineDrawer());

}

protected void record(int x, int y) {lastX = x; lastY = y;

}

www.neeviaPDF.com

Page 93: Java_Comb

Handling Mouse and Keyboard Events26 www.corewebprogramming.com

Simple Whiteboard (Continued)

private class PositionRecorder extends MouseAdapter {public void mouseEntered(MouseEvent event) {

requestFocus(); // Plan ahead for typingrecord(event.getX(), event.getY());

}

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

}}...

www.neeviaPDF.com

Page 94: Java_Comb

Handling Mouse and Keyboard Events27 www.corewebprogramming.com

Simple Whiteboard (Continued)

...private class LineDrawer extends MouseMotionAdapter {

public void mouseDragged(MouseEvent event) {int x = event.getX();int y = event.getY();Graphics g = getGraphics();g.drawLine(lastX, lastY, x, y);record(x, y);

}}

}

www.neeviaPDF.com

Page 95: Java_Comb

Handling Mouse and Keyboard Events28 www.corewebprogramming.com

Simple Whiteboard (Results)www.neeviaPDF.com

Page 96: Java_Comb

Handling Mouse and Keyboard Events29 www.corewebprogramming.com

Whiteboard: Adding Keyboard Events

import java.applet.Applet;import java.awt.*;import java.awt.event.*;

public class Whiteboard extends SimpleWhiteboard {protected FontMetrics fm;

public void init() {super.init();Font font = new Font("Serif", Font.BOLD, 20);setFont(font);fm = getFontMetrics(font);addKeyListener(new CharDrawer());

}

www.neeviaPDF.com

Page 97: Java_Comb

Handling Mouse and Keyboard Events30 www.corewebprogramming.com

Whiteboard (Continued)...private class CharDrawer extends KeyAdapter {

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

public void keyTyped(KeyEvent event) {String s = String.valueOf(event.getKeyChar());getGraphics().drawString(s, lastX, lastY);record(lastX + fm.stringWidth(s), lastY);

}}

}

www.neeviaPDF.com

Page 98: Java_Comb

Handling Mouse and Keyboard Events31 www.corewebprogramming.com

Whiteboard (Results)www.neeviaPDF.com

Page 99: Java_Comb

Handling Mouse and Keyboard Events32 www.corewebprogramming.com

Summary• General strategy

– Determine what type of listener is of interest• Check table of standard types

– Define a class of that type• Extend adapter separately, implement interface,

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

– Register an object of your listener class with the window• Call addXxxListener

• Understanding listeners– Methods give specific behavior.

• Arguments to methods are of type XxxEvent– Methods in MouseEvent of particular interest

www.neeviaPDF.com

Page 100: Java_Comb

33 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com

core

programming

Questions?

www.neeviaPDF.com

Page 101: Java_Comb

Handling Mouse and Keyboard Events34 www.corewebprogramming.com

Preview• Whiteboard had freehand drawing only

– Need GUI controls to allow selection of other drawing methods

• Whiteboard had only “temporary” drawing– Covering and reexposing window clears drawing– After cover multithreading, we’ll see solutions to this

problem• Most general is double buffering

• Whiteboard was “unshared”– Need network programming capabilities so that two

different whiteboards can communicate with each other

www.neeviaPDF.com

Page 102: Java_Comb

1

InheritanceInheritance

ww

w.n

eevi

aPDF.

com

Page 103: Java_Comb

2

Agenda● What is and Why Inheritance?● How to derive a sub-class?● Object class● Constructor calling chain● “super” keyword● Overriding methods● Hiding methods● Hiding fields● Type casting● Final class and final methodsww

w.n

eevi

aPDF.

com

Page 104: Java_Comb

3

What is What is Inheritance?Inheritance?w

ww

.nee

viaP

DF.co

m

Page 105: Java_Comb

4

What is Inheritance?

● Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class).

● A primary feature of object-oriented programming along with encapsulation and polymorphism

ww

w.n

eevi

aPDF.

com

Page 106: Java_Comb

5

Why Inheritance? Reusability● Benefits of Inheritance in OOP : Reusability

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

all subclasses. – Once a set of properties (fields) are defined in a super

class, the same set of properties are inherited by all subclasses● A class and its children share common set of properties

– A subclass only needs to implement the differences between itself and the parent. ww

w.n

eevi

aPDF.

com

Page 107: Java_Comb

6

How to derive aHow to derive asub-class?sub-class?w

ww

.nee

viaP

DF.co

m

Page 108: Java_Comb

7

extends keyword● To derive a child class, we use the extends keyword. ● Suppose we have a parent class called Person.

public class Person { protected String name; protected String address;

/** * Default constructor */ public Person(){

System.out.println(“Inside Person:Constructor”); name = ""; address = "";

}. . . .

}

ww

w.n

eevi

aPDF.

com

Page 109: Java_Comb

8

extends keyword

● Now, we want to create another class named Student● Since a student is also a person, we decide to just

extend the class Person, so that we can inherit all the properties and methods of the existing class Person.

● To do this, we write,

public class Student extends Person { public Student(){

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

}ww

w.n

eevi

aPDF.

com

Page 110: Java_Comb

9

What You Can Do in a Sub-class

● A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent, no matter what package the subclass is in

● If the subclass is in the same package as its parent, it also inherits the package-private members (fields or methods) of the parent

ww

w.n

eevi

aPDF.

com

Page 111: Java_Comb

10

What You Can Do in a Sub-classRegarding Fields

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

● You can declare new fields in the subclass that are not in the super class

● You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended).

● A subclass does not inherit the private members of 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.ww

w.n

eevi

aPDF.

com

Page 112: Java_Comb

11

What You Can Do in a Sub-classRegarding Methods

● The inherited methods can be used directly as they are.● You can write a new instance method in the subclass that

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 has the same signature as the one in the super class, thus hiding it.

● You can declare new methods in the subclass that are not in the super class.

ww

w.n

eevi

aPDF.

com

Page 113: Java_Comb

12

Object ClassObject Class

ww

w.n

eevi

aPDF.

com

Page 114: Java_Comb

13

Object Class● Object class is mother of all classes

– In Java language, all classes are sub-classed (extended) from the Object super class

– Object class is the only class that does not have a parent class

● Defines and implements behavior common to all classes including the ones that you write– getClass()– equals()– toString()– ...ww

w.n

eevi

aPDF.

com

Page 115: Java_Comb

14

Class Hierarchy● A sample class hierarchy

ww

w.n

eevi

aPDF.

com

Page 116: Java_Comb

15

Super class & Sub class● Super class (Parent class)

– Any class above a specific class in the class hierarchy.● Sub class (Child class)

– Any class below a specific class in the class hierarchy.

ww

w.n

eevi

aPDF.

com

Page 117: Java_Comb

16

Constructor CallingConstructor CallingChainChainw

ww

.nee

viaP

DF.co

m

Page 118: Java_Comb

17

How Constructor method of a Super class gets called

● A subclass constructor invokes the constructor of the super class implicitly – 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 sub-class's constructor method is invoked

● A subclass constructor can invoke the constructor of the super explicitly by using the “super” keyword – 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

ww

w.n

eevi

aPDF.

com

Page 119: Java_Comb

18

Example: Constructor Calling Chain

● To illustrate this, consider the following code,

● In the code, we create an object of class Student. The output of the program is,

public static void main( String[] args ){ Student anna = new Student();

}

Inside Person:Constructor Inside Student:Constructor

ww

w.n

eevi

aPDF.

com

Page 120: Java_Comb

19

Example: Constructor Calling Chain

● The program flow is shown below.

ww

w.n

eevi

aPDF.

com

Page 121: Java_Comb

20

“ “super” keywordsuper” keyword

ww

w.n

eevi

aPDF.

com

Page 122: Java_Comb

21

The “super” keyword

● A subclass can also explicitly call a constructor of its immediate super class.

● This is done by using the super constructor call.

● A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class, based on the arguments passed.

ww

w.n

eevi

aPDF.

com

Page 123: Java_Comb

22

The “super” keyword

● For example, given our previous example classes Person and Student, we show an example of a super constructor call.

● Given the following code for Student,

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

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

ww

w.n

eevi

aPDF.

com

Page 124: Java_Comb

23

The “super” keyword

● Few things to remember when using the super constructor call:– The super() call must occur as the first statement in a

constructor – The super() call can only be used in a constructor (not in

ordinary methods)

ww

w.n

eevi

aPDF.

com

Page 125: Java_Comb

24

The “super” keyword

● Another use of super is to refer to members of the super class (just like the this reference ).

● For example,

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

}

ww

w.n

eevi

aPDF.

com

Page 126: Java_Comb

25

Overriding MethodsOverriding Methods

ww

w.n

eevi

aPDF.

com

Page 127: Java_Comb

26

Overriding methods● If a derived class needs to have a different

implementation of a certain instance method from that of the super class, override that instance method in the sub class– Note that the scheme of overriding applies only to

instance methods– For static methods, it is called hiding methods

● The overriding method has the same name, number and type of parameters, and return type as 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

ww

w.n

eevi

aPDF.

com

Page 128: Java_Comb

27

Example: Overriding Methods

● Suppose we have the following implementation for the getName method in the Person super class, public class Person {

: : public String getName(){

System.out.println("Parent: getName"); return name;

} }

ww

w.n

eevi

aPDF.

com

Page 129: Java_Comb

28

Example: Overriding Methods● To override the getName method of the super class

Person in the subclass Student, reimplement the method with the same signature

● 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,

public class Student extends Person{: public String getName(){

System.out.println("Student: getName"); return name;

} :

}

Student: getName

ww

w.n

eevi

aPDF.

com

Page 130: Java_Comb

29

Modifiers in the Overriding Methods

● The access specifier for an overriding method can allow more, but not less, access than the overridden method– For example, a protected instance method in the super

class can be made public, but not private, in the subclass.● You will get a compile-time error if you attempt to

change an instance method in the super class to a class method in the subclass, and vice versa

ww

w.n

eevi

aPDF.

com

Page 131: Java_Comb

30

Runtime Runtime Polymorphism with Polymorphism with Overriding MethodsOverriding Methodsww

w.n

eevi

aPDF.

com

Page 132: Java_Comb

31

What is Polymorphism?

● Polymorphism in a Java program– The ability of a reference variable to change

behavior according to what object instance it is holding.

– This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to

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

w.n

eevi

aPDF.

com

Page 133: Java_Comb

32

Example: Runtime Polymorphism

Code:

Person person2 = new Student(); person2.myMethod("test4"); Person person3 = new InternationalStudent(); person3.myMethod("test5");

Result:

myMethod(test4) in Student class is called myMethod(test5) in InternationalStudent class is called

ww

w.n

eevi

aPDF.

com

Page 134: Java_Comb

33

Hiding MethodsHiding Methods

ww

w.n

eevi

aPDF.

com

Page 135: Java_Comb

34

Hiding Methods

● If a subclass defines a class method (static method) with the same signature as a class method in the super class, the method in the subclass “hides” the one in the super class

ww

w.n

eevi

aPDF.

com

Page 136: Java_Comb

35

Example: Coding of Hiding Static Method

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

// The testClassMethod() of the child class hides the one of the// super class – it looks like overriding, doesn't it? But// there is difference. We will talk about in the following slide.

class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); }}

ww

w.n

eevi

aPDF.

com

Page 137: Java_Comb

36

Overriding Method vs. Hiding Method

● Hiding a static method of a super class looks like overriding an instance method of a super class

● The difference comes during runtime– When you override an instance method, you get the benefit

of run-time polymorphism– When you override an static method, there is no runt-time

polymorphism

ww

w.n

eevi

aPDF.

com

Page 138: Java_Comb

37

Example: Overriding Method vs. Hiding Method during Runtime

// Create object instance of Cat. Cat myCat = new Cat(); // The object instance is Cat type // and assigned to Animal type variable. Animal myAnimal2 = myCat; // For static method, the static method of // the super class gets called. Animal.testClassMethod(); // 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();

ww

w.n

eevi

aPDF.

com

Page 139: Java_Comb

38

Hiding FieldsHiding Fields

ww

w.n

eevi

aPDF.

com

Page 140: Java_Comb

39

Hiding Fields

● Within a sub class, a field that has the same name as a field in the super class hides the super class' field, even if their types are different

● Within the subclass, the field in the super class cannot be referenced by its simple name– Instead, the field must be accessed through super keyword

● Generally speaking, hiding fields is not a recommended programming practice as it makes code difficult to read

ww

w.n

eevi

aPDF.

com

Page 141: Java_Comb

40

Type CastingType Casting

ww

w.n

eevi

aPDF.

com

Page 142: Java_Comb

41

What is “Type”?

● When an object instance is created from a class, we say the object instance is “type” of the class and its super classes

● Example: Student student1 = new Student();

– student1 object instance is the type of Student or it is Student type

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

– student1 object instance is also type of Object ww

w.n

eevi

aPDF.

com

Page 143: Java_Comb

42

What is Significance?

● An object instance of a particular type can be used in any place where an instance of the type and its super type is called for

● Example:– student1 object instance is a “type” of TuftsStudent,

Student, and Peson– student1 object can be used in any place where object

instance of the type of TuftsStudent, Student, or Person is called for

● This enables polymorphismww

w.n

eevi

aPDF.

com

Page 144: Java_Comb

43

Implicit Type Casting ● An object instance of a subclass can be assigned to a

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

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

classTuftsStudent tuftstudent = new TuftsStudent();Student student = tuftsstudent; // Implicit type casting Person person = tuftsstudent; // Implicit type castingObject object = tuftsstudent; // Implicit type casting

ww

w.n

eevi

aPDF.

com

Page 145: Java_Comb

44

Type Casting between Objects

tuftsstudent

student

person

TuftsStudentObject instance

ww

w.n

eevi

aPDF.

com

Page 146: Java_Comb

45

Explicit Type Casting

● An object instance of a super class must be assigned to a variable (reference) of a child class through explicit type casting– Not doing it will result in a compile error since the type

assignment is not safe– Compiler wants to make sure you know what you are doing

● Example– Let's assume Student class is a child class of Person classPerson person1 = new Student(); Student student1 = (Student) person1; // Explicit type casting

ww

w.n

eevi

aPDF.

com

Page 147: Java_Comb

46

Runtime Type Mismatch Exception

● Even with explicit casting, you could still end up having a runtime error

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

classPerson person1 = new Student(); Person person2 = new Teacher(); Student student1 = (Student) person1; // Explicit type casting// No compile error, but runtime type mismatch exceptionStudent student2 = (Student) person2;

ww

w.n

eevi

aPDF.

com

Page 148: Java_Comb

47

Use instanceof Operator toPrevent Runtime Type Mismatch Error

● You can check the type of the object instance using instanceof before the type casting

● ExamplePerson person1 = new Student(); Person person2 = new Teacher();

// Do the casting only when the type is verified if (person2 instanceof Student) { Student student2 = (Student) person2;}

ww

w.n

eevi

aPDF.

com

Page 149: Java_Comb

48

Final Class &Final Class &Final MethodFinal Methodw

ww

.nee

viaP

DF.co

m

Page 150: Java_Comb

49

Final Classes● Final Classes

– Classes that cannot be extended– To declare final classes, we write,

public final ClassName{. . .

}

● Example:

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

public final class Person { . . .

}

ww

w.n

eevi

aPDF.

com

Page 151: Java_Comb

50

Final Methods

● Final Methods– Methods that cannot be overridden– To declare final methods, we write,

public final [returnType] [methodName]([parameters]){. . .

}

● Static methods are automatically final

ww

w.n

eevi

aPDF.

com

Page 152: Java_Comb

51

Example: final Methods

public final String getName(){ return name; }

ww

w.n

eevi

aPDF.

com

Page 153: Java_Comb

52

InheritanceInheritance

ww

w.n

eevi

aPDF.

com

Page 154: Java_Comb

1

Abstract Class &Abstract Class &Java InterfaceJava Interface

ww

w.n

eevi

aPDF.

com

Page 155: Java_Comb

2

Agenda● What is an Abstract method and an Abstract class?● What is Interface?● Why Interface?● Interface as a Type ● Interface vs. Class● Defining an Interface● Implementing an Interface● Implementing multiple Interface's● Inheritance among Interface's● Interface and Polymorphism● Rewriting an Interface

ww

w.n

eevi

aPDF.

com

Page 156: Java_Comb

3

What is What is an Abstract Class?an Abstract Class?ww

w.n

eevi

aPDF.

com

Page 157: Java_Comb

4

Abstract Methods

● Methods that do not have implementation (body)● To create an abstract method, just write the method

declaration without the body and use the abstract keyword– No { }

● For example,

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

w.n

eevi

aPDF.

com

Page 158: Java_Comb

5

Abstract Class

● An abstract class is a class that contains one or more abstract methods

● An abstract class cannot instantiated// You will get a compile error on the following codeMyAbstractClass a1 = new MyAbstractClass();

● Another class (Concrete class) has to provide implementation of abstract methods– Concrete class has to implement all abstract methods of

the abstract class in order to be used for instantiation– Concrete class uses extends keywordww

w.n

eevi

aPDF.

com

Page 159: Java_Comb

6

Sample Abstract Classpublic abstract class LivingThing {

public void breath(){ System.out.println("Living Thing breathing...");

}

public void eat(){ System.out.println("Living Thing eating...");

}

/** * Abstract method walk() * We want this method to be implemented by a

* Concrete class. */ public abstract void walk();

} ww

w.n

eevi

aPDF.

com

Page 160: Java_Comb

7

Extending an Abstract Class

● When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated.

● For example, public class Human extends LivingThing {

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

}

}

ww

w.n

eevi

aPDF.

com

Page 161: Java_Comb

8

When to use Abstract Methods &Abstract Class?

● Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations– These subclasses extend the same Abstract class and

provide different implementations for the abstract methods

● Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.

ww

w.n

eevi

aPDF.

com

Page 162: Java_Comb

9

What is Interface?What is Interface?

ww

w.n

eevi

aPDF.

com

Page 163: Java_Comb

10

What is an Interface?

● It defines a standard and public way of specifying the behavior of classes– Defines a contract

● All methods of an interface are abstract methods – Defines the signatures of a set of methods, without the

body (implementation of the methods)● A concrete class must implement the interface (all

the abstract methods of the Interface) ● It allows classes, regardless of their locations in the

class hierarchy, to implement common behaviorsww

w.n

eevi

aPDF.

com

Page 164: Java_Comb

11

Example: Interface

// Note that Interface contains just set of method

// signatures without any implementations.

// No need to say abstract modifier for each method

// since it assumed.

public interface Relation {

public boolean isGreater( Object a, Object b);

public boolean isLess( Object a, Object b);

public boolean isEqual( Object a, Object b);

} ww

w.n

eevi

aPDF.

com

Page 165: Java_Comb

12

Example 2: OperatorCar Interface

public interface OperateCar {

// constant declarations, if any

// method signatures int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); ...... // more method signatures}

ww

w.n

eevi

aPDF.

com

Page 166: Java_Comb

13

Why Interface?Why Interface?

ww

w.n

eevi

aPDF.

com

Page 167: Java_Comb

14

Why do we use Interfaces?Reason #1

● To reveal an object's programming interface (functionality of the object) without revealing its implementation– This is the concept of encapsulation– The implementation can change without affecting

the caller of the interface– The caller does not need the implementation at the

compile time● It needs only the interface at the compile time● During runtime, actual object instance is associated

with the interface typeww

w.n

eevi

aPDF.

com

Page 168: Java_Comb

15

Why do we use Interfaces?Reason #2

● To have unrelated classes implement similar methods (behaviors)– One class is not a sub-class of another

● Example:– Class Line and class MyInteger

● They are not related through inheritance● You want both to implement comparison methods – 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

ww

w.n

eevi

aPDF.

com

Page 169: Java_Comb

16

Why do we use Interfaces?Reason #3

● To model multiple inheritance – A class can implement multiple interfaces while it can

extend only one class

ww

w.n

eevi

aPDF.

com

Page 170: Java_Comb

17

Interface vs. Abstract Class

● All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods– Abstract methods of abstract class have abstract

modifier● An interface can only define constants while

abstract class can have fields● Interfaces have no direct inherited relationship with

any particular class, they are defined independently– Interfaces themselves have inheritance relationship

among themselvesww

w.n

eevi

aPDF.

com

Page 171: Java_Comb

18

Interface as aInterface as aTypeTypew

ww

.nee

viaP

DF.co

m

Page 172: Java_Comb

19

Interface as a Type

● When you define a new interface, you are defining a new reference type

● You can use interface names anywhere you can use any other type name

● If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface

ww

w.n

eevi

aPDF.

com

Page 173: Java_Comb

20

Example: Interface as a Type

● Let's say Person class implements PersonInterface interface

● You can do – Person p1 = new Person();– PersonInterface pi1 = p1;– PersonInterface pi2 = new Person();

ww

w.n

eevi

aPDF.

com

Page 174: Java_Comb

21

Interface vs. ClassInterface vs. Class

ww

w.n

eevi

aPDF.

com

Page 175: Java_Comb

22

Interface vs. Class: Commonality

● Interfaces and classes are both types– This means that an interface can be used in places

where a class can be used– For example:

// Recommended practice

PersonInterface pi = new Person();

// Not recommended practice

Person pc = new Person();

● Interface and Class can both define methods

ww

w.n

eevi

aPDF.

com

Page 176: Java_Comb

23

Interface vs. Class: Differences

● The methods of an Interface are all abstract methods– They cannot have bodies

● You cannot create an instance from an interface– For example:

PersonInterface pi = new PersonInterface(); //ERROR!

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

ww

w.n

eevi

aPDF.

com

Page 177: Java_Comb

24

Defining InterfaceDefining Interface

ww

w.n

eevi

aPDF.

com

Page 178: Java_Comb

25

Defining Interfaces

● To define an interface, we write:

public interface [InterfaceName] { //some methods without the body}

ww

w.n

eevi

aPDF.

com

Page 179: Java_Comb

26

Defining Interfaces

● As an example, let's create an interface that defines relationships between two objects according to the “natural order” of the objects.

public interface Relation {

public boolean isGreater( Object a, Object b);

public boolean isLess( Object a, Object b);

public boolean isEqual( Object a, Object b);

}

ww

w.n

eevi

aPDF.

com

Page 180: Java_Comb

27

Implementing Implementing InterfaceInterfacew

ww

.nee

viaP

DF.co

m

Page 181: Java_Comb

28

Implementing Interfaces● To create a concrete class that implements an interface,

use the implements keyword.

/**

* Line class implements Relation interface

*/

public class Line implements Relation {

private double x1;

private double x2;

private double y1;

private double y2;

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

this.x1 = x1;

this.x2 = x2;

this.y1 = y1;

this.y2 = y2;

}

// More code follows

ww

w.n

eevi

aPDF.

com

Page 182: Java_Comb

29

Implementing Interfacespublic double getLength(){

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

return length;}

public boolean isGreater( Object a, Object b){double aLen = ((Line)a).getLength();double bLen = ((Line)b).getLength();return (aLen > bLen);

}

public boolean isLess( Object a, Object b){double aLen = ((Line)a).getLength();double bLen = ((Line)b).getLength();return (aLen < bLen);

}

public boolean isEqual( Object a, Object b){double aLen = ((Line)a).getLength();double bLen = ((Line)b).getLength();return (aLen == bLen);

}}

ww

w.n

eevi

aPDF.

com

Page 183: Java_Comb

30

Implementing Interfaces

● When your class tries to implement an interface, always make sure that you implement all the methods of that interface, or else, you would encounter this error,

Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation

public class Line implements Relation

^

1 errorww

w.n

eevi

aPDF.

com

Page 184: Java_Comb

31

Implementing Class

● Implementing class can have its own methods● Implementing class extend a single super class or

abstract class

ww

w.n

eevi

aPDF.

com

Page 185: Java_Comb

32

Implementing Implementing Multiple InterfacesMultiple Interfacesww

w.n

eevi

aPDF.

com

Page 186: Java_Comb

33

Relationship of an Interface to a Class

● A concrete class can only extend one super class, but it can implement multiple Interfaces– The Java programming language does not permit

multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.

● All abstract methods of all interfaces have to be implemented by the concrete class

ww

w.n

eevi

aPDF.

com

Page 187: Java_Comb

34

Example: Implementing Multiple Interfaces

● A concrete class extends one super class but multiple Interfaces:

public class ComputerScienceStudent extends Student

implements PersonInterface, AnotherInterface,

Thirdinterface{

// All abstract methods of all interfaces // need to be implemented.}ww

w.n

eevi

aPDF.

com

Page 188: Java_Comb

35

Inheritance Inheritance Among InterfacesAmong Interfacesww

w.n

eevi

aPDF.

com

Page 189: Java_Comb

36

Inheritance Among Interfaces

● Interfaces are not part of the class hierarchy● However, interfaces can have inheritance

relationship among themselves

public interface PersonInterface {void doSomething();

}

public interface StudentInterface extends PersonInterface {

void doExtraSomething();}ww

w.n

eevi

aPDF.

com

Page 190: Java_Comb

37

Interface & Interface & PolymorphismPolymorphismw

ww

.nee

viaP

DF.co

m

Page 191: Java_Comb

38

Interface and Polymorphism

● Interfaces exhibit polymorphism as well, since program may call an interface method, and the proper version of that method will be executed depending on the type of object instance passed to the interface method call

ww

w.n

eevi

aPDF.

com

Page 192: Java_Comb

39

Rewriting InterfacesRewriting Interfaces

ww

w.n

eevi

aPDF.

com

Page 193: Java_Comb

40

Problem of Rewriting an ExistingInterface

● Consider an interface that you have developed called DoIt:public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s);}

● Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes:

public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); 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

ww

w.n

eevi

aPDF.

com

Page 194: Java_Comb

41

Solution of Rewriting an ExistingInterface

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

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

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

ww

w.n

eevi

aPDF.

com

Page 195: Java_Comb

42

When to Use an When to Use an Abstract Class over Abstract Class over

an Interface?an Interface?ww

w.n

eevi

aPDF.

com

Page 196: Java_Comb

43

When to use an Abstract Class over Interface?

● For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes– Reducing the duplication

● For abstract methods, the motivation is the same with the ones in the interface – to impose a common behavior for all sub-classes without dictating how to implement it

● Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract classww

w.n

eevi

aPDF.

com

Page 197: Java_Comb

44

Abstract Class &Abstract Class &Java InterfaceJava Interface

ww

w.n

eevi

aPDF.

com

Page 198: Java_Comb

1

Java I/O StreamJava I/O Stream

ww

w.n

eevi

aPDF.

com

Page 199: Java_Comb

2

Topics

● What is an I/O stream?● Types of Streams● Stream class hierarchy● Control flow of an I/O operation using Streams● Byte streams● Character streams● Buffered streams● Standard I/O streams● Data streams● Object streams● File class

ww

w.n

eevi

aPDF.

com

Page 200: Java_Comb

3

What is an I/O What is an I/O Stream?Stream?w

ww

.nee

viaP

DF.co

m

Page 201: Java_Comb

4

I/O Streams

● An I/O Stream represents an input source or an output destination

● A stream can represent many different kinds of sources and destinations– disk files, devices, other programs, a network

socket, and memory arrays● Streams support many different kinds of data– simple bytes, primitive data types, localized

characters, and objects● Some streams simply pass on data; others

manipulate and transform the data in useful ways.

ww

w.n

eevi

aPDF.

com

Page 202: Java_Comb

5

I/O Streams

● No matter how they work internally, all streams present the same simple model to programs that use them– A stream is a sequence of data

ww

w.n

eevi

aPDF.

com

Page 203: Java_Comb

6

Input Stream

● A program uses an input stream to read data from a source, one item at a time

source:java.sun.com

ww

w.n

eevi

aPDF.

com

Page 204: Java_Comb

7

Output Stream

● A program uses an output stream to write data to a destination, one item at time

ww

w.n

eevi

aPDF.

com

Page 205: Java_Comb

8

Types of StreamsTypes of Streams

ww

w.n

eevi

aPDF.

com

Page 206: Java_Comb

9

General Stream Types● Character and Byte Streams– Character vs. Byte

● Input and Output Streams– Based on source or destination

● Node and Filter Streams– Whether the data on a stream is manipulated or

transformed or not

ww

w.n

eevi

aPDF.

com

Page 207: Java_Comb

10

Character and Byte Streams● Byte streams– For binary data– Root classes for byte streams:

● The InputStream Class● The OutputStream Class● Both classes are abstract

● Character streams– For Unicode characters– Root classes for character streams:

● The Reader class● The Writer class● Both classes are abstract

ww

w.n

eevi

aPDF.

com

Page 208: Java_Comb

11

Input and Output Streams● Input or source streams– Can read from these streams– Root classes of all input streams:

● The InputStream Class● The Reader Class

● Output or sink (destination) streams– Can write to these streams– Root classes of all output streams:

● The OutputStream Class ● The Writer Classww

w.n

eevi

aPDF.

com

Page 209: Java_Comb

12

Node and Filter Streams● Node streams (Data sink stream)– Contain the basic functionality of reading or writing

from a specific location– Types of node streams include files, memory and

pipes● Filter streams (Processing stream)– Layered onto node streams between threads or

processes– For additional functionality- altering or managing

data in the stream● Adding layers to a node stream is called stream

chaining

ww

w.n

eevi

aPDF.

com

Page 210: Java_Comb

13

Stream Class Stream Class HierarchyHierarchyw

ww

.nee

viaP

DF.co

m

Page 211: Java_Comb

14

StreamsInputStream

OutputStream

Reader

Writer

ww

w.n

eevi

aPDF.

com

Page 212: Java_Comb

15

Abstract Classes

● InputStream & OutputStream● Reader & Writer

ww

w.n

eevi

aPDF.

com

Page 213: Java_Comb

16

InputStream Abstract Classw

ww

.nee

viaP

DF.co

m

Page 214: Java_Comb

17

InputStream Abstract Classw

ww

.nee

viaP

DF.co

m

Page 215: Java_Comb

18

Node InputStream Classesw

ww

.nee

viaP

DF.co

m

Page 216: Java_Comb

19

Filter InputStream Classesw

ww

.nee

viaP

DF.co

m

Page 217: Java_Comb

20

OutputStream Abstract Classw

ww

.nee

viaP

DF.co

m

Page 218: Java_Comb

21

Node OutputStream Classesw

ww

.nee

viaP

DF.co

m

Page 219: Java_Comb

22

Filter OutputStream Classesw

ww

.nee

viaP

DF.co

m

Page 220: Java_Comb

23

The Reader Class: Methodsw

ww

.nee

viaP

DF.co

m

Page 221: Java_Comb

24

The Reader Class: Methodsw

ww

.nee

viaP

DF.co

m

Page 222: Java_Comb

25

Node Reader Classesw

ww

.nee

viaP

DF.co

m

Page 223: Java_Comb

26

Filter Reader Classesw

ww

.nee

viaP

DF.co

m

Page 224: Java_Comb

27

The Writer Class: Methodsw

ww

.nee

viaP

DF.co

m

Page 225: Java_Comb

28

Node Writer Classesw

ww

.nee

viaP

DF.co

m

Page 226: Java_Comb

29

Filter Writer Classesw

ww

.nee

viaP

DF.co

m

Page 227: Java_Comb

30

Control Flow ofControl Flow ofI/O Operation usingI/O Operation using

StreamsStreamsww

w.n

eevi

aPDF.

com

Page 228: Java_Comb

31

Control Flow of an I/O operation

Create a stream object and associate it with a data-source (data-destination)

Give the stream object the desired functionality through stream chaining

while (there is more information)

read(write) next data from(to) the stream

close the stream

ww

w.n

eevi

aPDF.

com

Page 229: Java_Comb

32

Byte StreamByte Stream

ww

w.n

eevi

aPDF.

com

Page 230: Java_Comb

33

Byte Stream

● Programs use byte streams to perform input and output of 8-bit bytes

● All byte stream classes are descended from InputStream and OutputStream

● There are many byte stream classes– FileInputStream and FileOutputStream

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

ww

w.n

eevi

aPDF.

com

Page 231: Java_Comb

34

When Not to Use Byte Streams?

● Byte Stream represents a kind of low-level I/O that you should avoid– If the data contains character data, the best

approach is to use character streams– There are also streams for more complicated data

types● Byte streams should only be used for the most

primitive I/O● All other streams are based on byte streamw

ww

.nee

viaP

DF.co

m

Page 232: Java_Comb

35

Example: FileInputStream & FileOutputStream

public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c;

while ((c = in.read()) != -1) { out.write(c); } } // More code

ww

w.n

eevi

aPDF.

com

Page 233: Java_Comb

36

Example: FileInputStream & FileOutputStream

finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}

ww

w.n

eevi

aPDF.

com

Page 234: Java_Comb

37

Simple Byte Stream input and output

ww

w.n

eevi

aPDF.

com

Page 235: Java_Comb

38

Character StreamCharacter Stream

ww

w.n

eevi

aPDF.

com

Page 236: Java_Comb

39

Character Stream

● The Java platform stores character values using Unicode conventions

● Character stream I/O automatically translates this internal format to and from the local character set.– In Western locales, the local character set is usually

an 8-bit superset of ASCII.● All character stream classes are descended from

Reader and Writer● As with byte streams, there are character stream

classes that specialize in file I/O: FileReader and FileWriter.

ww

w.n

eevi

aPDF.

com

Page 237: Java_Comb

40

Character Stream● For most applications, I/O with character streams is

no more complicated than I/O with byte streams.– Input and output done with stream classes

automatically translates to and from the local character set.

– A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.

– 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.

ww

w.n

eevi

aPDF.

com

Page 238: Java_Comb

41

Example: FileReader & FileWriter

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

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

int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } // More code

ww

w.n

eevi

aPDF.

com

Page 239: Java_Comb

42

Example: FileReader & FileWriter

finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }}

ww

w.n

eevi

aPDF.

com

Page 240: Java_Comb

43

Character Stream and Byte Stream

● Character streams are often "wrappers" for byte streams

● The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes.– FileReader, for example, uses FileInputStream,

while FileWriter uses FileOutputStream

ww

w.n

eevi

aPDF.

com

Page 241: Java_Comb

44

Line-Oriented I/O

● Character I/O usually occurs in bigger units than single characters– One common unit is the line: a string of

characters with a line terminator at the end– A line terminator can be a carriage-return/line-

feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n").

ww

w.n

eevi

aPDF.

com

Page 242: Java_Comb

45

Example: Line-oriented I/O File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); BufferedReader inputStream = new BufferedReader(in); PrintWriter outputStream = new PrintWriter(out); String l; while ((l = inputStream.readLine()) != null) { System.out.println(l); outputStream.println(l); } in.close(); out.close();

ww

w.n

eevi

aPDF.

com

Page 243: Java_Comb

46

Buffered StreamBuffered Stream

ww

w.n

eevi

aPDF.

com

Page 244: Java_Comb

47

Why Buffered Streams?● An unbuffered I/O means each read or write

request is handled directly by the underlying OS– This can make a program much less efficient, since

each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

● To reduce this kind of overhead, the Java platform implements buffered I/O streams– Buffered input streams read data from a memory

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.

ww

w.n

eevi

aPDF.

com

Page 245: Java_Comb

48

How to create Buffered Streams?

● A program can convert a unbuffered stream into a buffered stream using the wrapping idiom– A unbuffered stream object is passed to the constructor

for a buffered stream class● Example inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));w

ww

.nee

viaP

DF.co

m

Page 246: Java_Comb

49

Buffered Stream Classes

● BufferedInputStream and BufferedOutputStream create buffered byte streams

● BufferedReader and BufferedWriter create buffered character streams

ww

w.n

eevi

aPDF.

com

Page 247: Java_Comb

50

Flushing Buffered Streams● It often makes sense to write out a buffer at critical

points, without waiting for it to fill. This is known as flushing the buffer.

● Some buffered output classes support autoflush, specified by an optional constructor argument.– When autoflush is enabled, certain key events cause

the buffer to be flushed– For example, an autoflush PrintWriter object flushes

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.

ww

w.n

eevi

aPDF.

com

Page 248: Java_Comb

51

Standard StreamsStandard Streams

ww

w.n

eevi

aPDF.

com

Page 249: Java_Comb

52

Standard Streams on Java Platform

● Three standard streams– Standard Input, accessed through System.in– Standard Output, accessed through System.out– Standard Error, accessed through System.err

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

● System.out and System.err are defined as PrintStream objects

ww

w.n

eevi

aPDF.

com

Page 250: Java_Comb

53

Data StreamsData Streams

ww

w.n

eevi

aPDF.

com

Page 251: Java_Comb

54

Data Streams

● Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values

● All data streams implement either the DataInput interface or the DataOutput interface

● DataInputStream and DataOutputStream are most widely-used implementations of these interfaces

ww

w.n

eevi

aPDF.

com

Page 252: Java_Comb

55

DataOutputStream● DataOutputStream can only be created as a wrapper

for an existing byte stream objectout = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(dataFile)));for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]);}ww

w.n

eevi

aPDF.

com

Page 253: Java_Comb

56

DataInputStream● Like DataOutputStream, DataInputStream must be

constructed as a wrapper for a byte stream● End-of-file condition is detected by catching EOFException, instead of testing for an invalid return value

in = new DataInputStream( new BufferedInputStream( new FileInputStream(dataFile)));

try{ double price = in.readDouble(); int unit = in.readInt(); String desc = in.readUTF();} catch (EOFException e){}

ww

w.n

eevi

aPDF.

com

Page 254: Java_Comb

57

Object StreamsObject Streams

ww

w.n

eevi

aPDF.

com

Page 255: Java_Comb

58

Object Streams

● Object streams support I/O of objects– Like Data streams support I/O of primitive data types– The object has to be Serializable type

● The object stream classes are ObjectInputStream and ObjectOutputStream– These classes implement ObjectInput and

ObjectOutput, which are subinterfaces of DataInput and DataOutput

– An object stream can contain a mixture of primitive and object valuesww

w.n

eevi

aPDF.

com

Page 256: Java_Comb

59

Input and Output of Complex Object

● The writeObject and readObject methods are simple to use, but they contain some very sophisticated object management logic– This isn't important for a class like Calendar, which

just encapsulates primitive values. But many objects contain references to other objects.

● If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to.– These additional objects might have their own

references, and so on. ww

w.n

eevi

aPDF.

com

Page 257: Java_Comb

60

WriteObject

● The writeObject traverses the entire web of object references and writes all objects in that web onto the stream

● A single invocation of writeObject can cause a large number of objects to be written to the stream.

ww

w.n

eevi

aPDF.

com

Page 258: Java_Comb

61

I/O of multiple referred-to objects

● Object a contains references to objects b and c, while b contains references to d and e

ww

w.n

eevi

aPDF.

com

Page 259: Java_Comb

62

I/O of multiple referred-to objects

● Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this web are written also

● When a is read back by readObject, the other four objects are read back as well, and all the original object references are preserved.

ww

w.n

eevi

aPDF.

com

Page 260: Java_Comb

63

Closing StreamsClosing Streams

ww

w.n

eevi

aPDF.

com

Page 261: Java_Comb

64

Always Close Streams

● Closing a stream when it's no longer needed is very important — so important that your program should use a finally block to guarantee that both streams will be closed even if an error occurs– This practice helps avoid serious resource leaks.

ww

w.n

eevi

aPDF.

com

Page 262: Java_Comb

65

File ClassFile Class

ww

w.n

eevi

aPDF.

com

Page 263: Java_Comb

66

The File Class

● Not a stream class● Important since stream classes manipulate File

objects● Abstract representation of actual files and directory

pathname

ww

w.n

eevi

aPDF.

com

Page 264: Java_Comb

67

The File Class: Constructors

● Has four constructors

ww

w.n

eevi

aPDF.

com

Page 265: Java_Comb

68

The File Class: Methodsw

ww

.nee

viaP

DF.co

m

Page 266: Java_Comb

69

The File Class: Methodsw

ww

.nee

viaP

DF.co

m

Page 267: Java_Comb

70

The File Class: Example1 import java.io.*;23 public class FileInfoClass {4 public static void main(String args[]) {5 String fileName = args[0];6 File fn = new File(fileName);7 System.out.println("Name: " + fn.getName());8 if (!fn.exists()) {9 System.out.println(fileName 10 + " does not exists.");11 //continued...w

ww

.nee

viaP

DF.co

m

Page 268: Java_Comb

71

The File Class: Example12 /* Create a temporary directory instead. */13 System.out.println("Creating temp directory...");14 fileName = "temp";15 fn = new File(fileName);16 fn.mkdir();17 System.out.println(fileName +18 (fn.exists()? "exists": "does not exist"));19 System.out.println("Deleting temp directory...");20 fn.delete();21 //continued...w

ww

.nee

viaP

DF.co

m

Page 269: Java_Comb

72

The File Class: Example2425 System.out.println(fileName + " is a " +26 (fn.isFile()? "file." :"directory."));2728 if (fn.isDirectory()) {29 String content[] = fn.list();30 System.out.println("The content of this directory:");43 for (int i = 0; i < content.length; i++) {44 System.out.println(content[i]);45 }46 } 3536 //continued...

ww

w.n

eevi

aPDF.

com

Page 270: Java_Comb

73

The File Class: Example36 3738 if (!fn.canRead()) {39 System.out.println(fileName 40 + " is not readable.");41 return;42 }43 //continued...

ww

w.n

eevi

aPDF.

com

Page 271: Java_Comb

74

The File Class: Example47 System.out.println(fileName + " is " + fn.length()48 + " bytes long.");49 System.out.println(fileName + " is " +50 fn.lastModified() + " bytes long.");5152 if (!fn.canWrite()) {53 System.out.println(fileName 54 + " is not writable.");55 }56 }57 }w

ww

.nee

viaP

DF.co

m

Page 272: Java_Comb

75

Modified InputStream/ OutputStream Example

24 } catch (IOException ie) {25 ie.printStackTrace();26 }27 }28

29 public static void main(String args[]) {30 String inputFile = args[0];31 CopyFile cf = new CopyFile();32 cf.copy(inputFile);33 }34 }w

ww

.nee

viaP

DF.co

m

Page 273: Java_Comb

76

Thank You!Thank You!

ww

w.n

eevi

aPDF.

com

Page 274: Java_Comb

References

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

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

3. The Java Tutorial, 2nd ed., 2 volumes,MaryCampione and Kathy Walrath, Addison WesleyLongmans, 1998. Latest version available online atjava.sun.com. Download free. Book: Rs 630 (Vol. 1)and Rs 395 (Vol. 2).

4. Core Java 2, 2 volumes, Cay S. Horstmann, GaryCornell, The Sun Microsystems Press, 1999, Indianreprint 2000. Rs 450 (Vol. 1) and Rs 495 (Vol. 2).

5. Using Java 2Joseph L. WeberPrentice Hall, Eastern Economy Edition, 2000. Rs 499.

6. The Java Language Specification, 2nd ed, JamesGosling, Bill Joy, Guy Steele & Gilad Bracha, (1st ed1996, 2nd ed 2000), Sun Microsystems, 2000.

ww

w.n

eevi

aPDF.

com

Page 275: Java_Comb

Notes

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

• Note: Please do whatever is necessary to justifythese assumptions!

CKR Java Notes 2

ww

w.n

eevi

aPDF.

com

Page 276: Java_Comb

Java: Prehistory

• Development 1: C++– C++ (or “C with Classes”) was invented

in 1979, and became the stockprogramming language in the 90’s.(Standardized in Nov. 1997.)

– What were the reasons for its success?

– Lesson: C++ very successful, since itenhanced an existing successfullanguage like C.

– (instead of building an entirely newprogramming language).

• Development 2: GUI

– Object orientation permits reusablecode, hence a Graphical User interfaceGUI (E.g. MS-Windows).

– GUI has enormously expanded thenumber of computer-users.

– Lesson: Object oriented programming(OOP) with GUI is the “grand consensusof the computer industry”.

CKR Java Notes 3

ww

w.n

eevi

aPDF.

com

Page 277: Java_Comb

Java: Prehistory (contd.)

• Development 3: Internet

– Internet stared in the 1960’s as a way tomaintain communications in the event ofa nuclear attack.

– Success of ARPANET inspired NSFNET.

– In 1983, TCP/IP became the officialprotocol which connected ARPANET andNSFNET.

– This collection of connected networkscame to be called the Internet.

– By 1990, 3000 networks and 200,000computers were connected to theInternet. By 1992, there were 1 millionhosts.

– The hosts had diverse hardware andoperating systems like DOS/Windows,UNIX, and MacOS.

– Problem: How to share information easilyacross different computer platforms?

CKR Java Notes 4

ww

w.n

eevi

aPDF.

com

Page 278: Java_Comb

Java: Prehistory (contd.)

• Development 4: WWW

– To simplify sharing of documents anddata across the Internet, WWW inventedin 1989 at CERN, Geneva, forhigh-energy physicists.

– WWW is an architectural framework forviewing documents stored acrossthousands of machines connected tothe Internet.

– The scattered document seems like asingle document using a browser to viewhypertext, which contains hyperlinks.

– However, this concerned passive text ordocument files, and users on the wwwcould not share executable programs.

– Problem: How to incorporate interactiveprograms on the Web? How to shareexecutable programs across platforms?

CKR Java Notes 5

ww

w.n

eevi

aPDF.

com

Page 279: Java_Comb

Java: History

• In 1990, Sun Microsystems started a projectcalled Green.

– Objective: to develop software forconsumer electronics.

– Sun best known for its popular Unixworkstation, Solaris OS, and NetworkFile System (NFS).

– Project was assigned to James Gosling,a veteran of classic network softwaredesign.

– Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.

• The team started writing programs in C++ forembedding into

– toasters– washing machines– VCR’s– PDA’s (Personal Digital Assistants)

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

CKR Java Notes 6

ww

w.n

eevi

aPDF.

com

Page 280: Java_Comb

Java: History (contd.)

• C++ is powerful, but also dangerous.

– The power and popularity of C derivedfrom the extensive use of pointers.

– However, any incorrect use of pointerscan cause memory leaks, leading theprogram to crash.

– In a complex program, such memoryleaks are often hard to detect.

• Robustness is essential

– Users have come to expect thatWindows may crash or that a programrunning under Windows may crash.(“This program has performed an illegaloperation and will be shut down”)

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

– A design for consumer electronics hasto be robust. Replacing pointers byreferences, and automating memorymanagement was the proposed solution.

CKR Java Notes 7

ww

w.n

eevi

aPDF.

com

Page 281: Java_Comb

Java: History (contd.)

• Oak: Hence, the team built a new programminglanguage called Oak, which

– avoided potentially dangerousconstructs in C++, such as pointers,pointer arithmetic, operator overloadingetc.

– introduced automatic memorymanagement, freeing the programmer toconcentrate on other things.

• Architecture neutrality (Platform independence)

– Many different CPU’s are used ascontrollers. Hardware chips are evolvingrapidly. As better chips becomeavailable, older chips become obsoleteand their production is stopped.

– Manufacturers of toasters and washingmachines would like to use the chipsavailable off the shelf, and would not liketo reinvest in compiler developmentevery two-three years.

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

CKR Java Notes 8

ww

w.n

eevi

aPDF.

com

Page 282: Java_Comb

Java: History (contd)

• It was soon realized that these design goals ofconsumer electronics perfectly suited an idealprogramming language for the Internet andWWW, which should be:

– object-oriented (& support GUI)– robust– architecture neutral

• Internet programming presented a BIG businessopportunity. Much bigger than programming forconsumer electronics.

– Java was “re-targeted” for the Internet

• The team was expanded to include Bill Joy(developer of Unix), Arthur van Hoff, JonathanPayne, Frank Yellin, Tim Lindholm etc.

• In 1994, an early web browser called WebRunnerwas written in Oak. WebRunner was laterrenamed HotJava.

• In 1995, Oak was renamed Java. – A common story is that the name Java

relates to the place from where thedevelopment team got its coffee.

– The name Java survived the trade marksearch.

CKR Java Notes 9

ww

w.n

eevi

aPDF.

com

Page 283: Java_Comb

Java Features

• Additional features were added to make Java– secure– multithreaded (concurrent)– distributed and dynamic– high performance

• Security: Is a key feature on the Internet. Itshould be possible to specify what systemresources the program can access.

– In the sandbox policy remote applets arenot trusted to access any localresources,

– while local applications are trusted toaccess all resources.

– This can be modified, by allowingdigitally signed applets selective access.

• Multiple threads: C and C++ support multiplethreads, using fork(),

– this feature is NOT a part of the ANSI/ISOstandard, and is available only on UNIX.

– DOS support is available for the spawn...and exec... family of functions. Thesefeatures are not much used.

CKR Java Notes 10

ww

w.n

eevi

aPDF.

com

Page 284: Java_Comb

– But concurrency is essential on theinternet, since download times areuncertain, so one process should notblock all others.

– Threads also needed for e.g. animation.

• Distributed: – The ultimate vision of OOP is to have

objects stored on different computers tointeract with each other. That is, a usercan assemble a program different partsof which are stored on differentcomputers.

• Dynamic: – Java is both compiled and interpreted.

– Thus, source code is compiled tobytecode.

– The Java Virtual Machine loads and linksparts of the code dynamically at runtime.

– Hence it carries substantial run time typeinformation on objects.

– Hence, It supports late binding.

CKR Java Notes 11

ww

w.n

eevi

aPDF.

com

Page 285: Java_Comb

• High performance– Though Java uses an interpreter,

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

– Optimization can take place at this stageto ensure that Java programs can matchthe speed of programs in compiledlanguages like C++.

– Where speed cannot be traded off forplatform independence, Java provides“native method support”, for codewritten in languages like C/C++, andcompiled for specific platforms.

CKR Java Notes 12

ww

w.n

eevi

aPDF.

com

Page 286: Java_Comb

Java Features: Summary

• Simple

• Secure

• Portable

• Object-oriented

• Robust

• Multithreaded

• Architecture-neutral

• Interpreted

• High-performance

• Distributed

• Dynamic

CKR Java Notes 13

ww

w.n

eevi

aPDF.

com

Page 287: Java_Comb

Comparison of Java and other languages by Gosling

Fig. 1: From the Java Language Environment White

CKR Java Notes 14

ww

w.n

eevi

aPDF.

com

Page 288: Java_Comb

The JDK

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

• This can be downloaded free of cost fromhttp://java.sun.com

• The JDK can be downloaded for differentplatforms: Windows, Unix (Solaris), MacOS.

• Requires support for – long file names, and – case-sensitive file names.

• Hence, will not run in DOS. (Limited platformindependence.)

• Hardware and Software requirements:

– Win 95/Win NT4.0 or higher running onx86 (min. 486/8MB). Little disk space (~ 40 MB).

– Solaris 2.4 or higher on SPARC

– Solaris 2.5 or higher on x86.

CKR Java Notes 15

ww

w.n

eevi

aPDF.

com

Page 289: Java_Comb

• Comes as a self-extracting exe for Win95+, whichextracts to c:\jdk1.2 directory.

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

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

– If upgrading, if CLASSPATH set toclasses.zip, this should be removed.

– Setting the CLASSPATH variable isoptional: set CLASSPATH= .;c:\mydir\myclass.jar;.\myclasses.zip

– There should be no space around =

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

– This is preferred since applications mayrun differently depending upon theclasspath.

– More about CLASSPATH when we studypackages.

CKR Java Notes 16

ww

w.n

eevi

aPDF.

com

Page 290: Java_Comb

JDK Utilities

• The following are some of the important utilitiesavailable under jdk.

• javac– The java compiler, converts source code

into bytecode stored in class files.

• java– The java interpreter that executes

bytecode for a java application from classfiles.

• appletviewer– The java interpreter that executes

bytecode for a java applet from classfiles.

• javadoc– Creates HTML documentation based on

java source code, and the documentationcomments it contains.

• jdb– The java debugger. Allows one to step

through the program one line at a time,set breakpoints, and examine variables.

• javah– Generates C/C+ header files for

combining with native methods.

CKR Java Notes 17

ww

w.n

eevi

aPDF.

com

Page 291: Java_Comb

Using the JDK: Hello World Application

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

simple Integrated DevelopmentEnvironment, like Kawa to type thefollowing program.

Program 1/*** The HelloWorld class implements an* application that simply displays * “Hello World!” to the * standard output (console)*/ public class HelloWorld { public static void main (String args[])

{ //required prototype for main function System.out.println(“Hello world!”);}

}• Step 2: Save the source in a file:

– The file MUST have the same name asthe public class in the source, and musthave a .java extension. (Hence, supportfor long filenames is required.)

CKR Java Notes 18

ww

w.n

eevi

aPDF.

com

Page 292: Java_Comb

– That is, the above file should be savedas HelloWorld.javawith the case maintained.

– Note: A java source file cannot containmore than one public class according tothe above restriction.

• Step 3: Compile the source file using javac:

– use the following command line at theshell prompt

javac HelloWorld.java

– If the code is correct, compilation willproduce the file

HelloWorld.class

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

– To see what javac does behind thescenes, use the following command line

javac -verbose HelloWorld.java

CKR Java Notes 19

ww

w.n

eevi

aPDF.

com

Page 293: Java_Comb

Using the jdk: Hello World Application (contd.)

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

command line

java HelloWorld

– Output: Hello World!

• Congratulations! You have successfully run yourfirst java program.

• Note: 1. No file extension is needed wheninvoking the interpreter. 2. To view execution details of the compiledcode, use the command line

java -prof HelloWorld

This will generate a profile which shows

– methods called in order of decreasingfrequency.

– how memory is used.

– list of variable types and bytesnecessary to store them.

CKR Java Notes 20

ww

w.n

eevi

aPDF.

com

Page 294: Java_Comb

Anatomy of the HelloWorld program

• New style comments:

– The first line of the HelloWorld programshows a new style comment.

– This is a documentation comment whichbegins with /** and ends with */

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

• Using javadoc:

– The new style comments are used togenerate source code documentation.

– To generate this documentation, use thecommand line

javadoc HelloWorld.java

– javadoc ignores old-style comments.

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

CKR Java Notes 21

ww

w.n

eevi

aPDF.

com

Page 295: Java_Comb

Anatomy of the HelloWorld Program

• Stripped of comments, this is the HelloWorldprogram:

public class HelloWorld {

public static void main (String args[]) {

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

}• The first line declares a class. public is an

access specifier for the class.

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

• Thus, Java is completely object oriented.

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

– The main method continues to be theentry point.

– Every Java application MUST have amain method declared as above.

– This is NOT required for java applets.

CKR Java Notes 22

ww

w.n

eevi

aPDF.

com

Page 296: Java_Comb

Anatomy of the HelloWorld program (contd)

• Note the prototype of the main method

public static void main (String args[])

• For the main method– public is the access specifier.– static is the storage class.– void is the return type. – String args[] is an array of strings

similar to int argc, char *argv[] ofC/C++.

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

work. public static void main()

• We can check this out by writing a smallprogram.

Program 2

/** class NoMain has an incorrectly defined* main function. This class will compile * correctly, but will not execute. * The interpreter will say* In class NoMain: void main (Stringargv[]) is not defined*/

CKR Java Notes 23

ww

w.n

eevi

aPDF.

com

Page 297: Java_Comb

public class NoMain{

public static void main(){

System.out.println (“This program will notrun”);

}}

• Why does this happen?

– Several methods called main can bedefined, in a java class.

– The interpreter will look for a mainmethod with the prescribed signature asthe entry point.

– A method named main, which has someother signature is of no particularsignificance. It is like any other methodin the class

– Therefore, if the main method is notdeclared correctly, the application willnot execute.

CKR Java Notes 24

ww

w.n

eevi

aPDF.

com

Page 298: Java_Comb

A Java program with two main methods

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

Program 3public class TwoMains { /** This class has two main methods with * different signatures */

public static void main (String args[]) {

//required prototype for main method System.out.println(“Hello world!”);int i;i = main(2);System.out.println (“i = ” + i );

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

{return i*i;

}}

• Output: Hello World!i = 4

CKR Java Notes 25

ww

w.n

eevi

aPDF.

com

Page 299: Java_Comb

Anatomy of the Hello World Program (contd.)

• The argument to the mandatory main function

public static void main (String args[]) which isString args []

can also be written as

String [] args

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

• This represents the string of command lineparameters, as in C/C++,

• But– There is no need for argc, since an array

in Java always knows how manyelements it has.

– args[0] is NOT the name of theprogram itself, but the first parameter onthe command line.

• The last line refers to the println method of theout variable (representing the standard outputstream) of the System class.

CKR Java Notes 26

ww

w.n

eevi

aPDF.

com

Page 300: Java_Comb

Command line arguments

• We can test the above considerations by meansof a small program.

Program 4public class CommandLine{

public static void main (String argv []){

int length = argv.length;String myString = “No. of parameters”r

+ “ on the command line: ”;System.out.println (myString + length);for (int i=0; i length; i++)

{myString = argv[i];System.out.println (i + “: ” + myString);

}}

}• Input: java CommandLine Java is a good

language.

• Output: No of parameters on the command line: 50: Java1: is2: a3: good4: language.

CKR Java Notes 27

ww

w.n

eevi

aPDF.

com

Page 301: Java_Comb

Debugging a program

• Sometimes the program compiles but does notwork as intended.

• In this situation the java debugger can be used. – to generate full debugging info use the

-g option with javac

• The debugger is invoked as follows.

jdb HelloWorld

• To set a breakpoint, use the command

stop in HelloWorld.main

followed byrun

• When the breakpoint is hit, typelistto see the code.

• Type clear HelloWorld.mainfollowed by

• cont

CKR Java Notes 28

ww

w.n

eevi

aPDF.

com

Page 302: Java_Comb

CKR Java Notes 29

ww

w.n

eevi

aPDF.

com

Page 303: Java_Comb

CKR Java Notes 30

ww

w.n

eevi

aPDF.

com

Page 304: Java_Comb

Summary

• We have used the following utilities of JDK

– javac (compiler)– java (interpreter)– javadoc (for extracting documentation

comments)– jdb (debugger)

• We have learnt to write a basic application inJava, to compile it, and run it.

• Every java application must have a main method

– This main method is defined inside aclass.

– It must have the prescribed signature.

• Note: A main method is NOT required for javaapplets.

• Java is completely object oriented. No residuefrom structured programming.

– The main method is inside a class– class declarations need no semicolon. – Everything must be inside some class!

CKR Java Notes 31

ww

w.n

eevi

aPDF.

com

Page 305: Java_Comb

Elements of Programming style:

• Java is a free-form language, and white spacemay be used almost anywhere in a Javaprogram.

– However indentation helps humans tounderstand the program.

– Hence we will use appropriateindentation.

• Also, object-oriented programming involves aprofusion of names, hence names must bechosen systematically.

– Thus, class names begin with capitalletters by convention.

– method and variable names begin withlowercase letters by convention.

• If the name involves more than one word,mixed-capitalization is used to indicate thebeginning of the word for a method, andunderscore for a variable. E.g.

– myMethod– my_variable

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

CKR Java Notes 32

ww

w.n

eevi

aPDF.

com

Page 306: Java_Comb

Program 5public class FreeForm { public

static void

main ( String args [])

{ //required prototype for main method System.out.println(“ Java is a ” +“free-form language!”//strings must still be terminated//before end of line.//They must be concatenated using +// and not merely by whitespace.);}}

CKR Java Notes 33

ww

w.n

eevi

aPDF.

com

Page 307: Java_Comb

A program with three classes

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

Program 6In file Point.java:public class Point{ float x;

float y;public void setXY (float x0, float y0){

x = x0;y = y0;

}public float getX (){

return x;}public float getY (){

return y;}

}

class Line{

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

CKR Java Notes 34

ww

w.n

eevi

aPDF.

com

Page 308: Java_Comb

public float length (){

float temp1, temp2;temp1 = (a.getX()-b.getX());temp1 *= temp1;temp2 = (a.getY()- b.getY());temp2 *= temp2;return (float) Math.sqrt

((double)temp1+temp2);}

}

• In file PointLine.java:public class PointLine{

public static void main (String args[]){

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

myLine.length() );}

}• After compiling both files, use the command

java PointLIne

• Output: Length of myLine = 1

CKR Java Notes 35

ww

w.n

eevi

aPDF.

com

Page 309: Java_Comb

Hello World Applet

• Java programs are commonly of two types

– Applications– Applets

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

• Applications are stand-alone Java programs.

• Applets are programs that require a browser torun. Applets are typically downloaded from theInternet and run in an applet window within abrowser.

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

• But there is no inherent limitation to the size ofan applet, and they can be as complex as onewants.

• Applets get their parameters not from thecommand line but from the web page withinwhich they run.

CKR Java Notes 36

ww

w.n

eevi

aPDF.

com

Page 310: Java_Comb

Hello World Applet (contd.)

• Unlike applications, applets do not utilise a mainmethod. Instead they use the following methods.

– public void init(): Initializes theapplet. Called only once.

– public void start(): called when thebrowser is ready to run the applet.

– public void stop(): called when thebrowser wishes to stop the applet, or theuser leaves the web page, or the browseris iconified.

– public void destroy(): called whenthe browser clears the applet out ofmemory.

– public void paint (Graphics g):called whenever the browser needs toredraw the applet.

• Applets get their parameters using the String getParameter(String Param_name) method.

CKR Java Notes 37

ww

w.n

eevi

aPDF.

com

Page 311: Java_Comb

Hello World Applet (contd.)

• Step 1: Write the source code: For theHelloWorld Applet, create a java source file asfollows.

Program 7import java.awt.*; public class HelloWorldApplet extendsjava.applet.Applet{

public void paint (Graphics screen){

screen.drawString (“Hello World Applet!”,50, 25);

}}

• Step 2: Compile the source file using javac.

• Step 3: Create a minimal html file as follows.

<applet code = “HelloWorldApplet.class”height = 100 width = 300> </applet>

• and save it as CallApp.html

• Step 4: Viewing the applet in appletviewer: Runappletviewer by

appletviewer CallApp.html

CKR Java Notes 38

ww

w.n

eevi

aPDF.

com

Page 312: Java_Comb

HelloWorld Applet (contd.)

• Step 4: Preparing to viewing the applet in abrowser: Wrap the above html code within anydesired html code, e.g.

<HTML><HEAD><TITLE>Hello World Applet</TITLE></HEAD><BODY>This is what my applet does:

<applet code = “HelloWorldApplet.class”height = 100 width = 300></applet></BODY></HTML>Save the code in a file: myfile.html

• Step 5: Open the above html file using anyjava-enabled browser.

– E.g. use “Open page” on NetscapeNavigator

– the applet will automatically run in theassigned area.

CKR Java Notes 39

ww

w.n

eevi

aPDF.

com

Page 313: Java_Comb

Anatomy of the HelloWorldApplet applet

• The first line in the HelloWorldApplet program is

import java.awt.*;

• The import statement is an instruction to thecompiler to help resolve class names.

– An import statement helps to refer to theclasses in the java.awt package by theirshort names.

– Thus to refer to the Graphics class, wenow use the statement

public void paint (Graphics screen)• Without the import statement, we would have to

use the fully qualified name: public void paint (

java.awt.Graphics screen )

• Similarly, if we used the statementimport java.applet.Applet

• the second line of the program could beabbreviated to

public class HelloWorldApplet extendsAppleti.e., we could refer to java.applet.Applet simplyas Applet.

CKR Java Notes 40

ww

w.n

eevi

aPDF.

com

Page 314: Java_Comb

Anatomy of the HelloWorldApplet applet (contd.)

• The HelloWorldApplet does not use the init(),start(), stop(), or destroy() methods.

– It uses only the paint method.– The paint method takes a Graphics

object as an argument. – The Graphics class is part of the

Abstract Windows Toolkit (awt) package.

• The declaration public void paint (Graphics screen)says that the Graphics object will be referred by thename screen within the paint method.

– “screen” is only an identifier, and can bereplaced by any other identifier, such as“g”.

– Since the graphics class woks in thegraphics mode (as in classic C), thepreferred method is to draws stringsrather than perform console output.

– The instructionscreen.drawString (“Hello World Applet!”,50, 25);

– means that the string is to be drawn atpixels x=50, y=25, relative to the appletwindow, measured from the top left handcorner of the applet window.

CKR Java Notes 41

ww

w.n

eevi

aPDF.

com

Page 315: Java_Comb

Anatomy of the HelloWorldApplet applet (contd.)

• As observed before, an applet cannot run on itsown, and must run within a browser.

– Hence the applet code must besupplemented with HTML code.

• The minimum HTNL code that is needed forappletviewer is the following.

<applet code = “HelloWorldApplet.class”height = 100 width = 300> </applet>

• The HTML syntax is self-explanatory: it says thatthe applet with the given class file name shouldbe displayed in a window of the given height andwidth in pixels.

• The exact positioning of the window will bedecided by the browser and any other HTMLcommands such as ALIGN.

• if the applet class file is not in the same directoryas the web page, then use the syntax

CODEBASE= URL

• with the URL or path of the directory where theapplet class file is located.

CKR Java Notes 42

ww

w.n

eevi

aPDF.

com

Page 316: Java_Comb

Anatomy of the HelloWorldApplet (contd.)

• Unlike applications which take command lineparameters, applets get their parameters using

– The <PARAM,> tag in the HTML code– The getParameter method in the applet

code.

• The <PARAM> tag has the syntax

<PARAM NAME="parameter-name"VALUE="parameter-value">

• The getParameter method has the prototypeString getParameter(String parameter_name)

• E.g. below shows how two parameters areobtained by the applet. (Note the capitalization.)

Program 8

• Code in HTML file:

<applet code = GetParam.class height = 100width = 100><param name = Name value = “Myname”><param name = class value = “myclass”></applet>

CKR Java Notes 43

ww

w.n

eevi

aPDF.

com

Page 317: Java_Comb

• Code in file GetParameter.javaimport java.awt.*;import java.applet.Applet;public class GetParam extends Applet{

String s1, s2;public void init(){

s1 = getParameter (“NAme”)s2 = getParameter (“class”);

}

public void paint(Graphics screen){

if (s1 != null)screen.drawString (s1, 50, 100);

elsescreen.drawString (“No Name”, 50, 100);

if (s2 != null)screen.drawString (s2, 50, 200);

elsescreen.drawString (“No Class”, 50, 200);

}}

CKR Java Notes 44

ww

w.n

eevi

aPDF.

com

Page 318: Java_Comb

General Applets

• The Hello World applet used only the paintmethod.

• The Get Parameter applet used only the init andthe paint methods.

• The other methods of an applet are alwayscalled, and a default implementation is provided.

• To see how they are called, we can use thefollowing applet code.

• The code also shows how applets may use theconsole, although they usually don’t for obviousreasons.

• To see the output when the applet is running in abrowser use the Java Console window of thebrowser.

Program 9

import java.awt.*;import java.applet.Applet;public class TestApplet extends Applet{

static int countInit=0;static int countStart=0;static int countStop=0;

CKR Java Notes 45

ww

w.n

eevi

aPDF.

com

Page 319: Java_Comb

static int countPaint=0;static int countDestroy=0;

public void init() {

System.out.println (“Init = ” +(++countInit));

}

public void start(){

System.out.println (“Start = ” +(++countStart));repaint();

}

public void stop(){

System.out.println (“Stop = ” +(++countStop));

repaint();}

public void paint (Graphics screen){

System.out.println (“Paint = ” +(++countPaint));

/*repaint();//recursive call to paint*/}

CKR Java Notes 46

ww

w.n

eevi

aPDF.

com

Page 320: Java_Comb

public void destroy(){

System.out.println (“Destroy =” +(++countDestroy));

repaint();}

}

CKR Java Notes 47

ww

w.n

eevi

aPDF.

com

Page 321: Java_Comb

Summary

• There are two common types of Java programs.– Applications– Applets

• Applications use the main method, applets don’t.

• Applications are stand-alone, while applets runwithin a browser.

• Applets are inherently graphical. (However, theycan use console i/o).

• From the point of view of the language, bothapplications and applets are the same..

• Applications can avoid graphics and use onlyconsole i/o, so they are faster, and moreconvenient in a development environment.

• Hence, we will study the language usingprimarily applications.

CKR Java Notes 48

ww

w.n

eevi

aPDF.

com

Page 322: Java_Comb

How Java works

• Java is two things– Java Platform– Java language

• Computer world today has many platforms– MicroSoft windows– Unix– Macintosh– OS/2– NetWare

• Software must be compiled separately for eachplatform. The binary files for an application thatruns on one platform cannot run on anotherplatform, since they are machine specific.

• The Java Platform is a software platform that– sits on top of the other platforms– The Java compiler compiles source files

(.java files) to bytecodes (.class files). – these bytecodes are not specific to any

machine. – they are instructions for the Java Virtual

Machine. – Hence exactly the same file can run on

any machine on which the Java Platformis present.

CKR Java Notes 49

ww

w.n

eevi

aPDF.

com

Page 323: Java_Comb

The Java Platform

• Each underlying computer platform has its ownimplementation of the Java Virtual Machine.

• But there is only one virtual machinespecification.

• Hence Java is able to provide the “Write Once,Run Anywhere” capability.

– This capability is very important today,because of the diverse machinesconnected to the Internet. (E.g. AdobePDF format documents.)

– It is also important because of the highcosts of software development makes itdesirable to reuse code as easily aspossible.

• The Java Platform consists of

– The Java Virtual Machine, and– The java API (Application programmer

interface/ class files).

• The Java Base Platform consists of the JVM anda minimum set of API known as Base API.

CKR Java Notes 50

ww

w.n

eevi

aPDF.

com

Page 324: Java_Comb

The Java Virtual Machine

• The Java Virtual machine is a ‘soft machine’– a piece of software compiled for different

platforms.

• The JVM behaves like a real machine in that– it has an instruction set– it manipulates various memory areas at

run time. – similar to the P-Code machine of UCSD

Pascal (which was not such a successbecause “University people knownothing of marketing.”)

• “The Java Virtual Machine knows nothing of theJava Language” (Tim Lindholm and Frank YellinThe Java Virtual Machine Specifications)

• The Java Virtual Machine understands only aparticular binary format known as the class fileformat.

• The class file format contains – JVM instructions or bytecodes– a symbol table and other ancillary info.

• In principle, the JVM can run the instructionsfrom any language which can be compiled intothe class file format.

CKR Java Notes 51

ww

w.n

eevi

aPDF.

com

Page 325: Java_Comb

The Java Virtual Machine (contd.)

• The Java Virtual Machine starts execution by– invoking the method main of some

specified class– passing to it a single argument which is

an array of strings.

• This causes that class to be – loaded– linked to other types it uses, and– Initialised

• The loading process is implemented by the classClassLoader or its subclasses.

– Different subclasses may implementdifferent loading policies, e.g. pre-fetchbased on expected usage, load a relatedgroup of classes etc.

– This may not be transparent to therunning application. E.g. a newlycompiled version of a class is not loadedbecause a previously compiled versionis cached.

– Responsibility of class loader to reflecterrors only when they could have arisenwithout prefetching or group loading.

CKR Java Notes 52

ww

w.n

eevi

aPDF.

com

Page 326: Java_Comb

The Java Virtual Machine (contd.)

• Linking is the process of taking the binary form ofa class type or an interface type, and combiningit into the run time state of the JVM so that it canbe executed.

– A class or interface is always loadedbefore it is linked.

• Linking involves– verification– preparation, and– resolution of symbolic references

• Depending upon implementation, symbolicreferences may be resolved

– individually, when needed (lazy or lateresolution)

– collectively when the class is loaded(static resolution)

• Verification ensures that the binary representationof a class or interface is structurally correct.

– E.g. that every instruction has a validoperation code.

• Preparation– involves creating the static fields and

intializing them to their default values.

CKR Java Notes 53

ww

w.n

eevi

aPDF.

com

Page 327: Java_Comb

Java Virtual Machine: Limitation

• Despite all the hype, the Java Virtual machinehas certain limitations.

• The number of dimensions in an array is limitedto 255..

• The number of method parameters is limited to255 9with long and double counted as 2parameters).

• 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 to64K. (Does not include inherited methods. )

• The amount of code per (non-native,non-abstract) method is limited to 64K bytes.

• For more details: consult The JVM Specificationsby Lindholm and Yellin.

CKR Java Notes 54

ww

w.n

eevi

aPDF.

com

Page 328: Java_Comb

Java Virtual Machine limitations (Example Program)

• The Java virtual Machine can also run out ofmemory. Here is an example.

• The array size may have to be adjusted fordifferent machines.

Program 10class BigArray{

public static void main(String args[]){

double myArray[];myArray = new double [256*256*256];for (int i=0; i<=256*256*256; i++){

myArray[i] = (double)i;System.out.println (i+ “th element = ” +

myArray[i]);}

}}

• Expected output:Java.lang.OutOfMemoryError atBigArray.main(BigArray.java:6)

CKR Java Notes 55

ww

w.n

eevi

aPDF.

com

Page 329: Java_Comb

The Java API

• The Java API provide a standard interface ofready made code that a programmer can relyupon, irrespective of the platform.

• The Base API provide the language (java.lang),utility (java.util), i/o (java.io), network (java.net),gui (java.awt), and applet (java.applet) services.

• The Standard Extension API provide variousother services.

• Naturally, the classification will change with time.

Fig. 2: The Java Platform is the same for allsystems

CKR Java Notes 56

ww

w.n

eevi

aPDF.

com

Page 330: Java_Comb

The Java Environment

• The Java development environment includesboth Java compile time and run-timeenvironment.

• The developers source code (.java files) areconverted to bytecodes (.class files).

• In the case of applets the bytecodes aredownloaded.

• Once in the JVM, these are interpreted by theInterpreter or optionally turned into machinecode by a Just in Time (JIT) code generator,popularly called a JIT compiler.

• The Java Runtime Environment is providedseparately, for those who merely wish to runJava applicatoins, but do not wishh to compilethem.

Fig. 3: The Java Compile and RuntimeEnvironment

CKR Java Notes 57

ww

w.n

eevi

aPDF.

com

Page 331: Java_Comb

Identifiers and Unicode

• A legal identifier in Java is a finite sequence ofcharacters.

• Java programs (v. 1.1.7 upwards) may useUnicode character encoding (v. 2.1) as specifiedin

• The Unicode Standard Version 2.0 ISBN 0-201-48345-9

• Unicode only for identifiers, and the contents ofcharacters and string literals, and comments.

• Everything else must be in ASCII.

• The unicode character set uses 16 bit encoding,to try to represent characters from variouslanguages (currently some 24 languages).

– Of the 65536 possible characters, 49194have been assigned.

– The first 256 of these are the standardASCII character set.

– Supports Japanese, Greek, Russian,Hebrew etc.

CKR Java Notes 58

ww

w.n

eevi

aPDF.

com

Page 332: Java_Comb

• Indian scripts supported include: – Devnagari– Bengali– Gujarati– Gurmukhi– Malayalam– Tamil– Oriya– Telegu– Kannada

• A unicode character may be represented within astring by \uhhhh, where h are the hex digits.

– E.g. “\u0043" is the ASCII character C.

– For more information on Unicode consulthttp://www.unicode.org

CKR Java Notes 59

ww

w.n

eevi

aPDF.

com

Page 333: Java_Comb

Data types

• Three kinds of datatypes in Java. – primitive data types

– reference data types

– the special null data type, also the typeof the expression null.

• The null reference is the only possible value ofan expression of null type, and can always beconverted to any reference type.

– In practice, the null type can be ignored,and one can pretend that null is just aspecial kind of literal.

– i.e. if(obj != null) always makes sense.

• Java datatypes are NOT machine-dependent.

• The Java datatypes are defined as part of thelanguage, as follows.

• Apart from the primitive data types, (and the nulldata type) everything else is an object or areference datatype in Java.

CKR Java Notes 60

ww

w.n

eevi

aPDF.

com

Page 334: Java_Comb

Datatypes (contd.)

• The primitive data types are– numeric data types– Non-numeric data types

• The non-numeric data types are

– boolean (true or false)– char . (16 bit unicode)

• The numeric data types are further divided into – integer numeric types, and – real numeric types.

• The integer numeric types are as follows.

– byte 8 bit 2c

– short 16 bit 2c

– int 32 bit 2c

– long 64 bit. 2c

• Note: There is NO unsigned integer type in Java.

• 2c representation means that there is wraparound without any notification of error. This feature is similar to C and C++.

CKR Java Notes 61

ww

w.n

eevi

aPDF.

com

Page 335: Java_Comb

A class which adds two integers

Program 11

/** This program demonstrates how Java* adds two integers. */public class BigInt {

public static void main(String args[]){

int a = 2000000000; //(9 zeros)int b = 2000000000;System.out.println (

“This is how Java adds integers”);System.out.println ( a + “+” + b + “ = ” +

(a+b) );}

}

• Output:

This is how Java adds integers2000000000 + 2000000000 = -294967296

• Q. Explain why this happens. What, if any, is theremedy to this problem?

• This explains the difference between portableand architecture neutral.

CKR Java Notes 62

ww

w.n

eevi

aPDF.

com

Page 336: Java_Comb

Portable and architecture neutral revisited

• We observed earlier Gosling’s claim that C/C+are portable, but NOT architecture neutral.

• The above code provides an example.

• In C/C++, an int is defined as two bytes, but theactual size in bits is implementation andarchitecture dependent.

• Though one can use bitsperbyte to ensurearchitecture neutrality, this is rarely done.

• Thus, the following C/C+= program will givedifferent results on different systems.

#include <stdio.h>main(){

int a = 20000;int b = 20000;int c; c = a+b;printf (“%d + %d = %d”", a, b, c);

}• Output: 20000+20000 = 40000

(eg on Sun SPARC) 20000+20000 = -25536 (on x86)

CKR Java Notes 63

ww

w.n

eevi

aPDF.

com

Page 337: Java_Comb

Primitive Datatypes (contd)

• The real data types are – float 32 bit (23+8+1)– double 64 bit (52+11+1)

– roughly as per IEEE floating point 754standard of 1985.

• The key differences from IEEE 754 are

– In the handling of Nan– In the handling of division by zero.– INF is denoted by Infinity.

• The range of representable numbers is restrictedby both mantissa and exponent.

– The size of the exponent decides thesmallest and largest numbers that canbe represented.

– the size of the mantissa decides theprecision or accuracy.

• Note that use of floating point numbers meansthe failure of the usual laws of arithmetic, such as

– associative law– distributive law

CKR Java Notes 64

ww

w.n

eevi

aPDF.

com

Page 338: Java_Comb

Significant figures and failure of associative law

Program 12public class Significant{

public static void main (String args[]){

final float PI = 3.141519265359f;float radius = 1.0f;float area;area = PI * radius * radius;System.out.println (“The area of the

circle = ” + area);}

}• Output: area of the circle = 3.1415193

Program 13class AssocLaw{

public static void main(String args[]){

float epsilon = (float)1.0E-7;float a1, a2;a1 = (epsilon + 1) -1; a2 = epsilon + (1-1);System.out.println (“The difference is = ”

+ (a1-a2));} }• Output: difference = 1.9209288E-8

CKR Java Notes 65

ww

w.n

eevi

aPDF.

com

Page 339: Java_Comb

Difference from IEEE floating point representation

Program 14public class NumberTest{

public static void main(String args[]){

int a = 0, b=0;float fa = 0, fb = 0;try{

System.out.print (“(int) 0/0 = ” );System.out.println (“ ”+ a/b);

}catch (ArithmeticException e){

System.out.println (“Caught Arithmetic"+"Exception”);

}System.out.println (“(float) 0/0 = ” +

fa/fb);fa = (float) 1.0;System.out.println (“(float) 1/0 = ” +

fa/fb);fa = (float) 1E+39;System.out.println (“(float) 1E39 = ” +

fa);fb = (float) 2E+39;System.out.println (“(float) 1E39/2E39 = ”

+ fa/fb);

CKR Java Notes 66

ww

w.n

eevi

aPDF.

com

Page 340: Java_Comb

fb = 0.0f;System.out.println (“(float) 1E39 * 0 =” +

fa * fb);double lfa = 1E+39;double lfb = 2E+39;System.out.println (“(double) 1E39/2E39 =

” + lfa/lfb);

}}

• Output: (int) 0/0 = Caught Arithmetic Exception(float) 0/0 = NaN(float) 1/0 = Infinity(float) 1E39 = Infinity(float) 1E39/2E39 = Nan(float) 1E39*0 = NaN(double) 1E39/2E39 = 0.5

CKR Java Notes 67

ww

w.n

eevi

aPDF.

com

Page 341: Java_Comb

Features added by Java

• Relational operators:

• New use of the arithmetic operator %

– The % operator now applies also tofloating point data types.

– for real a, b, a%b returns the remainderor the floating point value, a-nb, where nis an int.

• These follow the same conventions as in C/C++.

– Namely: For integers a, b, and integerdivision a/b, the quotient is alwaysrounded towards zero. Hence,

– a%b always has the same sign as a (topreserve the relation between dividend,divisor, quotient and remainder) . That is,if

dividend = a divisor = dquotient = q remainder = r, then

a = qd + r

CKR Java Notes 68

ww

w.n

eevi

aPDF.

com

Page 342: Java_Comb

Features added by Java (contd.)

Program 15class RemainderTest{

public static void main(String args[]){

float a=3.2f, b=4.3f, c;c = b%a;System.out.println (“b%a = ” + c);b = -4.3f;c=b%a;System.out.println (“-b%a = ” + c);

}}

• Output: b%a = 1.1000001-b%a = -1.1000001

• New operator >>>:

– To compensate for the absence of theunsigned type,

– and to permit better bit levelmanipulation for graphics.

– Java has an unsigned right shift. >>>

CKR Java Notes 69

ww

w.n

eevi

aPDF.

com

Page 343: Java_Comb

Features added by Java (contd.)

Program 16class RightShift{

public static void main (String args[]){

System.out.println (“-1>>4 = ” + (-1>>4));System.out.println (“-1>>>25 = ” +(-1>>>25));char ch = 0x43;System.out.println (“ ”+ch);//char is promoted to int after call to//right shiftSystem.out.println (“ch>>> 1 = ” +

(ch >>> 1));}

}

• Output: -1 >> 4 = -1-1>>>25 = 127 Cch >>>1 = 5

CKR Java Notes 70

ww

w.n

eevi

aPDF.

com

Page 344: Java_Comb

Labeled loops and multi-level breaks

• The goto statement was strongly opposed byproponents of structured programming.

– imagine jumping into the middle of a forloop.

• However, a classic study of thousands of lines ofcomputer code showed that 90% of the time, thegoto was used to jump completely out of deeplynested loops.

• This suggested that the anti-goto lobby had gonetoo far. C offers no other mechanism for jumpingout of deeply nested loops.

• the solution offered by Java is to eliminate goto,but allow jumping out of deeply nested loopsthrough the use of

– labeled breaks, and– labeled continue statements.

• We recall that – break can be used only inside a for,

while, do-while, or switch statement.– continue can be used only inside a for,

while, do-while statement block.

– continue distinguishes between for andwhile loops.

CKR Java Notes 71

ww

w.n

eevi

aPDF.

com

Page 345: Java_Comb

Labeled loops and Multi-Level Break

• Accordingly Java provides an elegant solution tothe goto problem

– by restricting jump statements to loops, – using multi-level break and continue.

• A loop can be labeled, and the break andcontinue statements can be followed by the labelto permit execution to jump out of the loop.

Program 17public class MultiLevelBreak{

public static void main(String args[]){

Identifier1: for (int k=0;k<=2; k++){

System.out.println (“In top for loop”);Identifier2: for (int i=0; i<=20; i++){

System.out.println (“In next for loop”);for (int j=0; j<=30; j++){if (j==2) break Identifier2;if (i==2) continue Identifier1;

System.out.println (“In bottom for loop”);}

}}}}

CKR Java Notes 72

ww

w.n

eevi

aPDF.

com

Page 346: Java_Comb

Pass by value

• Java passes by value means– value of primitive types and reference

value of reference types (objects, arraysetc.) are passed by value.

• Therefore, – A method cannot change the value of a

primitive type.

– A method cannot change an objectreference which is its argument.

• However, – a method CAN change the accessible

variables within an object by invokingthe objects methods or otherwise.

• This is demonstrated by the following program.

Step 1: Define an object

In file: Ncomplex.java

public class Ncomplex{

public float real;public float im;public Ncomplex (float real1, float im1)

CKR Java Notes 73

ww

w.n

eevi

aPDF.

com

Page 347: Java_Comb

{real = real1;im = im1;

}}

Step 2: Define methods which modify arguments, andtheinstance variables of the arguments.

In file: PrimObj.java

public class PrimObj{

public void passPrimitive (float real1,float im1, Ncomplex c)

{real1 = c.real;im1 = c.im;

}public void passObject1 (float real1,

float im1, Ncomplex c){

c.real = real1;c.im = im1;

}

CKR Java Notes 74

ww

w.n

eevi

aPDF.

com

Page 348: Java_Comb

public void passObject2 (Ncomplex c){

Ncomplex c1; /*get object reference.Exactly like declaring a pointer to c1*/

c1 = new Ncomplex(1.0f, 2.0f);/*Initialise the reference declaredearlier */

c = c1;}

}

Step 3: Define a main method which calls the relevantmethod, using the object and primitive data types.

In file: PassRefTest.java

public class PassRefTest{

public static void main (String args[]){

PrimObj my_PrimObj = new PrimObj ();Ncomplex c1 = new Ncomplex (1.0f, 0.0f);Ncomplex c2 = new Ncomplex (0.0f, 1.0f);float real1 = 0.0f;float im1 = 0.0f;/*1: pass primitive and try to change it*/my_PrimObj.passPrimitive (real1, im1, c1);System.out.println (“c1.real = ” +

c1.real);System.out.println (“real1 = ” + real1);

CKR Java Notes 75

ww

w.n

eevi

aPDF.

com

Page 349: Java_Comb

/*2: pass reference and try to change its accessible members*/

System.out.println (“Before: c1.real =” +c1.real);

my_PrimObj.passObject1 (real1, im1, c1);System.out.println (“After: c1.real = ” +

c1.real);

/*3: pass reference and try to changereference*/

System.out.println (“Before: c2.real = ” +c2.real);

my_PrimObj.passObject2 (c2);System.out.println (“After: c2.real = ” +

c2.real);}

}• Output:

c1.real = 1.0real1 = 1.0Before: c1.real = 1.0After: c1.real = 0.0Before c2.real = 0.0After c2.real = 0.0c2.real = 0.0c2.im -= 1.0

CKR Java Notes 76

ww

w.n

eevi

aPDF.

com

Page 350: Java_Comb

Features removed by Java from C++

• Simplicity:

“You know when you have achieved perfectionin design, Not When you have nothing more to add, But when you have nothing more to take away.”

– Antoinne de Saint Exuperyas quoted in the Java LanguageEnvironment White Paper.

• No more– Preprocessor directives– # define

• Keywords removed: No more– typedef– enum– structure– union

since they are all subsumed under the notion of class.

• No more storage class modifiers– auto (default, use static when needed)– extern (no global variables)– register (register access not permitted)–

• Control statements: No more goto

CKR Java Notes 77

ww

w.n

eevi

aPDF.

com

Page 351: Java_Comb

• No more automatic coercions.

• Functions: No more

– default arguments– inline functions

• Operators– No more operator overloading.

• No more pointers?

– No more uninitialised pointers. – (References can always be used.)

• Inheritance– No more multiple inheritance.

Imagine DDD syndrome with dynamicclass binding. DDD = Dreaded Diamond of Derivation

Since, in a distributed environment, user may notknow the entire family tree of the class, and classdesigner may not know all possible end-uses of aclass.

– No more: virtual keyword. – use final in place of const– Unlike C++, final class members may

and must be initialised where declared. final int a=2;

CKR Java Notes 78

ww

w.n

eevi

aPDF.

com

Page 352: Java_Comb

Classes

• Classes in Java are similar to classes in C++. Butthe following salient differences exist.

• The class definition does NOT close with asemicolon.

– Since Java is completely object oriented,there is nothing outside of classes, noteven a semicolon!

• The class itself can have access specifiers– public– (no specifier) default

• A public class is visible to all other classes. – There cannot be more than one public

class within a file.

– The file must have the same name as thename of the public class.

• A default class is visible only to members of itsown package

– (More on packages shortly)

CKR Java Notes 79

ww

w.n

eevi

aPDF.

com

Page 353: Java_Comb

Class members

• Class members: named variables or referencetypes are called fields.

– static fields are called class variables

– non static fields are called instancevariables.

• Class members can also have the followingtypes of access specifiers

– public– private– protected– (no specifier) default

• Note: private protected no longer supported.This is not updated in the book byBalagurusamy.

• Unlike C++, – default access is NOT private

– There is no colon after the accessspecifier

– Access specifiers must be repeated oneach line, else default access isassumed.

CKR Java Notes 80

ww

w.n

eevi

aPDF.

com

Page 354: Java_Comb

– Thus,public int a; int b;

– means that b has default access.

• Members with default access CAN be accessedby other classes in the same package.

• The term protected plays a similar role as it doesin C++

– protected members are like defaultmembers, in that they cannot beaccessed from outside the package.

– However, protected members are unlikedefault members in that they can beinherited, also by subclasses in otherpackages.

CKR Java Notes 81

ww

w.n

eevi

aPDF.

com

Page 355: Java_Comb

Classes: Constructors

• Classes have constructors, as in C++.– If no constructor is specified, then the

system provides a default constructor.

– if any constructor is specified, no defaultconstructor is provided.

– The superclass constructor is alwayscalled as the first line in a constructor. Ifnot explicitly called, then the superclassconstructor with no arguments super()is automatically called, and this mayresult in a compile time error.

• Unlike C++ an appropriate constructor is NOTautomatically called when an object is declared.

• Memory allocation for objects is not doneautomatically: the constructor must be explicitlycalled.

– Thus, if My_Class is a classMyClass mc;

– only declares an object reference. – To obtain the object, memory must be

explicitly allocated, using e.g. the defaultconstructor

mc = new MyClass()

CKR Java Notes 82

ww

w.n

eevi

aPDF.

com

Page 356: Java_Comb

Classes: Memory Deallocation

• However, unlike C++, in Java classes do NOThave destructors.

– Memory deallocation is doneautomatically.

• Java does automatic garbage collection to claimback memory of objects not required any more.

– Garbage collection is done on a lowpriority basis. (More on threads later.)

– Garbage collection strategies areimplementation dependent.

• Garbage collection can be explicitly initiated byhand by calling the method gc() of the Runtimeclass. The gc() method has the signature

void gc()

• Note: Remote applets canNOT access theRuntime class without risking a securityexception.

– Untrusted applets will raise a securityexception.

– hence untrusted applets cannot initiategarbage collection on demand.

CKR Java Notes 83

ww

w.n

eevi

aPDF.

com

Page 357: Java_Comb

Memory Deallocation: finalize() method

• There is also a finalize method which has thesignature

protected void finalize()• The finalize method is normally called just before

garbage collection is initiated.

• However, whereas C++ destructors are calleddeterministically whenever an object goes out ofscope, the finalize method is not.

– Specifically, the finalize method may ormay not be called even if garbagecollection is manually initiated.

• Since Applets cannot usually initiate garbagecollection, on demand, it is even more uncertainwhen finalize will be called in Applets.

• Hence the finalize method should make NOassumptions about what objects exist and whatdo not.

• Better procedure is to define a method, saycleanup, which is explicitly called just before theobject goes out of scope.

• These ideas are illustrated by the followingprogram.

CKR Java Notes 84

ww

w.n

eevi

aPDF.

com

Page 358: Java_Comb

Program 18class MyClass{

float myfloat [];MyClass()//define constructor{

myfloat = new float [2000];System.out.println (“Constructor called”);

}protected void finalize (){

System.out.println (“Finalize called”); }

}public class Finalize{

public static void main (String args[]){

Runtime r = Runtime.getRuntime();//Runtime class cannot be instantiated//however we can get a reference to it.

long tmem, bmem, amem;tmem = r.totalMemory(); //returns longbmem = r.freeMemory();

System.out.println (“Total Memory: ” +tmem);

System.out.println (“Free Memory Before: ”+ bmem);

CKR Java Notes 85

ww

w.n

eevi

aPDF.

com

Page 359: Java_Comb

if (true){

//instantiate MyClass and invoke its//constructorMyClass myclass = new MyClass();

//again check free memoryamem = r.freeMemory();System.out.println (“Free Memory After”

+"allocation: “ + amem);}

//myclass goes out of scope;r.gc(); //initiate garbage collectionamem = r.freeMemory();System.out.println (“Free Memory After”

+ “garbage collection: ” + amem);}

}

• Sample output: Total Memory = 1048568Free Memory Before: 927824Constructor calledFree Memory After allocation: 918608Free Memory After garbage collection: 923208Application Exit...

• Note: Finalize method was NOT called in theabove run.

CKR Java Notes 86

ww

w.n

eevi

aPDF.

com

Page 360: Java_Comb

Inheritance and Polymorphism

• Theoretically, Java permits only multi-levelinheritance.

– That is, a given class can have exactlyone superclass.

• Officially Java does not permit multipleinheritance. But multiple inheritance creeps inthrough

– interfaces (officially), and – inner classes (more on this later.).

• Unlike C++– No colon “:” is used to indicate the base

class. Instead one uses the keywordextends. For example,

public class MyApplet extends Applet

• The base class of C++ is called superclass inJava.

– There is no scope resolution operator,but one can refer to the superclassmembers using the keyword super.

– This is the counterpart of the thispointer available in any non-staticmethod.

CKR Java Notes 87

ww

w.n

eevi

aPDF.

com

Page 361: Java_Comb

Polymorphism: method overloading and overriding

• Overloading works exactly as in C++.

• Overloading means that two methods – have the same name, but– have different parameter lists– so that they have different signatures. – (Note: signature differences due to

differences in return type alone are notpermitted: the parameter lists must bedifferent. )

• Overriding means that two methods– have the same name, and– have the same parameter lists– so that they have the same signature, – but one method is defined in a super

class, – and the second method is defined in a

derived class.

• Overriding works exactly as in C++. Thiscorresponds to dynamic polymorphism.

– the right version of the method is calledat run time.

• However, instead of pointers, one uses objectreferences.

CKR Java Notes 88

ww

w.n

eevi

aPDF.

com

Page 362: Java_Comb

Program 19import java.io.*;class Animal{

void sleep (){

System.out.println (“Animalzzz..”);}void sleep (int t) //overload sleep method{

System.out.println (“Animalzzz... for”+ t + “ seconds”);

}}

class Dog extends Animal{

void sleep () //override sleep method{

System.out.println (“Dogzzz...”);}

void sleep (int t) //override second sleep method

{System.out.println (“Dogzzz... for ” +

t + “ seconds”);}

}

CKR Java Notes 89

ww

w.n

eevi

aPDF.

com

Page 363: Java_Comb

class Mongrel extends Dog{

void sleep () //override sleep method{

System.out.println (“Mongrelzzz...”);}

void sleep (int t) //override second sleep method

{System.out.println (“Mongrelzzz... for ” +

t + “ seconds”);}

}

public class Polymorph{

public static void main (String args[])throws IOException

{//obtain a reference to AnimalAnimal my_Animal;

//initialise to Animal objectmy_Animal = new Animal();int trun;DataInputStream in = new

DataInputStream(System.in);System.out.println (“\n Enter an integer”);

CKR Java Notes 90

ww

w.n

eevi

aPDF.

com

Page 364: Java_Comb

String inString = in.readLine();trun = Integer.parseInt (inString); switch (trun){

case 1://re-initialize the reference to an//appropriate object

my_Animal = new Dog();break;

case 2:my_Animal = new Mongrel();break;

default:break;}

//just code the following two linesmy_Animal.sleep(); my_Animal.sleep(2);//the right version of sleep is called.

}}• Ouptut: The right version of sleep is called.

E.g. input trun = 1, output: Dogzzz...Dogzzz... for 2 seconds

CKR Java Notes 91

ww

w.n

eevi

aPDF.

com

Page 365: Java_Comb

Overriding (contd): abstract and final classes

• Since there is no virtual keyword in Java, thereare no pure virtual functions.

• However, a method which has noimplementation is called an abstract method, andmay be ddeclared as such, using the abstractkeyword. abstract ret_type method_name (args);

• A class containing an abstract method is notonly known as an abstract class, it must bedeclared as such.

• Though an abstract class cannot be instantiated,a reference to it can be created.

– This is essential to permit dynamicpolymorphism.

• In the preceding example, if one or both of thesleep methods in the Animal class is declaredabstract, then the class cannot be instantiated,so its constructor cannot be called.

– However, the rest of the program willwork similarly.

• On the other hand, to prevent a method frombeing overridden one can declare the method (orclass) to be final, using the final keyword.

– A final class cannot be subclassed.

CKR Java Notes 92

ww

w.n

eevi

aPDF.

com

Page 366: Java_Comb

Packages and C++ namespaces

• Since Java, like C++, permits both – method overloading, and – method overriding

An unintended name collision can lead to unexpectedprogram behaviour.

• Such unintended name collision may arise, forexample when using two libraries sourced fromtwo different third-parties.

• 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

libraries and change the name– persuade the owner of the library to

recompile the library after changing thename of the concerned function.

• Very often, none of these choices was feasible.

• Hence it is desirable to have a mechanism tolimit the scope of names.

• This is achieved in C++ through the use ofnamespaces.

• Java uses packages.

CKR Java Notes 93

ww

w.n

eevi

aPDF.

com

Page 367: Java_Comb

Packages (contd)

• A package is created by the statementpackage pkg;

• A package statement always has file scope, sothat

– a package statement, if used, must bethe first statement in a file.

– If no package statement is used, adefault package is automaticallyprovided.

• The use of a package limits the scope of names,so that the fully qualified name of a variable ormethod is its name preceded by the packagename. pkg.my_variable

– Note that Java uses a dot, since there isno scope resolution operator.

• The fully qualified name may be abbreviatedwithin the file by an import statement

import pkg.*; //imports all classes in pkg

– The Java import statement is thecounterpart of the C++ usingstatement.

CKR Java Notes 94

ww

w.n

eevi

aPDF.

com

Page 368: Java_Comb

Packages: Java source file structure

• Thus, a java source file can have any or all of thefollowing four internal parts.

• (1) A single package statement (optional)– this must be the first non-comment

statement of the program

• (2) Any number of import statements (optional)

• (3) A single public class declaration (necessary)

• (4) Any number of class declarations (optional)– subject to the overall limitations of the

JVM.

• If multiple import statements lead to a namecollision, this will be flagged as an error.

• That is, if package pkg1 has a class calledMyClass, and package pkg2 also has a classcalled MyClass, and if one invokes MyClass,without specifying the package name, this will beflagged as an error.

CKR Java Notes 95

ww

w.n

eevi

aPDF.

com

Page 369: Java_Comb

Packages: hierarchies and CLASSPATH

• Like namespaces, packages may be nested intoa hierarchy.

package pkg1.pkg2.pkg3

• For the benefit of the JVM Class Loader, – public class names must match file

names, and

– A package hierarchy must match thedirectory structure.

• CLASSPATH environment variable must be set tothe root of this directory tree.

– Preferably use -classpath option, insteadof setting the CLASSPATH variableglobally.

• In the following example, there are two packages– pkg1 in e:\java\kawa\pkg1 directory– pkg2 in e:\java\kawa\pkg2 directory

• set CLASSPATH to include e:\java\kawa – (Java 1.1)

setCLASSPATH=.;e:\java\lib\CLASSES.ZIP;e:\java\kawa

– java 1.2set CLASSPATH=.;e:\jdk1.2;e:\java\kawa

CKR Java Notes 96

ww

w.n

eevi

aPDF.

com

Page 370: Java_Comb

Package and access: example

Program 20• Source in file e:\java\kawa\pkg1\Base.java

package pkg1;

public class Base{

public int pub; //public accessprotected int prot; //protectedint def;//default access //inconsistent declaration//private protected int priprot; //illegal

private int priv; }

class Derived extends Base{

int deriv;void showPriv (){//error: private variables are not//inherited//System.out.println (“b.priv = ” + priv);}

}

CKR Java Notes 97

ww

w.n

eevi

aPDF.

com

Page 371: Java_Comb

• Source in file e:\java\kawa\pkg1\InheritTest.java

package pkg1;import pkg2.*;public class InheritTest{

public static void main (String args[]){

Base b = new Base();Derived d = new Derived();System.out.println (“b.pub = ” + b.pub);System.out.println (“d.pub = ” + d.pub);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);//error: private variable not accessible//System.out.println (“b.priv = ” +

//b.priv);

//Now declare object from another package

Other o = new Other();System.out.println (“o.pub = ” + o.pub);System.out.println (“o.prot = ” + o.prot);

//def variable may be accessed thus.System.out.println (“o.def = ” + o.def);

// o.showDef ();//error showDef not//accessible hereo.showProt();}}

CKR Java Notes 98

ww

w.n

eevi

aPDF.

com

Page 372: Java_Comb

Source in e:\java\kawa\pkg2\Other.java

package pkg2;import pkg1.*;public class Other extends Base{

int other;void showDef (){

//error variable def not accessible here//System.out.println (“o.def = ” + def);//protected variable from other package//can be accessed here.public void showProt () { System.out.println (“o.prot = ” + prot);}

}}

• Output:

b.pub = 0d.pub = 0b.prot = 0d.prot = 0b.def = 0d.def = 0o.pub = 0o.prot =0o.def = 0o.prot = 0

CKR Java Notes 99

ww

w.n

eevi

aPDF.

com

Page 373: Java_Comb

Access rules for class members

Private Default Protected PublicSame class Y Y Y Y

Same package:subclass

N Y Y Y

Same package:nonsubclass

N Y Y Y

Differentpackage:subclass

N N Y Y

Differentpackage

non-subclassN N N Y

CKR Java Notes 100

ww

w.n

eevi

aPDF.

com

Page 374: Java_Comb

JAR files

• JAR files are Java archive files.• Exactly like zip files, except that the terminology

and usage relates to Unix, where – tape archive files are called tar files.– Moreover, compressed JAR files are

acceptable to the JVM. • Bundling and Compression: The advantage of

zip files is that the directory structure can berecursed and stored in the zip file.

• Portability: This makes JAR files particularlysuitable for storing and transferring largepackages.

– E.g. on Mac more than 32 characterswere not accepted as Dir names

• Thus, the previous example can also be run byfirst archiving and calling the jar tool fromE:\java\kawa directory (Java 1.1)

jar -cvf0 Inherit.jar pkg1c= create new, v=verbose, f=filename 0= nocompression.

• Since the argument is a directory, it isautomatically recursed.

• One now adds Inherit.jar to the classpath, andinvokes java InheritTest, and the classloader willlocate the InheritTest class.

• Security: Jar files can be signed, thus providinga layer of security.

CKR Java Notes 101

ww

w.n

eevi

aPDF.

com

Page 375: Java_Comb

Interfaces

• Java’s first route to multiple inheritance isprovided through interfaces.

• Usually, in multiple inheritance one is interestedonly in the methods, and not in duplicateinheritance of data members.

• An interface contains only– constants (i.e., final data members), and– method declarations

– Like a class the interface itself can havedefault or public access.

access_type interface i_name { return_type method1(param_lst);return_type method2 (param_lst);type final var_name1 = value;...}

• However, all methods and constants in aninterface are implicitly public.

• A class implements an interface. – i.e., the class defines the methods

declared in the interface.

CKR Java Notes 102

ww

w.n

eevi

aPDF.

com

Page 376: Java_Comb

– all interface methods must be declaredpublic in the class implementation.

• A class may implement more than one interface,by providing a comma separated list ofinterfaces.

access class class_name [extendssuperclass_name] implementsinterface_name1, interface_name 2{...]

• If a class which implements an interface, doesnot implement all the methods of that interface,then the class must be declared as abstract.

• Any subclass must either implement all themethods or be itself declared as abstract.

• Interfaces thus provide a form of multipleinheritance, in which a class may inheritmethods from a variety of sources.

CKR Java Notes 103

ww

w.n

eevi

aPDF.

com

Page 377: Java_Comb

Dynamic polymorphism, extending interfaces andadapter classes

– An object reference may be declared tobe of interface type.

– This reference may be assigned at runtime to any one of various classes whichimplements the interface.

– The implemented methods of that classwill be called.

• Inheritance of interfaces:– One interface can extend another

interface.

interface mine extends yours{

//new methods]

• A class which now implements interface minemust implement all the methods in yours andmine.

• However, there are Adapter classes which enableone to implement only part of an interface.

CKR Java Notes 104

ww

w.n

eevi

aPDF.

com

Page 378: Java_Comb

Program 21interface Area{

final float pi = 3.14f;float area (float diameter);

}

class Circle implements Area{

public float area (float diameter){

return pi*diameter;}

}

class Square implements Area{

public float area (float diameter){

return diameter*diameter;}

}

CKR Java Notes 105

ww

w.n

eevi

aPDF.

com

Page 379: Java_Comb

public class Interf{

public static void main (String args[]){

Area a; a = new Circle();

System.out.println (“Area of circle = ” +a.area (2.0f));

a = new Square();System.out.println (“Area of square= ”+

a.area (2.0f));}

}

• Output: Area of circle = 6.38Area of square = 4

CKR Java Notes 106

ww

w.n

eevi

aPDF.

com

Page 380: Java_Comb

Inner classes and multiple inheritance in Java

• Interfaces provide one route to multipleinheritance.

• Inner classes provide another route.

• This second route is not documented, and sundocumentation speaks of adapter classes.

• However, while inner classes may be used in thatcontext, adapter classes are irrelevant to thebasic syntax of inner classes.

• One class may be defined within another.

• Such a class is called a nested class.

• A static nested class behaves like a top-levelclass (i.e., a class which is not contained in anyclass)

• A non-static nested class is called an inner class.

• Such nested classes may be defined within anyexpression.

CKR Java Notes 107

ww

w.n

eevi

aPDF.

com

Page 381: Java_Comb

Nested and inner classes (contd)

• Nested classes have access to all of thevariables of the enclosing class.

• However, the enclosing class must access thenested class variables through an objectreference.

• The key point is that the nested class can inheritindependently of the inheritance hierarchy of theenclosing class.

• Thus, inner classes permit multiple inheritance inpractice.

• This is illustrated by the following example.

• Note: Java rejects multiple inheritance inprinciple, since it permits one class to have onlyone superclass.

– Inner classes do NOT negate this rule inprinciple.

– However, through inner classes, one caneffectively subvert this principle inpractice.

CKR Java Notes 108

ww

w.n

eevi

aPDF.

com

Page 382: Java_Comb

Program 22

• In file: e:\java\kawa\pkg2\Base2.javapackage pkg2;public class Base2{

int base2;protected void base2Method(){

System.out.println (“In Base 2");}

}

• In file: e:\java\kawa\pkg1\MultipleInherit.javapackage pkg1;class Base1{

int base1;void base1Method(){

System.out.println (“In Base 1");}

}

class Derived extends Base1

{int derivInt=2;

CKR Java Notes 109

ww

w.n

eevi

aPDF.

com

Page 383: Java_Comb

class Inner extends pkg2.Base2{

void showInner(){

base1Method();base2Method();

//access protected method from other//package

System.out.println (”Though I abused"+“multiple inheritance, I still use it”);

}}//end of class Innervoid deriv(){Inner i = new Inner();i.showInner();}}public class MultipleInherit {

public static void main(String args[]){

Derived d = new Derived();d.deriv();//Inner i = new Inner(); //illegal//i.showInner();

} }• Output:

In Base 1In Base 2Though I abused multiple inheritance, I still use it.

CKR Java Notes 110

ww

w.n

eevi

aPDF.

com

Page 384: Java_Comb

Exceptions

• An exception is an unusual condition in aprogram.

– Example: an illegal mathematicaloperation is an exception.

– Eg. integer division by zero will lead toan exception and to immediate programtermination.

Program 23public class DivideByZero{

public static void main (String args[]){

int a=1;int b=0;System.out.println (“a/b = ” + a/b);

}}

• output: java.lang.ArithmeticException: / byzero

atDivideByZero.main(DivideByZero.java:7)Application Exit

CKR Java Notes 111

ww

w.n

eevi

aPDF.

com

Page 385: Java_Comb

• Though the stack trace provided by Java ishelpful to the programmer for debugging, suchabrupt termination is likely to leave the userconfused.

• Exceptions allow the programmer to handle suchsituations smoothly..

• The classical C approach to exception handlinginvolves two routes.

– signal and raise– setjmp and longjmp

• In the signal method, an exceptional condition,such as division by zero, is indicated by meansof a signal SIGFPE, defined in signal.h

• (Alternatively, a user may raise a signal throughraise.).

• When a signal is raised, a signal handler (afunction) is called.

• A default signal handler is provided, and the usermay override it by registering an alternativesignal handler (pointer to a function).

• A default math error handler is provided, and theuser may override it by redefining the functionmatherr.

CKR Java Notes 112

ww

w.n

eevi

aPDF.

com

Page 386: Java_Comb

• These considerations are illustrated by thefollowing C program (which works also in C++)

Program 24#include <stdlib.h>#include <stdio.h>#include <math.h>#include <signal.h>

/*==trap floating point errors === */void float_trap(int sig){ fixerr(); /*do some deallocation*/printf(“\n Encountered a floating point”,“error.”);

printf(“\n Check whether the last input:,”was mathematically well-posed.");

return;}/*==signal handler for floating pointerrors====*/void siginst(void)r{ if (signal(SIGFPE, float_trap) == SIG_ERR)

{ printf(“Error installing signal”“handler.\n”);

exit(3);}

}/*=user defined handler for math errors =*/ int matherr (struct exception *a) {

CKR Java Notes 113

ww

w.n

eevi

aPDF.

com

Page 387: Java_Comb

/*This user-modifiable function is calledautomatically when a mathematical erroris encountered. struct exception isdefined in math.h*/

char *s1; fixerr(); printf (“\n Encountered a mathematicalerror,”); printf (“\n related to the function:%s.”,a->name); switch (a->type)

{case DOMAIN: s1 = “The argument was”

“outside the domain of the function.”;break;

case SING: s1= “The argument was singular”“(i.e., on the domain boundary).”;break;

case OVERFLOW: s1="The function value was"“too large.”; break;

case UNDERFLOW: s1="The function value"“was too small.”; break;

case TLOSS:case PLOSS:s1="There was total or partial"

“loss of significance.”; break;default: s1= “ ”; break;

} printf (“\n %s\n\n”, s1); exit(1); return 1;

}

CKR Java Notes 114

ww

w.n

eevi

aPDF.

com

Page 388: Java_Comb

/*=============fixerr================*/ fixerr(){ }

/* ============main=============== */ main() {

float a=1, b=0;float c;system(“cls”);siginst (); /*install signal handler*//*if (b==0)raise (SIGFPE);*//*The commented code above is an example

of a user generated signal. Below thesignal is raised by the system*/

c=a/b;c = log (-a);return;

}• Output:

Encountered a floating point error...Encountered a mathematical errorrelated to the function logThe input was outside the domain ofthe function.

CKR Java Notes 115

ww

w.n

eevi

aPDF.

com

Page 389: Java_Comb

Exceptions (contd)

• The other way to handle exceptions is throughthe functions setjmp and longjmp.

• The state of the stack at a user-determined pointin the program is saved through a call to setjmp.

• If an error is subsequently encountered, thestack is unwound to the previously saved state,i.e., the program executes a goto to thepreviously saved state by calling longjmp.

• This is illustrated by the following program.

CKR Java Notes 116

ww

w.n

eevi

aPDF.

com

Page 390: Java_Comb

Program 25#include <stdio.h>#include <setjmp.h>#include <signal.h>jmp_buf jumper;/*jmp_buf is a structure defined insetjmp.h*//*==trap floating point errors ==== */void float_trap(int sig){

char *s = “\n\n Encountered a floatingpoint error”;

printf (“%s”, s);longjmp (jumper, 1);

}/*===signal for floating point errors=========*/void siginst(void){

if (signal(SIGFPE, float_trap) == SIG_ERR){printf(“Error installing signal

handler.\n”);exit(3);}

}/* ==============main=============== */main(){

int value;

CKR Java Notes 117

ww

w.n

eevi

aPDF.

com

Page 391: Java_Comb

float a=1, b=0;float c;siginst (); /*install signal handler*/value = setjmp(jumper);if (value != 0){

printf(“\n Longjmp with value %d\n”,value);

goto next;}c=a/b;next:

printf (“\n Reached next”);return;

}

• Output: Error encountered Long jump with value 1 Reached next.

• While this approach may be used in C++ it hascertain disadvantages.

• The disadvantages of this older approach ofhandling exceptions, arise from certain newfeatures introduced by C++, namely classes andobjects.

CKR Java Notes 118

ww

w.n

eevi

aPDF.

com

Page 392: Java_Comb

Exceptions (contd.)

• Consider the following sort of code involvinglongjmp

void some_function (){

FILE* fp = fopen (fname, “rw”);float *pf = (float *) malloc (1000*sizeof(float);

/* do something */if (error)

longjmp (jumper, ErrorCode);/*do something else*/fclose (fp);free (pf);}

• if the program encounters an exception, andtakes a long jump to the previously saved state.

• Hence the file handle is not closed, andsubsequent attempts to access the same filewould fail.

– If a new file is opened each time, thesystem would soon run out of filehandles.

• The dynamically allocated memory would not bereturned to the heap.

CKR Java Notes 119

ww

w.n

eevi

aPDF.

com

Page 393: Java_Comb

Exceptions (contd)

• Thus, a longjmp creates a problem when thereare interim resources at risk.

• Since the longjmp has to be executed at thepoint where the error/exception is encountered,all resources must be freed.

• However, unwinding the stack only freesautomatic variables and function calls.

• The manually allocated heap memory, and otherresources must be freed manually.

• This is difficult to perform in C++/Java, sincereferences to objects also occupy the stack.

• Unwinding the stack frees the references tothese objects, but it does not free the heapmemory occupied by the objects.

• For that to happen, the destructor functionsmust execute, and this would be bypassed whena longjmp takes place.

• Hence, C++/Java needs an alternative method ofexception handling.

CKR Java Notes 120

ww

w.n

eevi

aPDF.

com

Page 394: Java_Comb

Exception handling: Java specific

• In Java exception handling is done through 5keywords

– throw– try– catch– throws– finally

• When an exception is thrown, – not only is the stack unwound to a

previously saved state, but– automatic objects are marked for

finalization (destructors are exeecuted inC++)

– if the exception is thrown from within aconstructor, the finalizer of that object isnot executed.

– key resources may be manually freedthrough the use of a finally block which isguaranteed to execute, whether or not anexception is thrown.

• The code to be monitored is put into a a try block.

• The action to be taken, when an exception isthrown is put into various catch blocks.

CKR Java Notes 121

ww

w.n

eevi

aPDF.

com

Page 395: Java_Comb

• Each catch block decides what action is to betaken when a particular exception is thrown.

try{//try block}catch (Exception_type1 arg){ //catch block}catch (Exceptiontype2 arg){ //catch block 2}...

Object

Throwable

Error Exception

RunTimeException

ArithmeticException

CKR Java Notes 122

ww

w.n

eevi

aPDF.

com

Page 396: Java_Comb

Exceptions: try, throw, catch sequence

• The following code is an example of a basictry-throw-catch sequence.

Program 26public class CatchException{

public static void main(String args[]){

int a = 1;int b = 0;try //start try block{

System.out.println (“Trying...”);int c = a/b; //exception is thrown

}catch (ArithmeticException e)//and caught{

System.out.println (“Well caught”);}System.out.println (“Normal program exit”);

}}

• Output: Trying...Well caughtNormal program exit.

CKR Java Notes 123

ww

w.n

eevi

aPDF.

com

Page 397: Java_Comb

Exceptions: multiple catch blocks

• Catch is not called: program execution istransferred to it.

– if no exception occurs, then the catchblock will NOT execute.

• There may be more than one catch block. – Each catch block handles one type of

exception .

– But only that catch block will beexecuted which matches the type of theexception generated.

• Thus, if we rewrite the previous program, so that

– there are two catch blocks:

– one which handles arithmetic exceptions.

– and one which handles i/o exceptions,

– and if an integer is incorrectly entered,

– then the exception will NOT be caught,and an abnormal program terminationwill occur .

CKR Java Notes 124

ww

w.n

eevi

aPDF.

com

Page 398: Java_Comb

Program 27import java.io.*;public class MultipleCatch{

public static void main(String args[]){ int a;

int b;

try{

System.out.println (“a = ”);DataInputStream in = new

DataInputStream(System.in);String inString = in.readLine();a = Integer.parseInt (inString);System.out.println (“b = ”);b = Integer.parseInt (in.readLine());int c = a/b;

}catch(ArithmeticException e){

System.out.println (“Caught Arithmetic"+“exception”);

}catch (IOException i){ System.out.println (“Caught i/o”+

“exception”);}System.out.println (“Program exit”);

}}

CKR Java Notes 125

ww

w.n

eevi

aPDF.

com

Page 399: Java_Comb

• Case 1: input: a=2b=3

• output: Program exit

• Case 2: Inputa=2b=0

• Output: Caught Arithmetic Exception Program exit

• Case 3: input: a= *

• output: java.lang.NumberFormatException: * at java.lang.Integer.parseInt(Integer.java:231) at java.lang.Integer.parseInt (Integer.java:278) at MultipleCatch.main (MultipleCatch.java:15)

• Case1: no catch block is executed, since noexception is thrown.

• Case 2: the first catch block is executed, sincean ArithmeticException is thrown.

• Case 3: a NumberFormatException is thrown butthere is no matching catch block. Hence theprogram terminates

CKR Java Notes 126

ww

w.n

eevi

aPDF.

com

Page 400: Java_Comb

Exceptions: Throwable and checked exceptions

• Unlike C++, primitive types cannot be thrown.Throwable types must be subclasses ofThrowable

• In the previous example we saw that anuncaught exception leads to programtermination.

• Not all exceptions can be uncaught. Exceptionsmay be divided into two classes

• Unchecked exceptions are– subclasses of Error, or– subclasses of RunTimeException

• checked exceptions: all others

Exceptions: catch all

• if a method can generate checked exceptions,then these must be either

– specified using a throws clause – or caught in a try block

else there is a compile-time error

• Unchecked exceptions need not be specified.– hence lazy programmers tend to

subclass RunTimeException to producetheir exceptions.

– Program 28

CKR Java Notes 127

ww

w.n

eevi

aPDF.

com

Page 401: Java_Comb

class MyException extends Exception{

int exception_num;}

public class CheckedException{int myMethod (int a, int b) throws

MyException{MyException e = new MyException();if (a==0)

{e.exception_num = 1;throw e;}

if (b==0){e.exception_num=2;throw e;}

return a/b;}public static void main (String args[]) {

CheckedException e = newCheckedException();

try{

e.myMethod (0, 1);}

CKR Java Notes 128

ww

w.n

eevi

aPDF.

com

Page 402: Java_Comb

catch (MyException me){

System.out.println (me.exception_num);}

}}

• The above program will NOT compile if – the throw clause is removed from

myMethod, or– the catch clause is removed from main

(and no throws clause is provided tomain)

CKR Java Notes 129

ww

w.n

eevi

aPDF.

com

Page 403: Java_Comb

Catch all exception handler

• Since all exceptions are subclasses ofException,

– To catch all exceptions, one uses thecatch-all exception handler withException as the type

catch (Exception e) { //catch block}

• Since one exception is handled by at most onecatch block,

– if there is more than one catch block, – and a catch-all,

• then the catch-all error handler must appear last– for the first catch block which fits the

exception will be executed.

• Similarly, if there are two catch blocks oneinvolving a base type and one a derived type,

– then the catch block with base type mustappear last

– since a base type will fit a derived type,but not vice versa.

CKR Java Notes 130

ww

w.n

eevi

aPDF.

com

Page 404: Java_Comb

Exceptions: Miscellaneous

• Try blocks may be nested.– In this case, if the first try block does not

have an appropriate handler for theexception, the exception will be passedto the outer block, and so on.

– The exception can be handled by bothinner and outer catch block, by makingthe inner catch block rethrow what it hascaught.

• A finally clause may be associated with each tryblock, and this is guaranteed to execute.

– The JVM achieves this by checking allpossible exits to the try block.

CKR Java Notes 131

ww

w.n

eevi

aPDF.

com

Page 405: Java_Comb

Program 29import java.io.*;public class NestedCatch{

public static void main(String args[]){

int a; int b;

try{try{

System.out.println (“a = ”);DataInputStream in = new

DataInputStream(System.in);String inString = in.readLine();a = Integer.parseInt (inString);System.out.println (“b = ”);b = Integer.parseInt (in.readLine());int c = a/b;

}catch(ArithmeticException e){

System.out.println (“Caught Arithmeticexception”);

throw e; //rethrow}

CKR Java Notes 132

ww

w.n

eevi

aPDF.

com

Page 406: Java_Comb

catch (IOException i){

System.out.println (“Caught i/oexception”);

}finally {

System.out.println (“Exiting inner try”);}}catch(Exception e){

System.out.println (“Caught something”);}System.out.println (“Program exit”);

}}

• input: a=2b=2

• output:Exiting inner tryProgram exit

• input:a=*

• output: Exiting inner tryCaught somethingProgram exit

CKR Java Notes 133

ww

w.n

eevi

aPDF.

com

Page 407: Java_Comb

Threads

• A multitasking OS, such as UNIX or Widows,handles several processes at the same time.

• Each process is an independently executingprogram, which may be

– running– ready, or – blocked (waiting for input)

• A thread is a subsequential flow of control withina single sequential program.

– That is, a thread is a “lightweight”process (or a sub-process) that runsfrom within a program.

• That is, a thread is a process, where theoverheads involved in switching from one threadto another are small, since

– a thread runs from within the program– a thread shares the existing memory

space allocated to the program– Inter-thread communication is easier.

• From a logical point of view, however, threadsare best thought of in terms of Hoare’s paradigmof

– communicating sequential processes.– since only one processor, and one

program is involved, the operationaloverheads are small in practice.

CKR Java Notes 134

ww

w.n

eevi

aPDF.

com

Page 408: Java_Comb

Threads (contd.)

• Logically, the CSP (Communicating SequentialProcesses) model applies to

– parallel processing– multi-tasking– threads

• However, the goals in each case are different.

– In parallel processing, the goal is toimprove performance at low cost, byincreasing the number of processors,each of which runs a separate process.

– In multi-tasking, the goal is to make moreefficient use of a single processor (CPU),by running other processes when theCPU is idle because a given process iseither blocked or idle, or does not needall the system resources.

• Java uses threads to permit part of a program toexecute, even when another part of the programis

– blocked (waiting for input)– or running in an infinite loop.

CKR Java Notes 135

ww

w.n

eevi

aPDF.

com

Page 409: Java_Comb

Threads (contd)

• Thus, animation typically requires an infiniteloop.

– if a program has only one thread, it canperform animation, but do no other task.

– Typically, however, one wants ananimation, as a background, while someother process runs in the foreground.

• Similarly, GUI typically involves event drivenprogramming.

– A particular text box (window) is in aninfinite loop,

– waiting for events, or– handling events.

• Without threads, nothing else could executeuntil a particular event handler returns.

– With multi-threading, one thread can waitfor events or handle events withoutblocking other parts of the program.

• Finally, network download times are uncertain,so threads are essential for a complex program.

• Thus, though Java is architecture-neutral it canrun only in a multi-tasking environment!

CKR Java Notes 136

ww

w.n

eevi

aPDF.

com

Page 410: Java_Comb

Threads

• Like a process, a thread can exist in variousstates

– running– ready– suspended– resumed– blocked

• In any of the above states the thread is alive. Athread an be terminated, in which case it is nolonger alive.

• Some key concepts associated with threads arethe following.

• Priority, decides how much of the process timethe thread will consume.

• Synchronization: – if one thread updates names, and– another updates addresses

the two threads must be synchronized to ensure thatnames and addresses match!

• Deadlock:If two threads simultaneously accessthe same resource, this can result in a deadlock.

– e.g. two people speaking simultaneouslyin an international call.

CKR Java Notes 137

ww

w.n

eevi

aPDF.

com

Page 411: Java_Comb

Threads: implementation

• Every Java program has a Main thread. – The main thread is the first thread to start

– and it must be the last thread to finish

– since other threads are spawned orforked from the main thread.

• Threads may be implemented in two ways. – implement the Runnable interface– extend the Thread class.

• The interface Runnable has the run methodwhich has the prototype

public void run();

• There is no major difference between these twomethods, since the Thread class extends Objectand implements Runnable.

– If the Thread object is created bypassing it a Runnable object then the runmethod of the Runnable object isinvoked.

– Else the run method of the thread classdoes nothing.

CKR Java Notes 138

ww

w.n

eevi

aPDF.

com

Page 412: Java_Comb

• Hence, in both cases, the run method must beoverridden.

• In both cases, the entry point for the thread is therun method.

• In both cases, one must create a Thread object.

• The Thread class has several constructors.Some common constructors are given below.

Thread();Thread (Runnable, String);Thread (String)

• The String passed to Thread decides the name ofthe thread.

– Two distinct threads can have the samename.

– Or a thread may not have a name– (the system will provide an internal name)

• The Runnable object passed to the Threaddecides the run method which will be invoked.

• After the Thread is created one must explicitlycall its start method, upon which the JVM will callthe Thread’s run method.

CKR Java Notes 139

ww

w.n

eevi

aPDF.

com

Page 413: Java_Comb

Program 30class MyThread implements Runnable{

Thread t; //instantiate ThreadMyThread(int id)//define constructor{

String myThreadName = new String(“mythread” + id);

t = new Thread (this, myThreadName);

System.out.println (“Child thread"+ “starting” + t);

t.start(); //New thread must be explicitly started}

public void run() //start calls run{

try{

for (int i=0; i<10; i++){

System.out.println (“Child awake: ”+ i);t.sleep(100); //sleep for 100 ms

//method sleep throws InterruptedException}

} catch (InterruptedException e){

System.out.println (“Child interrupted”);}

CKR Java Notes 140

ww

w.n

eevi

aPDF.

com

Page 414: Java_Comb

System.out.println (“Child thread done”);}

}

public class ThreadMain{

public static void main (String args[]){

//get a reference to the main thread//currentThread is a static method of//the Thread classThread t = Thread.currentThread(); System.out.println (“Started ” + t);

//start two new threadsMyThread n1 = new MyThread (1);MyThread n2 = new MyThread (2);

try{

for (int i=10; i>0; i—)System.out.println (“Main thread going to”

+ “sleep ” + i);//sleep is a static method//the second argument is nanosecond!Thread.sleep(2000, 2);//if 2000 is changed a deadlock may result

} catch (InterruptedException e){

CKR Java Notes 141

ww

w.n

eevi

aPDF.

com

Page 415: Java_Comb

System.out.println (“Main threadinterrupted”);

}System.out.println (“Main thread done”);

}}

• Output: Started Thread [main, 5, main]Child thread starting Thread [mythread1, 5, main]Child thread starting Thread [mythread2, 5, main]Child awake: 0Main thread going to sleep 10Main thread going to sleep 9Main thread going to sleep 8Main thread going to sleep 7Main thread going to sleep 6Main thread going to sleep 5Child awake: 0Main thread going to sleep 4Main thread going to sleep 3Main thread going to sleep 2Main thread going to sleep 1Child awake: 1Child awake: 1...Child thread doneChild thread doneMain thread done

CKR Java Notes 142

ww

w.n

eevi

aPDF.

com

Page 416: Java_Comb

Threads (contd)

• In the above, the synchronization between themain thread and the child threads is dicey.

• This has been accomplished by putting the mainthread to sleep for a longer time.

• To ensure more reliable synchronization, we usethe join method.

• The join method is the opposite of fork. – the child threads were forked from the

main thread, – the thread which calls join() waits until

the other thread joins it (i.e., dies)

• To use this method, add the following code, andreduce the sleeping time of the main method)

//improved synchronizationSystem.out.println (“Main waiting for children to finish”); try{

n1.t.join(); n2.t.join(); } catch (InterruptedException e) { System.out.println (“Child thread interrupted”); } System.out.println (“Main thread done”);

CKR Java Notes 143

ww

w.n

eevi

aPDF.

com

Page 417: Java_Comb

Threaded applets

• Threaded applets can be created in exactly thesame way.

• A threaded applet will extend Applet andimplement Runnable.

• An example is given below.Program 31//A parametrized banner

import java.awt.*;import java.applet.*;

/*applet code="Parmc" width = 300 height = 50param name=message value="Time neverstops!"param name=fontName value="Times New Roman"param name=fontSize value="18"/applet*/

public class Parmc extends Appletimplements Runnable{

String msg;String fN;int fS;

CKR Java Notes 144

ww

w.n

eevi

aPDF.

com

Page 418: Java_Comb

Font f;Thread t = null;

//Set colors and initialize thread

public void init(){

setBackground (Color.cyan);setForeground (Color.red);f=new Font (“Courier”, Font.PLAIN, 12);

//Create space for fontsetFont (f); //set new font.t = new Thread (this); //create new threadt.start(); //start thread runningt.suspend();

//Suspend until applet fully initialized//this is the old suspend method now//deprecated.

}

public void start(){

String param;msg = getParameter (“message”);if (msg == null) msg = “Message not

found.”;msg = “ ”+ msg + “ ”;

fN = getParameter (“fontName”);if (fN == null )

CKR Java Notes 145

ww

w.n

eevi

aPDF.

com

Page 419: Java_Comb

fN = “Courier”;

param = getParameter (“fontSize”);try{

if (param!= null ) fS = Integer.parseInt (param);else fS = 12;

} catch (NumberFormatException e) {

fS = -1; }

f = new Font (fN, Font.PLAIN, fS);setFont (f);t.resume();

}

//Entry point for the thread that runs thebanner.

public void run(){

char ch;

//Displays banner until stopped

for (; ; ){

try

CKR Java Notes 146

ww

w.n

eevi

aPDF.

com

Page 420: Java_Comb

{repaint();Thread.sleep (500);ch = msg.charAt(0);msg = msg.substring (1, msg.length());msg += ch;

} catch (InterruptedException e){

}

}}

//Pause the Banner

public void stop(){

t.suspend();}r

//Kill thread when applet is terminated

public void destroy(){

if (t != null){

t.stop();t = null;

}

CKR Java Notes 147

ww

w.n

eevi

aPDF.

com

Page 421: Java_Comb

}

//Display the banner

public void paint (Graphics screen){

screen.drawString (msg, 50, 30);}

}

CKR Java Notes 148

ww

w.n

eevi

aPDF.

com

Page 422: Java_Comb

Thread priorities

• Threads can have different priorities on a scaleof 1-10.

• The average thread has a priority of 5.

• Technically, the priority scale ranges fromMIN_PRIORITY to MAX_PRIORITY, whichnumbers are currently 1 and 10 respectively.

– The average priority is defined by thenumber NORM_PRIORITY.

– These numbers are defined as finalvariables in the Thread class

• When a thread is created, its priority is set equalto the priority of the thread which created it.

• Thread priority may be determined or changedusing the methods

final void setPriority ( int P_level)final int getPriority ()

– p_level must be an int in the priorityscale of 1-10.

– The actual priority set will the minimumof p_level and the priority of the callingthread.

CKR Java Notes 149

ww

w.n

eevi

aPDF.

com

Page 423: Java_Comb

Thread priorities (contd)

• Thread priorities only provide a rough indicationof how much time the thread will get.

• The same priority thread may get differentamount of time slices from run to run.

• These considerations are demonstrate by thefollowing example program.

class Ticker implements Runnable{

int tick = 0;Thread t; private volatile boolean isRunning = true;

//define constructorpublic Ticker (int p_level){

t = new Thread (this);t.setPriority(p_level);

}

public void run(){

while (isRunning){

tick++;}

CKR Java Notes 150

ww

w.n

eevi

aPDF.

com

Page 424: Java_Comb

}

public void stop(){

isRunning = false;}

public void start(){

t.start();}

}

public class Priority{

public static void main(String args[]){

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

Ticker high = new Ticker(Thread.NORM_PRIORITY + 2);

Ticker low = new Ticker(Thread.NORM_PRIORITY - 2);

high.start(); //call to thread.start()low.start(); //JVM will call run()

try{

Thread.sleep (5000);

Entry set Wait set

The owner

CKR Java Notes 151

ww

w.n

eevi

aPDF.

com

Page 425: Java_Comb

/*causes the thread to sleep (ceaseexecution)

for the specified number of milliseconds*/} catch(InterruptedException e)/*Derived from Exception */{

System.out.println("Main threadinterrupted");

}int pLow = low.t.getPriority();int pHigh = high.t.getPriority();low.stop();high.stop();

try { /*wait for other threads to end*/

high.t.join();low.t.join();

} catch(InterruptedException e){}System.out.println(pLow + " priority

thread got: " + low.tick + " clock ticks");System.out.println (pHigh + " priority

thread got: " + high.tick + " clockticks");

}}

• Output: varies from run to run.

CKR Java Notes 152

ww

w.n

eevi

aPDF.

com

Page 426: Java_Comb

CKR Java Notes 153

ww

w.n

eevi

aPDF.

com

Page 427: Java_Comb

Thread synchronization

• Since it is not clear when the system will switchfrom executing one thread to executing another,various peculiarities may arise.

• Race conditions: Different threads may allmanipulate the same object, and may race tofinish execution.

• To avoid this, Java has a synchronizedstatement.

synchronized (objectref) { /*Synchronizedblock*/ }

• Java’s synchronization model uses monitors tosupport two kinds of thread synchronization.

– mutual exclusion– cooperation

• Cooperation is achieved through inter-threadcommunication, using the

– wait(), and– notify()– notifyall()

methods of Object, implemented as final methods.

– These methods can be called only withina synchronized block.

• Mutual exclusion is achieved through locksimposed by the JVM.

CKR Java Notes 154

ww

w.n

eevi

aPDF.

com

Page 428: Java_Comb

Thread synchronization (contd)

• A monitor is like – a building– which has a a special room (toilet?)

Only one person can use the special room at a time.

• From the time the thread enters the specialroom to the time it leaves the special room, it hasexclusive access to the data in the room.

• Entering the building is called “entering themonitor”.

• Entering the special room is called “acquiringthe monitor”.

• Occupying the special room is called “owningthe monitor”.

• Leaving the special room is called “releasing themonitor”.

• Leaving the entire building is called “exiting themonitor”.

• A monitor is also associated with a bit of codecalled a monitor region.

– A monitor region is a code that isexecuted as one indivisible operation.

CKR Java Notes 155

ww

w.n

eevi

aPDF.

com

Page 429: Java_Comb

Thread synchronization (contd)

• When one thread is executing a monitor region,associated with a given monitor, no other threadcan execute any part of that region.

• A thread can only enter a monitor by arriving atthe beginning of a monitor region, associatedwith that monitor.

• At this point the thread is placed in the entry setfor the associated monitor.

• The only way a thread can move forward andexecute the monitor region is by acquiring themonitor.

• If the monitor is not owned by any other thread,the thread can acquire the monitor, execute themonitor region, exit and release the monitor.

• If the monitor is currently owned by anotherthread the given thread must wait, until thatmonitor is released.

• After that, it must compete with any otherthreads also waiting in the entry set.

• Only one thread form the entry set will win thecompetition and acquire the monitor.

CKR Java Notes 156

ww

w.n

eevi

aPDF.

com

Page 430: Java_Comb

• While exclusion keeps threads from interferingwith one another, cooperation helps the threadsto work towards a common goal.

– e.g. a "read" thread which is readingdata from a buffer filled by a "write"thread.

Enter

Acquire

Release

Acquire

Release &Exit

Waiting thread

Active thread

CKR Java Notes 157

ww

w.n

eevi

aPDF.

com

Page 431: Java_Comb

Thread synchronization (contd)

• The JVM uses a "wait and notify" model ofcooperation.

• A thread that currently owns a monitorvoluntarily relinquishes it by executing a wait()command.

• The thread will stay suspended, in the wait set,until after another thread executes a notifycommand.

• The thread issuing the notify commandcontinues to own the monitor, until it releasesthe monitor of its own accord.

• A waiting thread can optionally issue a timeoutto the JVM.

• At the end of the timeout, even if no other threadnotifies it, it will be automatically resurrected bya notify message from the JVM.

• JVM implementers are free to make FIFO or LIFOqueues or some more complex orderings todecide which of the waiting threads will acquirethe monitor.

• Thus, e.g. use notifyall() rather than notify() forthere may be more than one thread waiting.

CKR Java Notes 158

ww

w.n

eevi

aPDF.

com

Page 432: Java_Comb

Thread synchronization (contd.)

• The JVM coordinates multithreaded access totwo kinds of data:

– Instance variables – Class variable

• The JVM does NOT coordinate access to local

variables which reside on the stack and areprivate to the thread to which the stack belongs.

• Every object and every class is associated with amonitor.

– For classes, the monitor protects theclass variables.

– For objects, the monitor protects theinstance variables.

• To implement mutual exclusion, the JVMassociates a lock with each object and class.

• A single thread is permitted to lock an object anynumber of times.

– In that case the object must be unlockedas many times for it to be released.

• Programmers however need be concerned onlywith the synchronized statement.

CKR Java Notes 159

ww

w.n

eevi

aPDF.

com

Page 433: Java_Comb

• These considerations are illustrated by thefollowing sample program .

/*Aim: To illustrate the asynchronous operation of threads. One thread attempts to update data in the same object from which another threadis trying to retrieve data. This mayresult in garbled output, which variesfrom run to run. */ class Student{

String name;//class Student has two dataint marks; //members which can be updated

//or printed.

Student (String n, int m) {

name = n;marks = m;

}

void Update (String n, int m){

name = n;/*after doing the above supposethe thread is descheduled. To simulate this, we artificially

CKR Java Notes 160

ww

w.n

eevi

aPDF.

com

Page 434: Java_Comb

put the thread to sleep. */try{

Thread.sleep (1000); } catch (InterruptedException e){}/*The thread now resumes*/marks = m;

}

void Print () {

System.out.println ( name);/*after doing the above supposethe thread is descheduled. To simulate this, we artificially put the thread to sleep. */try{

Thread.sleep (1000); } catch (InterruptedException e){}/*The thread now resumes*/System.out.println (" " + marks);

}}

class Interact implements Runnable

{

CKR Java Notes 161

ww

w.n

eevi

aPDF.

com

Page 435: Java_Comb

Student s; Thread t;int iType;int newMarks = 0;String newName;Interact (Student std, int i) //define

constructor{

s = std;iType = i;newName=" ";t = new Thread (this);t.start();

}

Interact (Student std, int i, String str,int m)

{ //define a second construtors = std;iType = i;newName = str;newMarks = m;

t = new Thread (this); t.start();

}

CKR Java Notes 162

ww

w.n

eevi

aPDF.

com

Page 436: Java_Comb

public void run(){ //either update or print

switch (iType){

case 1: s.Print();break;

case 2: s.Update (newName, newMarks);break;

default: break;}

}}

public class Async{

public static void main(String args[]){

Student s = new Student ("Ram" , 40);Interact i1 =new Interact (s, 2, "Shyam",

50);Interact i2 = new Interact (s, 1);try{ //wait for threads to finish

i1.t.join();i2.t.join();

} catch (InterruptedException e){}

}}

CKR Java Notes 163

ww

w.n

eevi

aPDF.

com

Page 437: Java_Comb

/*Possible output: Shyam40

Note: Output may vary from run to run*/

• Only two changes are needed in the precedingprogram.

• The method run should be synchronized on thestudent object, as follows.

• 1. Change the run function

public void run(){

synchronized (s) { switch (iType) { //... } } }• 2. Change the name of the class to SyncAsync

• In this case the output is not jumbled up.

• 3. To experiment further, change the threadpriorities, as in the following sample program.

•/*Aim: To illustrate how threads may be synchronized. In the earlier codeAsync.java

CKR Java Notes 164

ww

w.n

eevi

aPDF.

com

Page 438: Java_Comb

one thread attempted to update data in the same object from which another threadwas trying to retrieve data. This sometimesresulted in garbled output, which variedfrom run to run. The present code changesthis by using synchronization. The earliercodeis changed in just two places*/ class Student{

String name;//class Student has two dataint marks; //members which can be updated

//or printed.

Student (String n, int m) {

name = n;marks = m;

}

void Update (String n, int m){

name = n;/*after doing the above supposethe thread is descheduled. To simulate this, we artificially put the thread to sleep. */try{

CKR Java Notes 165

ww

w.n

eevi

aPDF.

com

Page 439: Java_Comb

Thread.sleep (1000); } catch (InterruptedException e){}/*The thread now resumes*/marks = m;

}

void Print () {

System.out.println ( name);/*after doing the above supposethe thread is descheduled. To simulate this, we artificially put the thread to sleep. */try{

Thread.sleep (1000); } catch (InterruptedException e){}/*The thread now resumes*/System.out.println (" " + marks);

}}

class Interact implements Runnable

{Student s; Thread t;int iType;

CKR Java Notes 166

ww

w.n

eevi

aPDF.

com

Page 440: Java_Comb

int newMarks = 0;String newName;Interact (Student std, int i) //define

constructor{

s = std;iType = i;newName=" ";t = new Thread (this);t.setPriority (4);t.start();

}

Interact (Student std, int i, String str,int m)

{ //define a second construtors = std;iType = i;newName = str;newMarks = m;

t = new Thread (this); t.setPriority(1); t.start();

}

public void run(){ //either update or printsynchronized (s) /*1. operation on s is

synchronized*/

CKR Java Notes 167

ww

w.n

eevi

aPDF.

com

Page 441: Java_Comb

{switch (iType){

case 1: s.Print();break;

case 2: s.Update (newName, newMarks);break;

default: break;}

}}

}

public class SyncAsync /*2. Name of theclass is changed*/{

public static void main(String args[]){

Student s = new Student ("Ram" , 40);Interact i1 =new Interact (s, 2, "Shyam",

50);Interact i2 = new Interact (s, 1);try{ //wait for threads to finish

i1.t.join();i2.t.join();

} catch (InterruptedException e){}}

}

CKR Java Notes 168

ww

w.n

eevi

aPDF.

com

Page 442: Java_Comb

• Output: Ram 40

• Note: Output may vary from run to run, and withthread priorities, but the output will be eitherRam 40 or Shyam 50.

CKR Java Notes 169

ww

w.n

eevi

aPDF.

com

Page 443: Java_Comb

i/0: Streams and Files in C

• We recollect that C uses the two abstractions – streams, and– files

• C was developed in the context of Unix, and inUnix everything is a file: console, keyboard, diskfiles, tape drives etc.

• A stream provides a level of abstraction betweenthe programmer and the physical device, viz. file.(i.e., represented by the file abstraction).

• There are two kinds of streams– text streams– binary streams

• A text stream is a sequence of characters. – text streams are organized into lines

separated by the newline character.

– in a text stream certain charactertranslations may occur as required bythe host environment, e.g.

– a newline may be converted to a carriagereturn/linefeed pair on a printer.

CKR Java Notes 170

ww

w.n

eevi

aPDF.

com

Page 444: Java_Comb

– Thus, there is NOT a on-to-onerelationship between the characters thatare read (or written) to a text stream, andthe characters stored on the externaldevice.

• A binary stream is a sequence of bytes– no character translations are permitted

in a binary stream.

• Hence in a binary stream there is a one to onecorrespondence between

– the characters written to the stream, and

– the characters stored in the externaldevice.

– However, an implementation dependentnumber of null bytes may be appendedto the end of a binary stream, to fill upthe sectors on a disk, for example.

• Correspondingly there are two types of files

– text files, and

– binary files

CKR Java Notes 171

ww

w.n

eevi

aPDF.

com

Page 445: Java_Comb

• A file may be any device– a terminal– a keyboard– a printer

• Streams are associated with files by performingan open operation.

• Streams are dissociated with files by performinga close operation.

• While all streams are the same, all files are not. – A disk file can support random access.– A printer typically cannot.

• Certain types of files (e.g. disk files) may supportposition requests

– Opening such a file also initializes thefile position indicator to the beginning ofthe file.

• Files are represented in a C program by a FILEstructure.

– A FILE * variable is called a file pointer. • Streams may contain a buffer, which stores

characters before they are actually written to afile.

– Such buffers improve execution speed. – writing the buffer is called flushing.

CKR Java Notes 172

ww

w.n

eevi

aPDF.

com

Page 446: Java_Comb

C-style i/o: standard streams

• Whenever a program starts, it usually needs tobe able to

– input data from the keyboard– output data to the screen– inform the user of some error conditions.

• Accordingly, three predefined streams areavailable, to any program

– stdin (keyboard)– stdout (screen)– stderr (screen)

• stdin is the standard input device, usuallyconnected to the keyboard.

– remember this is a file which has to beopened.

– The availability of this predefined streammeans that the programmer does nothave to do this manually,.

– however, input may be redirected andtaken from a disk file, using <

myprogram < myfile– This may be achieved since the

programmer is dealing with anabstraction.

CKR Java Notes 173

ww

w.n

eevi

aPDF.

com

Page 447: Java_Comb

C-style i/o (contd)

• stdout is the standard output device, usually thescreen

– however, output may be redirected to adisk file using >

myprogram > myfile

• stderr is usually the screen.

• File i/o is not fundamentally different fromconsole i/o.

• The only difference is that a file pointer must beavailable for file i/o.

• This file pointer can be obtained by means of afile open call as in the program above, using theopen function, and

– supplying a file name– supplying an open mode

FILE * DataFile = fopen(szFileName,szMode);

• The open mode can be– r (read)– w (write)– a (append)– rb (open binary file for reading) etc.

CKR Java Notes 174

ww

w.n

eevi

aPDF.

com

Page 448: Java_Comb

C file i/o

• One difference between console i/o and file i/o isthat diskfiles support random access i/o, andhence indicate position in the file.

• This is accomplished by using the function fseekwhich has the prototype

int fseek (FILE *fp, long numbytes, intwhence);

• The fseek function takes three parameters– FILE *fp (the file pointer returned by the

call to fopen

– numbytes indicates the number of bytesto move

– whence is the position indicator, andcould be

– SEEK_SET (0) Beginning of file– SEEK_CUR (1) Current position– SEEK_END (2) End of file.

• To seek the nth item of a data which setnumbytes to n*sizeof(datatype) in a binary file.

• stdout can be internally redirected by using freopen(const char* filename, , constchar* mode, FILE *stream)

CKR Java Notes 175

ww

w.n

eevi

aPDF.

com

Page 449: Java_Comb

• 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, oneuses the function ftell(), which has the prototype

long ftell (FILE *fp);

• For formatted file i/o one uses the functions– fprintf() – fscanf()

• In addition to – console i/o, and– file i/o

C supports a third form of i/o• character array based i/o

– where reading and writing can be doneto a character array in memory.

– this uses the family of functionsbeginning with s, e.g.

– sprintf– sscanf– etc.

CKR Java Notes 176

ww

w.n

eevi

aPDF.

com

Page 450: Java_Comb

i/o (contd.) : Difference between text and binary streams

• The following example demonstrates some ofthese concepts.

Program 32/* TXTFILE.c * This program demonstrates how text and* binary files * differ */

#include <stdio.h>#include <string.h> /* For string functions */#include <conio.h> /* For console getch(), getche(), etc. */#include <ctype.h> /*Forcharacter-conversion functions tolower() */

#define MAX_LINES 25#define MAX_LENGTH 80

char szSaying[MAX_LINES][MAX_LENGTH] = { /*ALL strings below should be coded to fit intoone line AND padded to cover 64 characters*/“\nFirestone’s Law of Forecasting: \n",“\n Chicken Little has to be right only once. \n”,“\n\n\n”,“\nManly’s Maxim:\n”,“\n Logic is a systematic method of coming to \n”,

CKR Java Notes 177

ww

w.n

eevi

aPDF.

com

Page 451: Java_Comb

“\n the wrong conclusion with confidence. \n”,“\n\n\n”,

“\nMoer’s truism:\n”,“\n The trouble with most jobs is the job holder’s\n”,“\n resemblance to being one of a sled dog team. Noone \n”,“\n gets a change of scenery except the lead dog.\n”,“\n\n\n”,“\nCannon’s Comment:\n”,“\n If you tell the boss you were late for workbecause you \n”,“\n had a flat tire, the next morning you will have aflat tire.\n”,“\n\n\n”, };

int main(void);

int main()

{

FILE *DataFile = NULL;

char szFileName[25]; /*string to hold filename*/

CKR Java Notes 178

ww

w.n

eevi

aPDF.

com

Page 452: Java_Comb

char szMode[5] = “w\0\0"; /*to hold file mode*/

int i;int nNumberRecords = 0;int nRecord = 0;int nResult = 0;r

long lNewPosition = 0;long lOldPosition = 0;

/* Prompt the user to supply the mode,* either lowercase t

* for a text file or lowercase b for a * binary file.

*/

while (DataFile == NULL) {

while(szMode[1] != ’b’ && szMode[1] != ’t’) {

printf(”\nEnter ’t’ for text file, "’b’ for binary: “);

szMode[1] = tolower(getche()); }

printf(”\nEnter the name of file to write: “); gets(szFileName);

if ((DataFile = fopen(szFileName,

CKR Java Notes 179

ww

w.n

eevi

aPDF.

com

Page 453: Java_Comb

szMode))==NULL) {printf(”\n ERROR: opening file ’%s’.\n",

szFileName); } }

printf(“\n”);switch(szMode[1]) { case ’t’:

printf(“This is a text file\n\n”); break;

case ’b’:printf(“This is a binary file\n\n”);

break; }

for (i = 0; strlen(szSaying[i]); i++) {

lOldPosition = ftell(DataFile); /*store current file position*/

fwrite(szSaying[i],/*Saying number to write*/

strlen(szSaying[i]), /*size (in bytes) to write*/

1, /*No of items of above size to write*/DataFile); /*where to write*/

CKR Java Notes 180

ww

w.n

eevi

aPDF.

com

Page 454: Java_Comb

lNewPosition = ftell(DataFile); /*get new file position*/

printf( “Start position %5ld ” “end %5ld, ” “strlen(...) %d but ” “wrote %5ld bytes’\n”,

lOldPosition, /*start position*/lNewPosition, /*end position*/strlen(szSaying[i]), /*string length*/(long)lNewPosition - lOldPosition); /*file

position change*/ }

fclose(DataFile);

printf(“\n”);

switch(szMode[1]) { case ’t’:

printf(“Note the bytes written do NOT”“ equal the string length\n\n”);

break;

case ’b’:printf(“Note the bytes written DO”“ equal the string length\n\n”);

break;

CKR Java Notes 181

ww

w.n

eevi

aPDF.

com

Page 455: Java_Comb

}getch();

return (0);}

• Input: t• output: Bytes written do not match string length

• Input b• Output: Bytes written match string length

CKR Java Notes 182

ww

w.n

eevi

aPDF.

com

Page 456: Java_Comb

Java i/o

• Java i/o resembles C i/o.

• The key difference is that Java is designed to becompletely object-oriented, so that

– Java i/o is object oriented.

• This is achieved through wrapper classes.

• Wrapper classes have been created for– streams– files– data types

• This has the effect of making Java i/o somewhatcomplicated.

– This complication may be unavoidable, ifthe aim is to have platformindependence rather than merelyportability.

• Java i/o is internally byte-oriented.

• However, classes are provided to supportcharacter streams.

CKR Java Notes 183

ww

w.n

eevi

aPDF.

com

Page 457: Java_Comb

Predefined Streams

• The three standard predefined streams of C – stdin– stdout– stderr

• are available in Java as the three members of thestatic System class

– in– out– err

• The System class cannot be instantiated since ithas a private constructor.

• However, it is a static class, so we can refer to itsmembers simply by using the class name.

• Thus, instead of stdin, stdout, stderr werespectively use

– System.in– System.out– System.err

CKR Java Notes 184

ww

w.n

eevi

aPDF.

com

Page 458: Java_Comb

Byte and Character i/o

• In C there are two types of streams– binary– character

• Correspondingly, Java has two types of i/oclasses

– byte oriented i/o classes– character-oriented i/o classes

• Additional complications are introduced by theneed for

– Unicode characters– platform independence

• The byte-stream oriented class hierarchy beginswith two abstract classes

– InputStream– OutputStream

• The character-stream oriented class hierarchyalso begins with two abstract classes

– Reader– Writer

• These classes define basic methods such asread() and write().

CKR Java Notes 185

ww

w.n

eevi

aPDF.

com

Page 459: Java_Comb

Java Character i/o: Input

• Since Reader and Writer are abstract classes, weneed to use subclasses which implement all theirmethods.

• To Read a character we need to use the classInputStreamReader

• The InputStreamReader class converts bytes tocharacters.

• However, since i/o access is time-consuming, toimprove efficiency, we should use theInputStreamReader class in combination with aclass which provides a buffer. Such a class isthe class

BufferedReader

• The BufferedReader class is a direct subclass ofReader. It has two constructors

BufferedReader (Reader in)BufferedReader (Reader in, int buff_size)

• Since Reader is an abstract class, we cannotinstantiate it. So how do we get a reference to aReader type ?

CKR Java Notes 186

ww

w.n

eevi

aPDF.

com

Page 460: Java_Comb

• To get a reference to a Reader type, we use, theInputStreamReader, which is also a directsubclass of the class Reader.

– Hence an object of typeInputStreamReader can be used as areference to a Reader type.

• The InputStreamReader has two constructors:InputStreamReader (InputStream in)InputStreamReader (InputStream in,

String encoding)

• The second construtor specifies the name of thecharacter encoding to be used.

• For the default encoding, we use only the firstconstructor.

• Since InputStream is also an abstract class, howdo we get a reference to an InputStream type?

• For this we can use– either a concrete subclass of

InputStream, or – System.in (which is a reference of type

InputStream)

CKR Java Notes 187

ww

w.n

eevi

aPDF.

com

Page 461: Java_Comb

Reading a character

• With all this wrapping, we can finally read asingle character using Java!

• Step 1: Create a new BufferedReader

BufferedReader br = new BufferedReader(new InputStreamReader (System.in) );

• Step 2: Read a character using the newly createdbr object and the read() method of theBufferedReader class.

– One form of read() reads a singlecharacter, and returns an int.

– This int must be typecast to char.

char c = (char) br.read();

• We can check the input, by printing it, using acall to the println() method of the System class.

System.out.println(c);

• Note: Unlike the getch() function, and like thegetchar() function, since System.in is linebuffered, no input is actually passed to it, until acarriage return is pressed. The call to println()places a carriage return and flushes the buffers.

CKR Java Notes 188

ww

w.n

eevi

aPDF.

com

Page 462: Java_Comb

Reading a string

• To read an entire string, use the readln() methodof the BufferedReader class.

– The readln() method throws anIOException (which is a checkedexception).

• To adjust the efficiency manually, we canexplicitly specify the size of the buffer, by usingthe second form of the constructor

BufferedReader(Reader in , int buff_size);

Output to console

• For output to console, we have been using theout member of the System class.

• The out and err members are of typePrintStream.

– PrintStream is a character-based outputclass.

– It converts its byte- arguments to 8-bitASCII Representations.

– The constructor for this class isdeprecated in JDK 1.2

– Thus, one should avoid constructingnew PrintStream objects.

CKR Java Notes 189

ww

w.n

eevi

aPDF.

com

Page 463: Java_Comb

Output to Console

• The alternative is to use the PrintWriter class,which directly subclasses Writer, and convertsits arguments to 16-bit Unicode representation.

• The Printwriter class supports output for allprimitive data types (and even Object), and it canbe used exactly like System.out.

• The constructor for Printwriter requires areference to either

– OutputStream, or– Writer

• In addition, a second boolean parameter may besupplied . If set to true, this will flush buffers on acall to a println() method.

• E.g.PrintWriter (OutputStream out, booleanflush);

• Since PrintStream is a subclass ofOutputStream, we can use the System.out fora reference to OutputStream.

• Note: In PrintWriter, unlike PrintStream, thebuffer will NOT be flushed on newline, but onlyon use of a println method.

– Error in Java 2 Complete Reference, p323.

CKR Java Notes 190

ww

w.n

eevi

aPDF.

com

Page 464: Java_Comb

• These considerations are illustrated by thefollowing program.

Program 33

//java i/o supports both byte and char//streams, though the i/o is primarily//byte based. //character streams are supported by the//abstract Reader class //which has a concrete subclass//InputStreamReader //and BufferedReader //Output is preferably done via the//PrintWriter class rather than a //call to System

import java.io.*; public class TestIO { public static void main (String args[])

throws IOException { //Creating a BufferedReader object

BufferedReader br = new BufferedReader(new InputStreamReader (System.in));

//Creating a PrintWriter object //The second parameter indicates whether

line //is to be flushed on encountering \nPrintWriter pw = new PrintWriter

(System.out, true); pw.println ("Enter a character: ’q’ to

CKR Java Notes 191

ww

w.n

eevi

aPDF.

com

Page 465: Java_Comb

quit"); char c;

do { c = (char) br.read(); pw.println (c);

} while (c !=’q’);//Reading a string

String str; pw.println ("Enter a line of text or data"); pw.println ("Enter ’end’ to quit"); do { str = br.readLine(); pw.println (str); } while (!str.equals ("end")); } }

• Input: abcdq• Output:

abcd

• Input: The quick brown fox ... end• Output:

The quick brown fox ...

CKR Java Notes 192

ww

w.n

eevi

aPDF.

com

Page 466: Java_Comb

File i/o

• We see that the Java philosophy is to separate – byte streams and – character streams

into two separate class hierarchies, starting from – InputStream, OutputSream– Reader, Writer

• Similarly, for stream-based file i/o, Java providestwo sets of classes.

– FileInputStream, FileOutputStream– FileReader, FileWriter

• All these classes have constructors which takethe filename (inclusive of full path) as a String

FileInputStream(String fileName) FileoutputStream (String fileName)FileReader (String fileName)FileWriter (String fileName)

• All the above constructors throw a FileNotFoundException, if the input file cannot be found or theoutput file cannot be created.

• If the output file exists it is overwritten. To avoidthis one can use the alternative constructors

FileOutputStream (String fileName, booleanappend)FileWriter (String fileName, booleanappend)

CKR Java Notes 193

ww

w.n

eevi

aPDF.

com

Page 467: Java_Comb

File i/o (contd)

Program 34

/*Java file i/o may be done using theclassesFileInputStream (String filename)FileOutputStream (String filename)FileOutputStream (String filename, booleanappend)all of which constructors throw aFileNotFoundException*/

import java.io.*;public class TestFileIO{

public static void main(String args[]) //throws IOException

{if (args.length <= 1){ System.out.println ("Usage: java TestFileIO fromFileName

toFileName");return;}

FileInputStream fin;FileOutputStream fout;

CKR Java Notes 194

ww

w.n

eevi

aPDF.

com

Page 468: Java_Comb

try{

fin = new FileInputStream (args[0]);} catch (FileNotFoundException e){System.out.println ("Input file not" +

"found");return;}

try{

fout = new FileOutputStream (args[1]);} catch (FileNotFoundException e) { System.out.println ("Error opening " +

"output file");return;} catch (IOException e){

System.out.println ("Error opening ""output file");

return;}int i;try{

do{

CKR Java Notes 195

ww

w.n

eevi

aPDF.

com

Page 469: Java_Comb

i = fin.read();if (i!=-1) //if not end of filefout.write (i);

/*Note: Only low-order 8 bits are writtenThus above code works for text or binary.*/

/* Print the same text to screen.*/} while (i!= -1);

} catch (IOException e){

System.out.println ("Error reading or" +"writing file");

//No return call here }finally {

try{fin.close();

fout.close();}catch (IOException e){

System.out.println ("Error closing files");}

}}

}

CKR Java Notes 196

ww

w.n

eevi

aPDF.

com

Page 470: Java_Comb

File i/o : Filename separators

• In the above example program, the filenameswere taken as parameters passed to the mainmethod.

• What if one wants to specify the filenameinternally.

• At this point the issue of platform independenceagain crops up.

– Unix uses / as a file name separator– DOS/Win use \ as a file name separator– C uses \ for escape characters (to

escape the ordinary meaning of acharacter, e.g. \n = newline)

– To print \ one must use \\ in C.

• Thus, the preferred method is to use / or use \\ tospecify the path.

• Java resolves this correctly, depending on thesystem.

• E.g. FileReader = new FileReader("C:\\mydir\\myfile.ext");

FileWriter = new FileWriter("C:\\mydir\\yourfile.ext", true);

CKR Java Notes 197

ww

w.n

eevi

aPDF.

com

Page 471: Java_Comb

File i/o : Random Access Files

• Finally, Java distinguishes completely betweenstreams and random access files which supportposition requests.

• Thus, Java defines a class calledRandomAccessFile

– which is NOT derived fromInputStream or OutputStream,

– but is derived directly from Object

public class RandomAccessFile extendsObject implements DataOutput DataInput

• DataInput and DataOutput are abstract interfaceswhich have methods to convert all of Javaprimitive data types from/to a sequence of bytes,and to read/write these to a binary stream .

• One constructor for this class isRandomAccessFile (String fileName, String

mode)

• Here mode must be either– "r" (for reading only) or– "rw" (both reading and writing)

• The constructor throws a FileNotFoundException, which is a subclass of IOException.

CKR Java Notes 198

ww

w.n

eevi

aPDF.

com

Page 472: Java_Comb

File i/o: Random Access Files (contd.)

• Additionally, the RandomAccessFileconstructors may throw the following Exceptions

• IllegalArgumentException if the mode isanything other than "r" or "rw".

• SecurityException if read/write permission forthe file is not available (e.g. in Unix systems)

• These exceptions are unchecked exceptions, sothe programmer is not obliged to bother aboutthem.

• A random access file is implicitly a large array ofbytes.

– The position in this implicit array is givenby the file pointer.

– To get the current position use themethod (instead of tell)

long getFilePointer();

– To set the current position use themethod

void seek (long pos);

• As already stated, various methods are availablefor reading and writing the primitive data types.

CKR Java Notes 199

ww

w.n

eevi

aPDF.

com

Page 473: Java_Comb

Program 35import java.io.*;

public class CompareFile{

public static void main (String args []) throws IOException

{String s1 = "Files differ in size by : "; String s2 = "Files differ at offset: : ";

/*Prepare initial string table */

if (args.length < 2){

System.out.println ("Usage: java CompareFile fromFileName "

+ "toFileName");return;}

RandomAccessFile fFrom = newRandomAccessFile (args[0], "r");

RandomAccessFile fTo = newRandomAccessFile (args [1], "r");

RandomAccessFile fRes = newRandomAccessFile ("c:\\kawa\\result",

"rw");

long fsize1 = fFrom.length();long fsize2 = fTo.length();

CKR Java Notes 200

ww

w.n

eevi

aPDF.

com

Page 474: Java_Comb

int bufsize = (int) Math.min (fsize1,fsize2);

int fmaxsize = (int) Math.max (fsize1,fsize2);

System.out.println ("bufsize = " +bufsize);

System.out.println ("fmaxsize = " +fmaxsize);

if (fsize1 != fsize2){

fRes.writeChars (s1);fRes.writeInt ((fmaxsize - bufsize));

}

byte buf1 [] = new byte [bufsize];byte buf2 [] = new byte [bufsize];

/*allocate buffers to hold files asbyte-arrays in memory */

fFrom.readFully (buf1, 0, bufsize);fTo.readFully (buf2, 0, bufsize);

/*args to readFully are buf, from, to */

CKR Java Notes 201

ww

w.n

eevi

aPDF.

com

Page 475: Java_Comb

for (int i=0; i bufsize; i++){

if (buf1 [i] != buf2 [i]){

fRes.writeChars (s2);fRes.writeInt (i);//fRes.writeChars (s3);

}}fFrom.close();fTo.close();

long fp = fRes.getFilePointer();System.out.println ("Length of result = "

+ fp);/*1*/fRes.seek((long)2*s1.length());fp = fRes.getFilePointer();System.out.println ("Currently at: "

+ fp); int i = fRes.readInt ();System.out.println (s1 + i);

fRes.close();}

}

• Note: /*1*/ : s1.length() returns the number ofcharacters in the string s, but for position weneed the number of bytes into the file, hence thefactor of 2.

CKR Java Notes 202

ww

w.n

eevi

aPDF.

com

Page 476: Java_Comb

File i/o: the File class

• Somewhat like the File structure in C, Java has aFile class.

• However, in Java, this class is used exclusively – to create files and directories, – to query and change their properties

• The File class does NOT incorporate anyread/write methods.

• As in Unix, a directory is simply a special type offile.

• The key issue is platform independence and thematter of the separator character: / or \

• To achieve this, Java uses the notion of anabstract pathname. While pathname strings aresystem dependent, abstract pathnames are not.

• An abstract pathname consists of – An optional prefix (such as / for root dir in

Unix or a drive specification– A sequence of zero or more String

names. • Each name, except the last must be a directory. • The last can be either a directory or a file.

CKR Java Notes 203

ww

w.n

eevi

aPDF.

com

Page 477: Java_Comb

File i/o: File class (contd)

• The File class has three constructors:

File (String pathname)File (File parent, String child)File (String parent, String child)

• It defines a variety of methods. All the followingreturn a boolean value.

– exists()– canRead()– canWrite()– isDirectory()– isFile()– isHidden()– isAbsolute()– delete()– setReadOnly– mkdir()

• The following method returns a URL– toURL() throws

MalformedURLException

• For various other methods consult thedocumentation.

• An example follows.

CKR Java Notes 204

ww

w.n

eevi

aPDF.

com

Page 478: Java_Comb

Program 36import java.io.*;

public class FileDemo{

public static void main (String args[]){

if (args.length < 1){System.out.println("Usage: FileDemo pathname/filename");return;}File f = new File (args[0]);

String s1 = f.exists() ? "Yes" : "No";String s2 = f.isFile() ? "Yes" : "No";String s3 = f.isDirectory ()? "yes" : "No";String s4 = f.canRead() ? "Yes" : "No";String s5 = f.isAbsolute() ? "Yes" : "No";

System.out.println ("Exists : "+s1);System.out.println("Is File : " + s2);System.out.println("Is Directory : " + s3);System.out.println("Can Read : " + s4);System.out.println("Is Absolute : " + s5);

}}

• Input: experiment

CKR Java Notes 205

ww

w.n

eevi

aPDF.

com

Page 479: Java_Comb

Numeric i/o:Type Wrapper classes

• apart from – character i/o and – byte i/o

Java implements a third type of – object i/o

which we shall not, however, examine here.

• The above i/o techniques still do not tell us howto read a numeric value, such as an int or float.

• 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:to read and write numbers one must first convertthem to strings.

• The programmer is expected to carry out theseconversions explicitly.

• To write a numeric value, we must first convert itto a string by concatenating using +

• To read a numeric value we must first read in astring and convert it to a numeric value by goingvia type-wrapper classes.

CKR Java Notes 206

ww

w.n

eevi

aPDF.

com

Page 480: Java_Comb

Numeric i/o and type-wrapper classes (contd)

• The type wrapper classes wrap the primitive typeinto classes, so that they can be treated asobjects.

• Some of the type wrapper classes are thefollowing (note the capitals)

– Byte– Short– Integer– Long– Float– Double

• All the above are derived by subclassing theabstract class

– Numberwhich subclasses Object.

• All the above types have constructors which takea string and return the wrapped object.

• Alternatively, one may use the static memberfunction

– valueOf(String str) for Float etc.– parseInt(String str) for Integer.

• Both the above methods may throw aNumberFormatException (which is derived from

CKR Java Notes 207

ww

w.n

eevi

aPDF.

com

Page 481: Java_Comb

RunTimeException and so is unchecked).

• All the above types have member functions– byteValue(), intValue(), floatValue() etc.

which return the equivalent primitive type.

• These considerations are illustrated by thefollowing program.

Program 37

/*This program illustrates how data typesmay be converted to and from stringsthis is a pre-requisite for i/o involvingprimitive datatypes.

For a language which claims to be simplei/o involving primitive data typesis remarkably complex in Java.

To convert from data type to string, use valueOf(double/float/int/long/char/char[]/boolean/Object/...) .of the String class

Note that the valueOf function of the Float class (or Number class) isdifferent. it returns a Float object. */

CKR Java Notes 208

ww

w.n

eevi

aPDF.

com

Page 482: Java_Comb

/* Summary:To read in an int, float etc. read in a string, convert the string to a wrapperclass, and then extract the data type fromthe wrapper class.

Step 1: Read in a string

Step 2: (String to Wrapper class) convert the string to a wrapper class by (a) passing the string to the constructor of that wrapper classor(b) use the valueOf static member functionof the corresponding class, for Float etc.and parseInt()for Integer.

Step 3: (Wrapper class to DataType) Extract the data type fromthe wrapper class by converting the wrapperclass to the data type using intValue()/floatValue()

CKR Java Notes 209

ww

w.n

eevi

aPDF.

com

Page 483: Java_Comb

etc. member functions (abstract functionsof the Number class).There is also a

booleanValue()

function ofthe Boolean class which subclasses Object.

II. Datatype to String. For the reverseprocess use either(a) concatenation with a string, using +, as in printlnor(b) convert datatype to a string, usingthe

valueOf (datatype)

function of the STRING class.

III. To convert Datatype to Wrapper class pass the datatype to the appropriate constructor of the Wrapperclass.

IV. Wrapper class to String: e.g. go via datatype */

CKR Java Notes 210

ww

w.n

eevi

aPDF.

com

Page 484: Java_Comb

import java.io.*;public class Convert{

public static void main (String args[]) throws IOException

{int myInt = 2;long myLong = 40000;float myFloat = 2.01f;double myDouble = 2.01;byte myByte = 1;boolean myBoolean = true;BufferedReader br = new BufferedReader

(new InputStreamReader (System.in));String str;

System.out.println ("Enter a line of text"+ "or data");

System.out.println ("Enter ’stop’ to" +"quit");

do {//Step 1: Read in string.

str = br.readLine();// System.out.println (str);

//Step 2: Convert the String to a //wrapper class.

try

CKR Java Notes 211

ww

w.n

eevi

aPDF.

com

Page 485: Java_Comb

{Integer myInteger = new Integer (str);

/*OrInteger myInteger = Integer.parseInt(str); */

//Step 3: Convert the wrapper class to intmyInt = myInteger.intValue();

//Step 4: Convert the int to a string to//print

System.out.println (" " + myInt);} catch (NumberFormatException e){

System.out.println ("Could not convertstring to Integer");

}

} while (!str.equals ("stop"));

}}

CKR Java Notes 212

ww

w.n

eevi

aPDF.

com

Page 486: Java_Comb

Servlets

• A servlet is to a server what an applet is to abrowser.

– A servlet may be almost thought of asan applet which runs on a web server.

• Formally, a servlet is a body of Java code thatruns inside a network service, such as a webserver.

• A servlet helps to build interactive web basedapplications

– by receiving and responding to requestsfrom clients.

• For example, a servlet may do the followingtasks.

• A servlet may process data POSTed by an HTTPclient, using an HTML form.

– Such a servlet might work together witha database and an online paymentsystem.

• A servlet can also forward requests to otherservers, to balance load between servers.

CKR Java Notes 213

ww

w.n

eevi

aPDF.

com

Page 487: Java_Comb

Servles (contd)

• Since a servlet can handle multiple requestsconcurrently, i.e., it is multi-threaded, it cansupport systems like online conferencing/chat.

• Since a servlet can dynamically generate HTTPresponses

– servlets serves as a replacement for CGI(Common Gateway Interface)scripts(server side scripting) used to generateweb pages dynamically.

• Servlets have some advantages over CGI

– CGI uses the process model: with CGI aseparate process is created for eachclient request.

– Servlets handle multiple client requestsusing a thread model: so performance isfaster.

– Full functionality of Java is available,including the security manager used toprotect resources on the server.

CKR Java Notes 214

ww

w.n

eevi

aPDF.

com

Page 488: Java_Comb

• Servlets work with the Servlet API.

– This is a standard Java extension API .

– Hence, unlike CGI, servlets may be runon different servers (which supportservlets) in a platform independent way.

– Many webservers support the servletAPI.

– These include Apache, iPlanet, andMicrosoft IIS.

– For a full list of third party products thatrun servlets, seehttp://java.sun.com/products/servlets/

– For examples of real life servletimplementations try

– ecampus.com, SiliconInvestor.com etc.

• Java has enhanced Servlet technology throughJava Server Pages: JSP, which serves as asubstitute for the proprietary ASP..

CKR Java Notes 215

ww

w.n

eevi

aPDF.

com

Page 489: Java_Comb

Servlets: initial preparations

• Preparations: To test and run servlets, one needs

– The Java servlet development kit, whichcontains the requisite class libraries.

– The servletrunner utility, which can beused to test servlets.

• Step 1: Download and install the Java servletdevelopment kit.

• Step 2: Update the CLASSPATH variable, toinclude the path where the servlet class librariesare installed. E.g.

setCLASSPATH=.;d:\jdk1.2.2\servlets\lib\jsdk.jar

• Step 3: Update the PATH variable to include thepath in which the servletrunner utility is located.E.g.

set PATH=%path%;d:\jdk1.2.2\servlets\bin

• We can now start writing the first servletprogram.

CKR Java Notes 216

ww

w.n

eevi

aPDF.

com

Page 490: Java_Comb

Servlet Lifecycle

• Servlet lifecycle: A servlet is– initialised– provides service– is destroyed (depending upon server on

which it is running)

• Correspondingly,writing a servlet involveswriting three key methods.

– init– service– destroy

• The init method is invoked exactly once foreach servlet.

• The service method is MULTITHREADED.– It is typically expected to concurrently

handle requests from multiple clients.

• The destroy method should– typically undo whatever initialization has

been performed, by closing files anddatabase connections.

– ensure that all service threads arecomplete before the servlet is destroyed.

CKR Java Notes 217

ww

w.n

eevi

aPDF.

com

Page 491: Java_Comb

Hello Servlet

• All servlets must implement the servlet interface– either directly– or by extending a class which

implements the interface.

• The HelloServlet class extends GenericServlet,which is a class which implements the Servletinterface.

Program 38

import java.io.*;import javax.servlet.*;

public class HelloServlet extendsGenericServlet{

public void service (ServletRequest rq,ServletResponse rp)

throws ServletException, IOException{

rp.setContentType ("text/html");PrintWriter pw = rp.getWriter();pw.println ("<B>Hello Servlet");pw.close();

}}

CKR Java Notes 218

ww

w.n

eevi

aPDF.

com

Page 492: Java_Comb

HelloServlet: Analysis of code

• The HelloServlet class implements only theservice method.

• The service method has the prototype

public void service (ServletRequest rq, ServletResponse rp);

• involving the public interfaces,

– Servlet Request and – ServletResponse

• These interfaces incorporate a number ofmethods for handling MIME (MultipurposeInternet Mail Extension) bodies.

• MIME bodies are either– text, or– binary data

• Correspondingly, one must– first get/set contentType

– then get an Input/OutputStream orReader and Writer

CKR Java Notes 219

ww

w.n

eevi

aPDF.

com

Page 493: Java_Comb

MIME types

S.No.

MIME type Origin

1 application/octet-stream Generic byte stream

2. application/pdfAdobe Acrobat portabledocument format files

3. application/postscript Postscript4. application/rtf Rich text format5. application/x-tex TeX6. text/plain .txt, .c, .cpp, .java, .h etc,7. text/html .htm, .html8. image/gif .gif9. image/jpeg JPEG

10. image/tiff TIFF11. video/mpeg .mpg

12. video/quicktime.mov or .qt AppleQuickTime files

13. video/x-sgi-movie .movie Silicon Graphics14. audio/basic .snd or .au sound clip15. audio/x-wav .wav file

• More info: RFC 2045/2046. (RFC = Request forComments. Many Internet standards are evolvedin this way. MIME is an evolving standard.

CKR Java Notes 220

ww

w.n

eevi

aPDF.

com

Page 494: Java_Comb

Hello Servlet: Analysis of code (contd)

• Thus, the HelloServlet class

– first set the MIME type to text/html, sincewe want to output HTML, and

– then gets a PrntWriter, using thegetWriter method provided by theServletResponse Interface

• The page to be generated can is now written instandard HTML

– More Info on HTML1.1: RFC2068http://infor.internet.isi.edu:80/in-notes/rfc/files/rfc2068.txt

• The HTML code to be generated can be ascomplex or as simple as we want.

– To generate this code we simply use thevarious methods available withPrintWriter, such as the println method.

– After completing the write, we close thestream through a call to the closemethod of PrintWriter.

CKR Java Notes 221

ww

w.n

eevi

aPDF.

com

Page 495: Java_Comb

HelloServlet: Testing the code

• Step 1: Compile the code as usual.

• (The javax package must be located so that itcan be found using the set CLASSPATH. Thedefault installation will put javax in the rightdirectory. )

• Step 2: Start servletrunner. – PATH and CLASSPATH should have

been set as described earlier.

– servletrunner invoked with -h willprovide help.

– servletrunner invoked with -d will set theservlet directory

servletrunner -d c:\java\kawa\

• Step 3: Start a webbrowser.

• Step 4: Request the servlet using the followingURL

http://localhost:80/servlet/HelloServletorhttp://127.0.0.1:8080/servlet/HelloServlet

• Output:Helloservlet in the browser.

CKR Java Notes 222

ww

w.n

eevi

aPDF.

com

Page 496: Java_Comb

Servlets (contd)

• An IOException may be thrown by the call to thegetWriter method.

• The ServletException indicates a servletproblem.

• The above servlet did not use the init or destroymethods.

• The destroy method has the prototype

public void destroy();

• The init method has the prototype

public void init (ServletConfig cfg)throws ServletException

• ServletConfig is a public interface, which definesvarious abstract methods like

getInitParameters( String name) getInitParameterNames()ServletContext getServletContext()

• ServletContext is an interface with varioususeful methods, which enable one to get theMIME type, server name, real path etc,, for whichcheck the documentation.

CKR Java Notes 223

ww

w.n

eevi

aPDF.

com

Page 497: Java_Comb

Servlet architecture (summary)

• Thus, servlets involve the following interfaces

• Servlet Interface– implemented by all servlets, directly or

indirectly– defines the three key public methods– void init (ServletConfig cfg)– void service (ServletRequest

rq, ServletResponse rp)– void destroy()

• ServletRequest Interface– passed as an argument to the service

method. – defines the

getInputStream() and getReader()

methods which return

– ServletInputStream, andBufferedReader objects, respectively.

– ServletInputStream extendsInputStream, and is used to handlebinary data.

CKR Java Notes 224

ww

w.n

eevi

aPDF.

com

Page 498: Java_Comb

• ServletResponse Interface– passed as an argument to the service

method

– defines the

getOutputStream(), andgetWriter()

– methods which returnServletOutputStream, andPrintWriterobjects, respectively.

– ServletOutputStream extendsOutputStream, and is used to handlebinary data.

• ServletConfig Interface and ServletContextInterface used to get various parametersassociated with the servlet.

• SingleThreadModel Interface– This interface has no constants or

methods. – A servlet implements this interface only

to indicate that the service method of theservlet can handle only one client at atime.

CKR Java Notes 225

ww

w.n

eevi

aPDF.

com

Page 499: Java_Comb

Servlets: initialization

• A servlet may be named, and initializationparameters may be provided for the servlet, inthe

– servlet.properties file

• The default location for this file is in– servlets\examples, – i.e., in .\examples relative to the directory

in which servletrunner starts– to set it some other location, use the -p

option with servletrunner

• The sample servlet.properties file, provided bySun, as part of the JDK, looks as follows (nextpage):

– This is self-explanatory. – # is used for comments– The name of the servlet may be

optionally set to something other than itsclass name through the line

servlet.<name>.code=codename (foo orfoo.class)

– the initial arguments may be provided by

servlet.name.initArgs=\pname1=pvalue1,\pname2=pvalue2

CKR Java Notes 226

ww

w.n

eevi

aPDF.

com

Page 500: Java_Comb

Sun’s sample servlet properties file

# @(#)servlets.properties 1.86 97/11/14## Servlets Properties## servlet.<name>.code=class name (foo or#foo.class)# servlet.<name>.initArgs=comma-delimited#list of {name, value} pairs# that can be accessed by the servlet#using the# servlet API calls#

# session servletservlet.session.code=SessionServlet

# simple servletservlet.simpleservlet.code=SimpleServlet

# snoop servletservlet.snoop.code=SnoopServlet

# survey servletservlet.survey.code=SurveyServletservlet.survey.initArgs=\

resultsDir=/tmp

CKR Java Notes 227

ww

w.n

eevi

aPDF.

com

Page 501: Java_Comb

Servlet initialization example

• These considerations are illustrated by thefollowing sample code.

Program 39import java.io.*;import javax.servlet.*;

public class GetProps extendsGenericServlet{

public void service (ServletRequest rq, ServletResponse rp)throws ServletException, IOException

{ServletConfig sc = getServletConfig();

//first set content typerp.setContentType ("text/html");

//then get i/o streamPrintWriter pw = rp.getWriter();pw.println ("<B>State = </B"> +

sc.getInitParameter("State") ) ;pw.println ("

<BR><B>City = </B>" + sc.getInitParameter("City") );

pw.close();}}

CKR Java Notes 228

ww

w.n

eevi

aPDF.

com

Page 502: Java_Comb

• Compile the code

• Add the following lines to the servlet.propertiesfile

#props servlet servlet.props.code=GetPropsservlet.props.initArgs=\

State=M.P.,\ City=Bhopal

• Start servletrunner utility (remember -d for the

servlet source files, and -p for the properties file)

• Open a webbrowser, and request the URL

http://localhost:8080/servlet/props

• Output: State=M.P.City=Bhopal

CKR Java Notes 229

ww

w.n

eevi

aPDF.

com

Page 503: Java_Comb

Servlets: More examples

• Instead of overriding the GenericServlet class, itis often more useful to override the HttpServletclass, which is specially adapted to http actions,with methods like

– doGet HTTP Get– doPost HTTP Post– doPut HTTP Put– doDelete HTTP Delete– doTrace HTTP Trace– doOptions HTTP Options– and– getLastModified

• In this case, the service method has theprototype

void service (HttpServletRequest rq,HttpServletResponse rp);

• The use of these functions is illustrated by thesample code given by Sun along with servlets.

• The following code reads a form, and writes theresults to file.

• The key issue is the question of synchronization:hence the method implements the single threadmodel.

CKR Java Notes 230

ww

w.n

eevi

aPDF.

com

Page 504: Java_Comb

• code in file JDcSurvey.html

<!DOCTYPE HTML PUBLIC "-//IETF//DTDHTML//EN">r<html> <head> <title>JdcSurvey</title> </head>

<body> <formaction=http://localhost:8080/servlet/survey method=POST> <input type=hidden name=surveyvalue=Survey01Results> <BR><BR>How Many Employees in yourCompany?<BR> <BR>1-100<input type=radioname=employee value=1-100> <BR>100-200<input type=radioname=employee value=100-200> <BR>200-300<input type=radioname=employee value=200-300> <BR>300-400<input type=radioname=employee value=300-400> <BR>500-more<input type=radioname=employee value=500-more> <BR><BR>General Comments?<BR> <BR><input type=text name=comment> <BR><BR>What IDEs do you use?<BR>

CKR Java Notes 231

ww

w.n

eevi

aPDF.

com

Page 505: Java_Comb

<BR>JavaWorkShop<inputtype=checkbox name=ide value=JavaWorkShop> <BR>J++<input type=checkboxname=ide value=J++> <BR>Cafe’<input type=checkboxname=ide value=Cafe’> <BR><BR><input type=submit><inputtype=reset> </form> </body></html>

CKR Java Notes 232

ww

w.n

eevi

aPDF.

com

Page 506: Java_Comb

/** @(#)SurveyServlet.java** Copyright (c) 1995-1997 SunMicrosystems, Inc. All Rights Reserved.**/import java.io.*;import java.util.*;

import javax.servlet.*;import javax.servlet.http.*;

/** * A sample single-threaded servlet thattakes input from a form * and writes it out to a file. It issingle threaded to serialize * access to the file. After the resultsare written to the file, * the servlet returns a "thank you" tothe user. * * <p>You can run the servlet as provided,and only one thread will run * a service method at a time. There areno thread synchronization * issues with this type of servlet, eventhough the service method * writes to a file. (Writing to a file

CKR Java Notes 233

ww

w.n

eevi

aPDF.

com

Page 507: Java_Comb

within a service method * requires synchronization in a typicalservlet.) * * <p>You can also run the servlet withoutusing the single thread * model by removing the<tt>implements</tt> statement. Because the * service method does not synchronizeaccess to the file, multiple * threads can write to it at the sametime. When multiple threads try * to write to the file concurrently, thedata from one survey does not * follow the data from another survey inan orderly fashion. * * <p>To see interaction (or lack ofinteraction) between threads, use * at least two browser windows and havethem access the servlet as * close to simultaneously as possible.Expect correct results (that * is, expect no interference betweenthreads) only when the servlet * implements the<code>SingleThreadedModel</code> interface. */

CKR Java Notes 234

ww

w.n

eevi

aPDF.

com

Page 508: Java_Comb

public class SurveyServlet extendsHttpServlet implements SingleThreadModel{ String resultsDir; public void init(ServletConfig config)

throws ServletException {

super.init(config); resultsDir =getInitParameter("resultsDir");

if (resultsDir == null) { Enumeration initParams =

getInitParameterNames(); System.err.println("The init

parameters were: "); while (initParams.hasMoreElements()) {

System.err.println(initParams.nextElement());

} System.err.println("Should have seen

one parameter name"); throw new UnavailableException (this,

"Not given a directory to write surveyresults!");

} }

CKR Java Notes 235

ww

w.n

eevi

aPDF.

com

Page 509: Java_Comb

/** * Write survey results to output filein response to the POSTed * form. Write a "thank you" to theclient. */ public void doPost(HttpServletRequestreq, HttpServletResponse res)

throws ServletException, IOException { // first, set the "content type"header of the response

res.setContentType("text/html");

//Get the response’s PrintWriter to returntext to the client. PrintWriter toClient =res.getWriter();

try { //Open the file for writingthe survey results. String surveyName =req.getParameterValues("survey")[0]; FileWriter resultsFile = newFileWriter(resultsDir

+System.getProperty("file.separator")

+ surveyName + ".txt", true); PrintWriter toFile = new

CKR Java Notes 236

ww

w.n

eevi

aPDF.

com

Page 510: Java_Comb

PrintWriter(resultsFile);

// Get client’s form data & store itin the file toFile.println("<BEGIN>"); Enumeration values =req.getParameterNames();

while(values.hasMoreElements()) { String name =(String)values.nextElement();

String value =req.getParameterValues(name)[0];

if(name.compareTo("submit") != 0) { toFile.println(name +": " + value); } } toFile.println("<END>");

//Close the file. resultsFile.close();

// Respond to client with a thank you toClient.println("<html>"); toClient.println("<title>Thank

you!</title>"); toClient.println("Thank youfor participating");

CKR Java Notes 237

ww

w.n

eevi

aPDF.

com

Page 511: Java_Comb

toClient.println("</html>");

} catch(IOException e) { e.printStackTrace(); toClient.println(

"A problem occured while recording youranswers. "

+ "Please try again."); }

// Close the writer; the responseis done.

toClient.close(); }}

CKR Java Notes 238

ww

w.n

eevi

aPDF.

com

Page 512: Java_Comb

Elements of Java GUI

• GUI programmingn is event-based.

• An event is a change of state in a source.

• A source of events can be– keyboard– mouse– internal state of the machine, such as a

clock, – a programme, when it completes some

job.

• Hence, GUI programming needs an event model .

• Java 1.0, 1.1 and 1.2 have used somewhatdifferent approaches.

• It is necessary to understand the earlierapproach, since

– most of the programmer’s time is spentin maintaining code, rather than indeveloping code.

• Legacy code uses the Java 1.0 model.

CKR Java Notes 239

ww

w.n

eevi

aPDF.

com

Page 513: Java_Comb

Java GUI elements

• The GUI elements such as– buttons– lists– icons– scroll panes– menus

• are all Windows.

• Java’s problem is to model these Windows in aplatform independent way.

• Java being object oriented, all these elementsare modeled using classes and objects.

• These elements are intuitively seen ascomponents put within a container.

– However, in Java the Component class isat the top of the awt hierarchy, andContainer is a subclass.

• Also, intuitively one tends to think of a Frame asa rectangular box, with nothing in it, and onethinks of a Window as something which has atitle, can be resized etc.

• This terminology is reversed in Java, withWindow being the rectangular box, and Frame

CKR Java Notes 240

ww

w.n

eevi

aPDF.

com

Page 514: Java_Comb

being a subclass with title bar etc.

• Applets are an important aspect of Java.

• Applets are subclasses of Panel, which is aconcrete implementation of the abstractContainer class.

Component

Container

Panel

Window

Frame

CKR Java Notes 241

ww

w.n

eevi

aPDF.

com

Page 515: Java_Comb

Java event models

• The key difference between the two eventmodels is this.

• In the 1.0 event model, the GUI elements werestacked hierarchically, and

– any event was despatched to allelements.

• A GUI element could handle the event if it sodesired, or it could ignore it.

• This method was found to be inefficient andtime-consuming.

• Accordingly, the 1.1 model adopts the usualMS-Windows technique:

• A GUI must notify all event sources, byregistering an event handler.

• Events are then despatched only to registeredhandlers.

• Such event handlers are called listeners

• The model is known as the Delegation EventModel.

CKR Java Notes 242

ww

w.n

eevi

aPDF.

com

Page 516: Java_Comb

– a user interface element is able todelegate the processing of events to aseparate piece of code.

• The source which generates the event sends toeach registered listener,

• Some events may not be handled by more than aspecified number of listeners.

– In this case registering an additionallistener leads to an exception.

• Like UI elements, Events too are modeled byclasses and objects.

• EventObject is the superclass of all events

• AWTEvent is the superclass of all AWT events.

• Various types of events are defined

– ActionEvent (when a button is pressed,or a list or menu item is selected)

– ItemEvent (when a checkbox or list itemis clicked, or a choice is made etc.)

– AdjustmentEvent (when a scroll bar ismanipulated)

CKR Java Notes 243

ww

w.n

eevi

aPDF.

com

Page 517: Java_Comb

– ComponentEvent (when a componentchanges its state and becomes visible oris hidden or moved or resized etc.)

– ContainerEvent (when a component isadded or removed from a container)

– KeyEvent (when input is received fromthe keyboard)

– MouseEvent (when the mouse is moved,or clicked, or dragged etc.)

– TextEvent (when the text in a TextField orTextArea is changed)

– WindowEvent (when a Window is closed,minimised etc.)

• Corresponding to this there are listenerinterfaces.

– ActionListener for ActionEvents– ItemListener for ItemEvents– AdjustmentListener for

AdjustmentEvents– ComponentLIstener– ContainerListener– KeyListener– MouseListener– TextListener, etc.

CKR Java Notes 244

ww

w.n

eevi

aPDF.

com

Page 518: Java_Comb

Java GUI (contd)

• These considerations are illustrated by thefollowing examples.

Program 40/*An applet illustrating the 1.0 eventmodel */

import java.applet.*;import java.awt.*;

public class SillyButton extends Applet{

public void init(){//add two buttons labeled red and blue

add (new Button ("Red")); add (new Button ("Blue"));

}

//older action method is deprecated

public boolean action (Event evt, Objectact)

{//check nature of eventif (!(evt.target instanceof Button)){

return false;

CKR Java Notes 245

ww

w.n

eevi

aPDF.

com

Page 519: Java_Comb

}

String btLabel = (String)act;if (btLabel == "Red"){

setBackground (Color.red);}else if (btLabel == "Blue"){

setBackground (Color.blue);}

repaint(); //show changed backgroundreturn true;

}}

CKR Java Notes 246

ww

w.n

eevi

aPDF.

com

Page 520: Java_Comb

Program 41/*This applet illustrates the revised Java1.1 event model which has been carriedover into Java 1.2 */

import java.applet.*;import java.awt.*;import java.awt.event.*;

class BackSet extends Objectimplements ActionListener

{Component cmp;Color clr;//define constructorBackSet(Component cmp, Color clr){

this.cmp = cmp;this.clr = clr;

}

public void actionPerformed (ActionEvent evt)

{cmp.setBackground (clr);cmp.repaint();

}}

CKR Java Notes 247

ww

w.n

eevi

aPDF.

com

Page 521: Java_Comb

public class SillyButton2extends Applet

{public void init()

{Button red = new Button ("Red");add (red);red.addActionListener (new BackSet (this, Color.red));

Button blue = new Button ("Blue");add (blue);blue.addActionListener(new BackSet (this, Color.blue));

}}

CKR Java Notes 248

ww

w.n

eevi

aPDF.

com

Page 522: Java_Comb

Choice

• The following program illustrates an appletwhich uses a choice. The choices are grouped tomake them mutually exclusive.

Program 42import java.applet.*;import java.awt.*;import java.awt.event.*;

public class SillyChoiceextends Applet

{static char ch=’B’;public void init(){

//create a choice menuChoice c = new Choice();

//add items to menuc.addItem ("Red");c.addItem ("Blue");c.addItem ("Green");

//mark one item as selectedc.select ("Blue");

//add choice to appletadd (c);

CKR Java Notes 249

ww

w.n

eevi

aPDF.

com

Page 523: Java_Comb

//create an ItemListener object

ItemListener l = new chkItemListener();

//add a listener interface to each//checkbox

c.addItemListener(l);

}

public void paint(Graphics g){

switch (ch){

case ’R’: setBackground (Color.red);break;

case ’B’: setBackground (Color.blue);break;

case ’G’: setBackground (Color.green);break;

default: break; } repaint();

}

}

//define an item listener

CKR Java Notes 250

ww

w.n

eevi

aPDF.

com

Page 524: Java_Comb

//ItemListener is an abstract interface//to implement which, one method must be//defined. //This method decides what is done when//a certain checkbox is selectedclass chkItemListener

implements ItemListener{

public void itemStateChanged (ItemEvent evt)

{

if (evt.getStateChange() == ItemEvent.SELECTED)

{Choice cb = (Choice)

evt.getItemSelectable();String sb = new String

(cb.getSelectedItem());SillyChoice.ch = sb.charAt (0);/*alternatively use int ch in place of

char chand use SillyChoice.ch=cb.getSelectedIndex()

0=Red, 1=Blue, 2=Green etc.*/

}} }

CKR Java Notes 251

ww

w.n

eevi

aPDF.

com

Page 525: Java_Comb

Check boxes and Radio buttons

/* Grouping checkboxes makes themradio buttons */ import java.applet.*;import java.awt.*;import java.awt.event.*;

public class SillyRadioextends Applet

{static char ch=’B’;public void init(){

//create a groupCheckboxGroup cbg = new CheckboxGroup();

//create checkboxes, state, to groupCheckbox cb1 = new Checkbox ("Red", false,

cbg);Checkbox cb2 = new Checkbox ("Blue", true,

cbg);Checkbox cb3 = new Checkbox ("Green",

false, cbg);

//add checkboxes to applet

CKR Java Notes 252

ww

w.n

eevi

aPDF.

com

Page 526: Java_Comb

add (cb1);add (cb2);add (cb3);

//create an ItemListener object

ItemListener l = new chkItemListener();

//add a listener interface to each//checkbox

cb1.addItemListener(l);cb2.addItemListener (l);cb3.addItemListener (l);

}

public void paint(Graphics g){

switch (ch){

case ’R’: setBackground (Color.red);break;

case ’B’: setBackground (Color.blue);break;

case ’G’: setBackground (Color.green);break;

default: break; } repaint();

}

CKR Java Notes 253

ww

w.n

eevi

aPDF.

com

Page 527: Java_Comb

}

//define an item listener//ItemListener is an abstract interface//to implement which, one method must be//defined. //This method decides what is done when//a certain checkbox is selectedclass chkItemListener

implements ItemListener{

public void itemStateChanged (ItemEvent evt)

{

if (evt.getStateChange() == ItemEvent.SELECTED)

{Checkbox cb = (Checkbox)

evt.getItemSelectable();String sb = new String (cb.getLabel());SillyRadio.ch = sb.charAt (0);

}}

}

CKR Java Notes 254

ww

w.n

eevi

aPDF.

com

Page 528: Java_Comb

Lists as applications

Program 43/*This runs as both an application and an applet*/ import java.applet.*;import java.awt.*;import java.awt.event.*;

class SillyListextends Applet

{static int ti;static int [] si = new int[3];List l;public void init(){

//create a List with 3 elements//permitting multiple selections //the default constructor does//not permit multiple selections

l = new List(3, true);

//add items to list//note that the function is add//not addItem//The addItem function still exists//but is deprecated

CKR Java Notes 255

ww

w.n

eevi

aPDF.

com

Page 529: Java_Comb

l.add ("Red");l.add ("Blue");l.add ("Green");

//mark two items as selectedl.select (1);l.select (0);

//if the list does not permit//multiple selections//then the second call //will de-select

//make a selected item visible l.makeVisible (1);

//add list to applet

add (l);

//create an ItemListener object

ItemListener ls = new chkItemListener();

//add a listener interface to each//checkbox

CKR Java Notes 256

ww

w.n

eevi

aPDF.

com

Page 530: Java_Comb

l.addItemListener(ls);

}

public void paint (Graphics g){

for (int i=0; i<= 3; i++)if (l.isIndexSelected(i) )

g.drawString ("Selected " + i, 10,30+20*i);

//repaint(); //don’t call this//resize the applet to force//repaint()

}}

//define an item listener//ItemListener is an abstract interface//to implement which, one method must be//defined. //This method decides what is done when//a certain list box item is selectedclass chkItemListener

implements ItemListener{

public void itemStateChanged

CKR Java Notes 257

ww

w.n

eevi

aPDF.

com

Page 531: Java_Comb

(ItemEvent evt){

if (evt.getStateChange() == p ItemEvent.SELECTED)

{List lb = (List) evt.getItemSelectable();//Note the plural in the next lineSillyList.si = lb.getSelectedIndexes();SillyList.ti =

lb.getSelectedIndexes().length;

}}

}

public class SillyListApplication{

public static void main (String args[]){

//create a Frame objectFrame f = new Frame ("Applet as an

application");

//create an applet objectSillyList sl = new SillyList();

//add applet to framef.add (sl);

CKR Java Notes 258

ww

w.n

eevi

aPDF.

com

Page 532: Java_Comb

//set size of frame andf.setSize (100, 120);

//make frame visiblef.show();

//call the applets methodssl.init();sl.start();

//add a listener to make the//windows close work//using an inner class

f.addWindowListener ( /*WindowListener is an abstract interface

whichextends EventListener. However we do not

wantto implement all methods in this

interface. Hencewe choose an Adapter class with empty

methodsand override the method of interest*/

new WindowAdapter(){ public void windowClosing (WindowEvent wevt){System.exit(0);

CKR Java Notes 259

ww

w.n

eevi

aPDF.

com

Page 533: Java_Comb

} //end of method def}//end of inner class def); //end of listener def

} //end of main} //end of SillyList class def

CKR Java Notes 260

ww

w.n

eevi

aPDF.

com

Page 534: Java_Comb

Networking

• The key networking classes are in the packagejava.net

• The package aims to facilitate communicationacross the network using

– HTTP– TCP/IP– UDP (Datagrams)

• Corresponding classes are provided. – InetAddress– URL– Socket (client socket)– ServerSocket– DatagramSocket– DatagramPacket

• The following programs demonstrate the use ofthese classes.

Getting an Internet address: Factory methods

• To get an IP address we use the InetAddressclass.

• The InetAddress class has no visibleconstructors.

CKR Java Notes 261

ww

w.n

eevi

aPDF.

com

Page 535: Java_Comb

• An object of the class must be constructed usingone of the so-called "factory methods"

– A factory method is merely a conventionwhere a static method in a class returnsan instance of the class.

– Factory methods are substitutes foroverloaded constructors.

– In the case of InetAddress, factorymethods are more appropriate thanconstructors: one gets an address.

• Some of these factory methods are

– getLocalHost()– getByName()– getAllByName()

• These methods have the prototypes

static InetAddress getLocalHost() throwsUnknownHostException

static InetAddress getByName (StringhostName) throws Unknown HostException

static InetAddress[]getAllByName (StringhostName) throws UnknownHostException

CKR Java Notes 262

ww

w.n

eevi

aPDF.

com

Page 536: Java_Comb

• The following program demonstrates the use ofthese factory methods.

Program 44import java.net.* ; class InetTest { public static void main(String args[])

throws UnknownHostException { InetAddress Address =InetAddress.getLocalHost();System.out.println("local host: " +Address); Address =InetAddress.getByName("msn.com");

System.out.println ("msn.com" + Address); InetAddress MSN[] =InetAddress.getAllByName ("www.msn.com");

for (int i=0; i MSN.length; i++)System.out.println ("www.msn.com" +

MSN[i]); } }

• output: localhost: 127.0.0.1 msn.com: 207.46.176.152 www.msn.com: 207.46.185.138 www.msn.com: 207.46.185.140www.msn.com: 207.46.209.218www.msn.com: 207.46.209.243www.msn.com: 207.46.179.134www.msn.com: 207.46.179.143 www.msn.com: 207.46.179.71Application Exit...

CKR Java Notes 263

ww

w.n

eevi

aPDF.

com

Page 537: Java_Comb

Getting a URL

• A URL is a Uniform Resource Locator: a pointerto a resource on the web.

• A "resource" may be – a file– a directory,– a query to a database– or other information generated on the fly.

• The public final class URL encapsulates a URL.

• To get a URL, we use the URL class.

• The URL class has several constructors

• The simplest constructor uses a URL specifiedby means of a string.

URL (String urlSpecifier);

• We can also break up the URL into itscomponents, and specify

– the protocol– the host name– the port name (optional)– path

to obtain a URL object.

CKR Java Notes 264

ww

w.n

eevi

aPDF.

com

Page 538: Java_Comb

• That is, we can also use the following twoconstructors.

URL (String protocolName, String hostName,int portNumber, String path)

URL (String protocolName, String hostName,String path)

• The following program builds a URL object fromthe string form of the URL

CKR Java Notes 265

ww

w.n

eevi

aPDF.

com

Page 539: Java_Comb

Program 45import java.net.*; class URLTest { public static void main(String args[]) throws MalformedURLException { URL url = new URL("http://www.hotmail.com"); System.out.println("Protocol: " +

url.getProtocol()); System.out.println ("Port: " + url.getPort()); System.out.println ("Host: " + url.getHost()); System.out.println ("File: " +

url.getFile()); System.out.println ("String: " +

url.toString()); }

}

• Output: Protocol: http Port: -1 (getPort returns - 1 if port not explicitly

set) Host: www.hotmail.com File: / String: http: //www.hotmail.com/

CKR Java Notes 266

ww

w.n

eevi

aPDF.

com

Page 540: Java_Comb

Connecting to a URL

• Once we have created a URL object we canconnect to it using the

– openConnection method. • This method returns an object of the

– URLConnection class

• Once we have connected to a URL, we can queryits properties, using methods (of theURLConenction class) such as

– getDate()– getLastModified()– getContentType()– getContentLength()

• A URL connection can be used for input andoutput.

• Having connected to a URL we can also readfrom it, using

– getInputeStream methodwhich returns an InputStream object from which wecan read and write using standard i/o techniques.

• We can also write to the URL, using the– getOutputStream method

and standard i/o techniques to the OutputStreamobject that it returns.

CKR Java Notes 267

ww

w.n

eevi

aPDF.

com

Page 541: Java_Comb

Connecting to a URL and transferring a file

import java.net.*; import java.io.*;import java.util.Date;class UConnect { public static void main (String args[]) throws Exception

//so declared, to avoid //exception handling logic {

int c=0; URL url = new

/*URL("http://www.ncsa.uiuc.edu/demoweb/url-primer.html"); */ //no more accessible URL("http://www.w3.org/Addressing/URL/url-spec.txt");

URLConnection urlCon = url.openConnection();

System.out.println ("Date: " + new Date (urlCon.getDate() ));

System.out.println ("Content type: " + urlCon.getContentType());System.out.println ("Last Modified: " +

new Date (urlCon.getLastModified()) ); int len = urlCon.getContentLength();

System.out.println ("Content length: " +len);

CKR Java Notes 268

ww

w.n

eevi

aPDF.

com

Page 542: Java_Comb

if (len == 0 ) { System.out.println ("No content totransfer");

return; } if (len == -1) { System.out.println ("Content length notknown"); } InputStream in =urlCon.getInputStream();

FileOutputStream fout = newFileOutputStream

("c:\\kawa\\url-spec.txt");

while ( ((c=in.read()) != -1) ) { fout.write(c);} in.close(); fout.close(); } }

• Output Date: Wed Jun 13 06:34:31 GMT+05:30 2001Content type: text.plain; Last Modified: Thu Mar 31 20:18:08 GMT+05:301994 Content length: 46204

CKR Java Notes 269

ww

w.n

eevi

aPDF.

com

Page 543: Java_Comb

Sockets

• A URL is for relatively high-level communication.

• Sometimes one must communicate with anothermachine at a lower level.

• For this, one uses sockets.

• The socket concept was evolved with BSD Unix.

• The purpose of sockets is to permitinter-process communication.

• A socket is one end of such an inter-processcommunication.

• Thus, a socket is like a telephone instrumentwhich permits two persons to talk to each other.

• A socket may concurrently handle severalprocesses.

• Thus, a more precise analogy is that a socket islike an EPABX:

– there is only one telephone number– But there are several lines, so that– several people can simultaneously

converse using that one number.

CKR Java Notes 270

ww

w.n

eevi

aPDF.

com

Page 544: Java_Comb

Sockets (contd)

• More precisely, a socket is one endpoint of atwo-way communication link between twoprocesses (running on a computer or a network).

– A socket is tied to a port number (toenable the TCP layer to identify theapplication with which data is beingexchanged).

• From the user point of view, to create a socket,or communicate with a socket one needs

– the IP address

– the port number

– An InputStream/OutputStream object orBufferedReader/PrintWriter object.

– Communication is subsequently likenormal i/o via the i/o object.

• The IP address must be specified by theprogrammer or the user.

CKR Java Notes 271

ww

w.n

eevi

aPDF.

com

Page 545: Java_Comb

• The port number depends upon the service.

• For example:

– FTP: 21– Telnet: 23– SMTP: 25 (Simple Mail Transfer Protocol)– Timeserver: 37– Nameserver: 42– Whois: 43– MTP: 57– HTTP: 80– Servlets: 8080

• For more details on Port Numbers, see RFC1700.

• The java.net package contains various classesencapsulating sockets in a platform independentway.

• A key class which the programmer will use is theclass Socket, which implements client sockets.

• (For serverside-sockets there is a separate classcalled ServerSockets)

CKR Java Notes 272

ww

w.n

eevi

aPDF.

com

Page 546: Java_Comb

Sockets (contd)

• The Socket class has several constructors, oneof which has the following prototype:

public Socket (InetAddress address, intPortno) throws IOException

• The uses of this constructor are demonstrated inthe following example which sends email, usingSMTP.

• (For more details on SMTP see RFC 821.)

Program 46 /*Program EMail.java Function: to send email across a socket*/

import java.net.*;import java.io.*;

public class EMail{

public static void main (String args[])throws Exception

{Socket s;//InetAddress Address =

InetAddress.getByName ("mail.hotmail.com");InetAddress Address =

CKR Java Notes 273

ww

w.n

eevi

aPDF.

com

Page 547: Java_Comb

InetAddress.getByName ("mail.vsnl.net");System.out.println ("Address: " + Address);try { s = new Socket (Address, 25);//Port 25 is for SMTP: Simple Mail

Transfer Protocol

}catch (Exception e){

System.out.println ("Error openingsocket");

return;}System.out.println ("Opened socket");if (s==null) { return; }

try{

PrintWriter out = new PrintWriter (

new OutputStreamWriter (s.getOutputStream()), true);BufferedReader in = new

BufferedReader ( newInputStreamReader ( s.

getInputStream() ));if (out==null || in==null){System.out.println ("Failed to open

stream to socket");

CKR Java Notes 274

ww

w.n

eevi

aPDF.

com

Page 548: Java_Comb

return;}

String hostName =InetAddress.getLocalHost().getHostName();

//String hostName = "Ghost";System.out.println ("Obtained i/o stream");String initID = in.readLine();System.out.println (initID);

out.println ("HELO " + hostName);System.out.println ("HELO " + hostName);

String resp = in.readLine();System.out.println (resp);

out.println ("MAIL FROM:<"+"[email protected]"+">");

String senderOK = in.readLine();System.out.println (senderOK);

out.println ("RCPT TO:<" +"[email protected]"+">");

String recptOK = in.readLine();System.out.println (recptOK);

out.println ("DATA");out.println ("The quick brown fox has sent

CKR Java Notes 275

ww

w.n

eevi

aPDF.

com

Page 549: Java_Comb

you mail");out.println (".");out.flush();s.close();}catch (IOException ex){

System.out.println ("IO Exception");}

}}

• Output: Address: mail.vsnl.net/203.197.12.5Opened socketObtained i/o stream220 mail02.vsnl.net ESMTP service(Netscape Messaging Server 4.15 Patch 2(built May 30 2000))HELO c250 mail02.vsnl.net250 Sender <[email protected]> Ok250 Recipient <[email protected]> OkApplication Exit...

CKR Java Notes 276

ww

w.n

eevi

aPDF.

com

Page 550: Java_Comb

JDBC

• JDBC stands for Java Data Base Connectivity.

• JDBC is different from ODBC in that – JDBC is written in Java (hence is

platform independent, object orientedrobust etc.), while

– ODBC is written in C, is not objectoriented.

• However, both JDBC and ODBC are based on theX/Open SQL Command Level Interface (CLI).

• Sun provides a JDBC ODBC bridge, whichenables one to connect painlessly to ODBC datasources.

• The following steps are involved.

• Step 1: Set up a Data Source Name, using theODBC administrator.

– It is assumed that you already know howto do this.

– The following example used Oracle 8Personal Edition, setting up a DataSource Name called Test on the localcomputer.

CKR Java Notes 277

ww

w.n

eevi

aPDF.

com

Page 551: Java_Comb

– But this would work just as well withAccess or DBase or FoxPro.

• Step 2: Load and Register the JDBC driver.

– The following example supposes thatone is using the jdbc-odbc bridge driversupplied by sun.

– Loading and registering the driver isdone using the single statement.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

• java.lang.Class is a public final class whichdescends directly from java.lang.Object (andimplements Serializable)

• The forName method of class Class has thefollowing prototype

public static Class forName (StringclassName) throws ClassNotFoundException

• The exception is thrown if the class representingthe driver is not found.

• For the class name of other drivers, check thedriver documentation.

CKR Java Notes 278

ww

w.n

eevi

aPDF.

com

Page 552: Java_Comb

JDBC (contd)

• Step 3: Connect to the database. Once the driverhas been loaded, one must connect to thedatabase (specified in the DSN)

• This is again achieved using a single statementDriverManager.getConnection(

url, user_login, user_password)

• DriverManager is a public class which extendsObject.

– This class is located in the java.sqlpackage.

• getConnection is a public static method of theDriverManager class, with the following prototype

public static Connection getConnection(String url, String user, String password)throws SQLException

• This method is appropriately overloaded. – example one overloaded version will

take only the url, for databases which donot have a user login or user password(such as DBaseIII)

CKR Java Notes 279

ww

w.n

eevi

aPDF.

com

Page 553: Java_Comb

• The meaning of user_login and user_passwordis obvious.

• String url is specified as follows: "jdbc:subprotocol:DSN"

• For the present case of ODBC, if the Data SourceName is Test, the url would be specified as

"jdbc:odbc:Test"

• Connection is an interface defined in thejava.sql package.

• Step 4: Create an SQL statement.

• This is done using the createStatementmethod of the Connection object returned bythe getConnection method of Step 3.

• The createStatement method (appropriatelyoverloaded) has a prototype

public Statement createStatement () throws SQLException()

• Statement is an interface defined in the java.sqlpackage:

– it is intended to represent an SQLstatement.

CKR Java Notes 280

ww

w.n

eevi

aPDF.

com

Page 554: Java_Comb

JDBC (contd)

• Step 5: Execute a given SQL statement – using the executeUpdate method of the

Statement object – returned by createStatement method

in Step 4.

• Step 6: Close– the statement, and– the connection.– using the respective close methods.

• 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 atable called TEAS.

Program 47

import java.sql.*;public class JDBCMakeTea {public static void main (String args[]){

String myDriverName ="sun.jdbc.odbc.JdbcOdbcDriver";

//the above is the fully qualified name ofthe sun

//jdbc-odbc bridge driver class.

CKR Java Notes 281

ww

w.n

eevi

aPDF.

com

Page 555: Java_Comb

String url = "jdbc:odbc:test";//the above string has the form//protocol:subprotocol:datasourcename//Thus test is the user DSN specified//in the ODBC administrator

String myLogin = "DEMO"; //user nameString myPassword = "demo"; //password

String sqlString = "create table TEAS " +"(TEA_NAME VARCHAR (32), " + "SUP_ID INTEGER, " +"PRICE FLOAT, " + "SALES INTEGER, " + "TOTAL INTEGER)";

try{

Class.forName (myDriverName);//the forName method of java.lang.Class//will load and register the driver.

}

catch (ClassNotFoundException e){

System.err.println ("Error loadingdriver");

return;

CKR Java Notes 282

ww

w.n

eevi

aPDF.

com

Page 556: Java_Comb

}

try{

Connection con = DriverManager.getConnection (url, myLogin, myPassword);

//connect to database

Statement stmt = con.createStatement();

stmt.executeUpdate (sqlString);

stmt.close();con.close();

}

catch (SQLException ex){

System.err.println ("SQLException " + ex.getMessage());

}}}

• Output: if no error messages – a table called teas is created under the

database connection called Test.

CKR Java Notes 283

ww

w.n

eevi

aPDF.

com

Page 557: Java_Comb

JDBC: Executing a query

• To summarise: the basic procedure is

– set up a DSN– Load and Register the JDBC driver– Connect to the DSN– Create a SQL statement– execute the SQL statement– close the statement and the connection.

• To execute a query a change is required only inStep 5.

– Instead of the executeUpdate methodused to execute a SQL statement, we willuse the executeQuery method of thestatement object.

– The executeUpdate method, returns anint, and so is restricted to INSERT,UPDATE and DELETE statements,

– or SQL statements that return nothingsuch as SQL DDL (Data DefinitionLanguage) statements, such as CREATE,ALTER, DROP

CKR Java Notes 284

ww

w.n

eevi

aPDF.

com

Page 558: Java_Comb

• A query however, returns a result set.

– A result set is encapsulated in theinterface ResultSet of the java.sqlpackage.

• A ResultSet object maintains a cursor pointingto the current row of data.

– It is initially set to point before the firstrow.

• The next method of the ResultSet objectmoves the cursor to the next row.

• Various getXXX methods return the values of thecolumns in the ResultSet.

• These considerations are illustrated by thefollowing program.

Program 48

import java.sql.*;public class JDBCAddTea{

public static void main (String args[]){

String myDriverName ="sun.jdbc.odbc.JdbcOdbcDriver";

CKR Java Notes 285

ww

w.n

eevi

aPDF.

com

Page 559: Java_Comb

//the above is the fully qualified name ofthe sun

//jdbc-odbc bridge driver class.

String url = "jdbc:odbc:test";//the above string has the form//protocol:subprotocol:datasourcename6//Thus test is the user DSN specified//in the ODBC administrator

String myLogin = "DEMO"; //user nameString myPassword = "demo"; //password6

String sqlString;Connection con; //Connection is an

interfaceStatement stmt; //Statement is an interface

try{

Class.forName (myDriverName);//the forName method of java.lang.Class//will load and register the driver.

}

catch (ClassNotFoundException e){

System.err.println ("Error loadingdriver");

CKR Java Notes 286

ww

w.n

eevi

aPDF.

com

Page 560: Java_Comb

return;}

try{

con = DriverManager.getConnection (url, myLogin, myPassword);

//connect to databasestmt =

con.createStatement();//so far this is standard for any//JDBC program. //we now change the sql command. sqlString = "insert into TEAS " +"values (’Darjeeling’, 201, 400.5, 0, 0)"; stmt.executeUpdate (sqlString);

sqlString = "insert into TEAS " +"values (’Assam’, 202, 56.3, 0, 0)"; stmt.executeUpdate (sqlString);

sqlString = "insert into TEAS " +"values (’Nilgiri’, 203, 100.5, 0, 0)";

CKR Java Notes 287

ww

w.n

eevi

aPDF.

com

Page 561: Java_Comb

stmt.executeUpdate (sqlString);

sqlString = "insert into TEAS " +"values (’Sri Lanka’, 501, 200.4, 0, 0)"; stmt.executeUpdate (sqlString);

//We now execute a query

String query = "select TEA_NAME, PRICE from TEAS";

//The results of the query are put into //an object of type result set.//ResultSet is an interface in java.sql

ResultSet rs = stmt.executeQuery (query);

System.out.println ("Tea Break: Teas and their prices: ");

while (rs.next()){

String s = rs.getString ("TEA_NAME");float f = rs.getFloat ("PRICE");System.out.println (s + " " + f);

}

CKR Java Notes 288

ww

w.n

eevi

aPDF.

com

Page 562: Java_Comb

//now put in the standard JDBC //closing process.

stmt.close();con.close();

}catch (SQLException ex){ System.err.println ("SQLException " +

ex.getMessage());}

}}

• Output:

Tea Break: Teas and their prices:Darjeeling 400.5Assam 56.3 Nilgiri 100.5 Sri Lanka 200.4

CKR Java Notes 289

ww

w.n

eevi

aPDF.

com

Page 563: Java_Comb

JDBC: New Features of the Java 2.0 API

• Certain new features are incorporated in theJDBC API available with JDK1.2

• ResultSets are scrollable both backward andforward.

– In JDK 1.0 one could only move forwardusing the next() method.

– We now have the previous()absolute(int)relative (int)methods, along with other methods.

– One can now declare the ResultSet to beof type TYPE_FORWARD_ONLYTYPE_SCROLL_INSENSITIVE (changesare not reflected while the result set isopen)TYPE_SCROLL_SENSITIVE (changesare reflected immediately)

• Updates can be made to database tables usingJava API methods instead of using SQLcommands.

CKR Java Notes 290

ww

w.n

eevi

aPDF.

com

Page 564: Java_Comb

– For example insertRow() method willinsert a row in the present location.

• Multiple SQL statements can be sent to thedatabase, as a unit or a batch.

• The new SQL3 datatypes can be used as columnvalues.

– These include BLOB (Binary Large Object)CLOB (Character Large Object)ArrayStruct to map SQL user defined types.

• For further information on using these methods,consult the API documentation.

CKR Java Notes 291

ww

w.n

eevi

aPDF.

com

Page 565: Java_Comb

Remote Method Invocation

• So far, all applications have been running on one(local) Java Virtual Machine.

• The RMI technology makes it possible to have anobject distributed across JVM’s.

• RMI applications typically take the form ofclient-server applications.

• When combined with the standard polymorphicfeatures, this can lead to a situation where

– a fast server executes a task– which it does not know about at compile

time.

• The following program provides an example ofhow this "RMI magic" is achieved.

• Basically, the server downloads from the client,the byte code of the class to be executed.

• After completing execution, it uploads the codeback again.

• This is done in a platform independent way.

• It is also done in a secure way, as follows.

CKR Java Notes 292

ww

w.n

eevi

aPDF.

com

Page 566: Java_Comb

RMI: Security

• Due attention has to be paid to the securityaspects.

• An RMI program will NOT run, until a securitymanager has been installed,

– and a policy file has been created– with the appropriate permissions.

• A security manager is installed through a singleline of code:

System.setSecurityManager (newRMISecurityManager());

• The policy file typically has the name – java.policy– and is located in the C:\windows file– but could be located anywhere.

• A sample file is provided in JRE\lib\java.policy.

• This file may be edited with the policytoolwhich is a part of the JDK.

– and the appropriate permissions mustbe granted.

CKR Java Notes 293

ww

w.n

eevi

aPDF.

com

Page 567: Java_Comb

RMI: Stubs and Skeletons

• Classes capable of being invoked remotely havestubs and skeletons.

• Stubs and Skeletons are surrogates (proxies) – Stubs are client side, and – Skeletons are server side

surrogates (proxies) for RMI capable classes.

• From Java 1.2 onwards, Skeletons are no longerused. Related methods are fully deprecated, withno substitute.

• However, stubs and skeletons must still begenerated,

– for backward compatibility with Java 1.1,which may be running on the remotemachine.

• Stubs and skeletons are generated from thecompiled classes by using the Java rmicompiler tool

– rmicwhich is part of the JDK toolkit.

• (This tool is to be used after javac has been usedto compile the program and create the relevantclasses. )

CKR Java Notes 294

ww

w.n

eevi

aPDF.

com

Page 568: Java_Comb

RMI: registration

• Before an RMI class can be invoked, it must be– (a) started– (b) registered in a special registry called

the RMI registry.

• This is achieved through – API calls, and– the rmiregistry tool

The foregoing considerations are illustrated by thefollowing example.

CKR Java Notes 295

ww

w.n

eevi

aPDF.

com

Page 569: Java_Comb

RMI: Example

• This example creates a server process which– accepts tasks from clients– returns the results to the clients.

• The server process involves three pieces ofcode.

• (1) an interface definition– interface RMIdoTask – in package rmitask

• (2) a second interface used in the first interface – interface Task– in package rmitask.

• (3) an implementation of the interface defined inthe code in (1) above.

– class MyRMI– in package rmiclass.

• The client process involves two pieces of code.

• (4) A class Pi which implements the interfaceTask

– and knows how (has a method ) tocalculate the value of Pi.

• (5) A class CalcPI which invokes the remotemethod.

CKR Java Notes 296

ww

w.n

eevi

aPDF.

com

Page 570: Java_Comb

RMI Example (contd): RMIDoTask.java

• Step 1: Define the first remote interface.

• The key idea is that a remotely accessible objectmust extend the interface java.rmi.Remote.

• The code is as follows.

• File: rmitask/RMIDoTask.java

package rmitask;import java.rmi.Remote; import java.rmi.RemoteException;

//all remotely accessible interfaces must//have the above two import statements.//An object declares itself as Remote //by extending java.rmi.Remote.

public interface RMIDoTask extends Remote { Object doTask (Task t)

throws RemoteException; }

• java.rmi.RemoteException is a subclass ofIOException, and is, hence, a checked exception.

• Task is an interface to be defined.

CKR Java Notes 297

ww

w.n

eevi

aPDF.

com

Page 571: Java_Comb

RMI Example (contd): Interface Task

• The interface Task used in the previous piece ofcode is defined as follows.

• The key idea is that RMi uses Serialization totransport the object from one Java VirtualMachine to another.

– by converting the object into a bytestream, and reconverting the streamback into an object.

– Hence RemoteException is a kind ofIOException.

• Serialization or object persistence is achievedthrough extending the interface Serializable.

• The Serializable interface has no methods,and this is mainly a matter of the objectsemantics to declare that the object is persistent.

• This interface must be defined in a separate file,since all remote interfaces have to be public.

package rmitask;import java.io.Serializable;public interface Task extends Serializable{

Object execute();}

CKR Java Notes 298

ww

w.n

eevi

aPDF.

com

Page 572: Java_Comb

RMI Example (contd): Class MyRMI

• To make a remote object, one simply implementsa remote interface.

• This is done in the file MyRMI.java, which is putinto a separate package rmiclass, to separate theinterface definition from its implementation.

• The public class MyRMI

– implements the interface RMIDoTask.

– It also extends the classUnicastRemoteObject

• Extending this class is NOT mandatory. (Error inJava 2 Complete Reference, p 834) .

– However, this is a convenience classwhich provides appropriate rmiimplementations of the methods

– which override the methods of the objectclass.

– A class which does not extendUnicastRemoteObject, e.g. it simplyextends RemoteObject

CKR Java Notes 299

ww

w.n

eevi

aPDF.

com

Page 573: Java_Comb

– must provide its own implementation ofthe methods in the Object class.

• Additionally, this class must– (i) construct at least one instance of the

remote object– (ii) register it– (iii) declare a security policy.

• The code in rmiclass/MyRMI.java is as follows.

package rmiclass;

import java.rmi.*;import java.rmi.server.*;

import rmitask.*;

public class MyRMI extendsUnicastRemoteObjectimplements RMIDoTask

{//define a constructorpublic MyRMI () throws

RemoteException{

super();//optionally a port no. can//be specified.

CKR Java Notes 300

ww

w.n

eevi

aPDF.

com

Page 574: Java_Comb

//call to super also "exports’ the//rmi object: i.e., makes it listen//to remote calls on port 1099.

}

//implement the remote interface

public Object doTask (Task t){

return t.execute();}

//start at least one instance //of the remote object//register it//and declare a security policy.

public static void main (String args[]){

//install a standard rmi security manager//if none is installed.

if (System.getSecurityManager()==null){

System.setSecurityManager(new RMISecurityManager ());

}try{

CKR Java Notes 301

ww

w.n

eevi

aPDF.

com

Page 575: Java_Comb

//declare an instance of the remote objectRMIDoTask rm = new MyRMI();

//decide a name for it

String name = " RMITask";

//name must have the above form//optionally a port no. may be specified//host:porno.

//if no port number is specified//port 1099 is used.

//register (bind) the name in the//rmiRegistry

Naming.rebind (name, rm);

//we use rebind instead of bind to//avoid exceptions, if name is already//bound//report success

System.out.println ("RMITask registered");}catch (Exception e){

System.err.println ("MyRMI exception:" + e.getMessage());

}}}

CKR Java Notes 302

ww

w.n

eevi

aPDF.

com

Page 576: Java_Comb

RMIExample (contd): The client class CalcPI

• The RMI Client must also set up a securitymanager.

• It simply looks up the name of the rmi object inthe rmiregistry.

• and passes the task to it.

• The task in this case is to calculate pi to anarbitrary number of decimal places.

• Hence the class java.math.BigDecimal is used topermit arbitrary precision arithmetic.

• The code for the RMI client CalcPI (main method)is as follows.

package rmiclient;

import java.rmi.*;import java.math.*;import rmitask.*;

public class CalcPi { public static void main (String args[])

{//load rmisecurity manager//else rmi call will fail.

CKR Java Notes 303

ww

w.n

eevi

aPDF.

com

Page 577: Java_Comb

if (System.getSecurityManager()==null)System.setSecurityManager(new RMISecurityManager() );

try { String name = "//"+args[0]+"/RMITask"; //args[0] is the host name: portno //if nothing is specified //local host is used on port 1099. RMIDoTask rm1 = ((RMIDoTask)

Naming.lookup (name)); Pi myPi = new Pi (Integer.parseInt

(args[1])); //The class Pi is defined elsewhere. //args[1] is the number of decimal places //to which the value of Pi should be

//computed.

BigDecimal pivalue = (BigDecimal) (rm1.doTask (myPi)); System.out.println (pivalue); } catch (Exception e) { System.err.println ("CalcPi exception: " + e.getMessage() ) ;

e.printStackTrace(); } }}

CKR Java Notes 304

ww

w.n

eevi

aPDF.

com

Page 578: Java_Comb

RMIExample (contd): the client class Pi

• The last piece of code is the class Pi, whichactually calculates the value of Pi.

• This is done using the power series expansionfor the arctangent function.

• This expansion was first put forward by Madhavaof Sangamagrama, and is found in the MSS ofNeelkantha Somayajulu’s TantraSangraha, andJyeshtadeva’s Yuktibhasa.

• This class implements the task interface.

• The rest of the code for this class isstraightforward, and does not require muchexplanation.

•package rmiclient;

import rmitask.*;import java.math.*;

public class Pi implements Task{

private static final BigDecimal ZERO = BigDecimal.valueOf(0);

CKR Java Notes 305

ww

w.n

eevi

aPDF.

com

Page 579: Java_Comb

//class BigDecimal implements//arbitrary precision arithmetic.

private static final BigDecimal ONE = BigDecimal.valueOf(1);

private static final BigDecimal FOUR = BigDecimal.valueOf(4);

private static final int roundingMode= BigDecimal.ROUND_HALF_EVEN;

//specifies rounding mode//The above mode rounds to nearest

neighbour//or the even number if both neighbours//are equidistant.

private int precision;

public Pi (int precision){

this.precision = precision;}//define the execute method//of the Task interface

public Object execute(){

return findPi (precision);}

CKR Java Notes 306

ww

w.n

eevi

aPDF.

com

Page 580: Java_Comb

/*find the value of pi using the formulaso called "Machin’s formula"pi/4 = 4*arctan (1/5) - arctan (1/239)and the power series expansion forarctan*/

public static BigDecimal findPi (intprecision)

{int scale = precision + 5;BigDecimal arctan_1by5 = arctani (5,

scale);BigDecimal arctan_1by239 = arctani (239,

scale);

BigDecimal pivalue = arctan_1by5.multiply (FOUR).

subtract( arctan_1by239).multiply(FOUR);

return pivalue.setScale (precision, BigDecimal.ROUND_HALF_UP);

}

/*The power series for the arctangent isarctan (x) = x - (x^3)/3

+ (x^5)/5

CKR Java Notes 307

ww

w.n

eevi

aPDF.

com

Page 581: Java_Comb

- (x^7)/7+ (x^9)/9- ...

*/

public static BigDecimal arctani(int inverseX, int scale)

//calculates arctan of the inverse of//inverseX//to precision scale.

{BigDecimal result, numerator, term;BigDecimal invX = BigDecimal.valueOf

(inverseX);BigDecimal invX2 =

BigDecimal.valueOf(inverseX * inverseX);numerator = ONE.divide(invX, scale,

roundingMode);

result = numerator;

int i=1;do{

numerator = numerator.divide (invX2, scale,

roundingMode);int denominator = 2*i+1;term =

CKR Java Notes 308

ww

w.n

eevi

aPDF.

com

Page 582: Java_Comb

numerator.divide(BigDecimal.valueOf(denominator), scale, roundingMode);

if ((i%2) == 0){result = result.add(term);}else{result = result.subtract(term);}i++;} while (term.compareTo(ZERO) != 0 ) ;return result;

}}

CKR Java Notes 309

ww

w.n

eevi

aPDF.

com

Page 583: Java_Comb

RMI example: Compiling and running the code

• Step 1: Compile all the .java files into classes.

• This must be done in the following order. – rmitask/Task.java– rmitask/RMIDoTask.java

• The resulting classes should be available in theclasspath before the following is compiled.

– rmiclass/MyRMI.java.

• Step 2: To make the classes available, put themin a jar file, by using the command

jar cvf rmitask.jar rmitask/*.class

• and add the file rmitask.jar in the CLASSPATH.setCLASSPATH=C:\KAWA\rmitask.jar;%CLASSPATH%

• now the file rmiclass/MyRMI.java can becompiled.

• Step 3: Create the stub and skeleton class byusing the following command.

rmic -d . rmiclass rmiclass.MyRmi

• The -d option will place the resulting classes inthe rmiclass directory.

CKR Java Notes 310

ww

w.n

eevi

aPDF.

com

Page 584: Java_Comb

RMI Example: Compiling and running (contd)

• Step 4: Build the client classes, using the aboveset CLASSPATH.

• Step 5: Declare a security policy.

– a sample security policy file exists in thejdk1.2.2/jre/lib/security/java.policy file.

– This file could be copied to anyconvenient location, such asc:\windows.

• invoke policytool

– Open the c:\windows\java.policy file.– choose codebase <ALL>– Add permission: SocketPermission– Target: *:1024-65535– Actions: accept, connect, listen, resolve

– Add permission: File permissions– Target: c:\kawa\- – Actions: read

– Add permission: File Permission– Target: c:\kawa\rmitask.jar– Actions: read

CKR Java Notes 311

ww

w.n

eevi

aPDF.

com

Page 585: Java_Comb

• This will add the following lines of code in thepolicy file.

grant{

permission java.net.SocketPermission"*:1024-655535, "accept, connect, listen,resolve";

/* This grants permission to processesusing non-privileged ports above 1024.Recall that rmi uses port 1099 by default*/

permission java.io.FilePermission"c:\\kawa\-", "read";}

• The above lines could be added by hand as well.

• Basically, the first line grants permission toprocesses to use non-privileged ports (with portnumbers above 1024.

• The second line grants permission to processesto read all files in the c:\kawa directory.

CKR Java Notes 312

ww

w.n

eevi

aPDF.

com

Page 586: Java_Comb

RMI Example: compiling and running the code (contd)

• Step 6: – (a) Unset the classpath, and– (b) start the rmiregistry.

• This is achieved through the followingcommands.

set CLASSPATH=start rmiregistry

• Step 7: Next one must start the server process.

• This may be done using a batch file (since thecommand line buffer may not contain the entirecommand)

• The batch file rmstart.bat has the followingcontents.

setCLASSPATH=.;C:\kawa;c:\kawa\rmitask.jarjava-Djava.rmi.server.codebase=file:c:\kawa/

-Djava.rmi.server.hostname=127.0.0.1 -Djava.security.policy=

c:\windows\java.policy rmiclass.MyRMI 127.0.0.1 10

CKR Java Notes 313

ww

w.n

eevi

aPDF.

com

Page 587: Java_Comb

• Step 8: Finally start the client process, andrequest a value of pi correct to 10 decimalplaces.

• This may be done through the batch filermicli.bat which has the following contents.

set CLASSPATH=.;C:\KAWA;C:\KAWA\rmitask.jarjava-Djava.rmi.server.codebase=file:c:\kawa/ -Djava.security.policy=

c:\windows\java.policy rmiclient.CalcPi 127.0.0.1 10

• Output: 3.1415926536

CKR Java Notes 314

ww

w.n

eevi

aPDF.

com

Page 588: Java_Comb

JFC and Swing

• Since java aims to be platform independent.

• And, since the behaviour of windows is differenton different platforms (Mac, X, MSWindows)

– this presents a problem.

• The AWT (abstract Windows toolkit) was the firstanswer to this problem.

• The Swing API is the second answer to thisproblem.

• Swing API are "lightweight" since they arewritten entirely in Java.

• Nevertheless, they offer many of the GUIfeatures of, say, MS-Windows programming.

• In this respect, Java Foundation Classes are likeMicrosoft Foundation classes:

– They make windowed programs mucheasier to write.

• Before proceeding further, let us take a fewexamples.

CKR Java Notes 315

ww

w.n

eevi

aPDF.

com

Page 589: Java_Comb

Java Swing: Hello World

/*First JFC program */

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JHelloWorld extends JPanel

{static JFrame jf;public JHelloWorld (){

JLabel lb = new JLabel ("Hello JFC World");

add (lb);}

public static void main ( String args[] )

{jf = new JFrame ("Hello JFC World");JHelloWorld jHello = new JHelloWorld();jf.getContentPane().add("Center", jHello);jf.setSize (250, 150);jf.addWindowListener

(new WindowAdapter(){

public void windowClosing

CKR Java Notes 316

ww

w.n

eevi

aPDF.

com

Page 590: Java_Comb

(WindowEvent e){ System.exit(0);}

});

jf.setVisible (true);}

}

• This program has the following output.

CKR Java Notes 317

ww

w.n

eevi

aPDF.

com

Page 591: Java_Comb

More Swing

• To get a better feel for some of the features ofSwing, try the following program.

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.border.*;

public class JSwingStart extends Frame { public static int WIDTH = 450; public static int HEIGHT = 450; public static String TITLE = "SwingStart";

// Swing components JTabbedPane tabbedPane = newJTabbedPane(); JPanel buttonPanel = new JPanel(); JPanel barPanel = new JPanel(); JPanel listPanel = new JPanel(); JPanel tablePanel = new JPanel(); JPanel[] panels ={buttonPanel,barPanel,listPanel,tablePanel};

Icon worldIcon = newImageIcon("world.gif"); Icon printerIcon = newImageIcon("printer.gif"); Icon leaf1Icon = new

CKR Java Notes 318

ww

w.n

eevi

aPDF.

com

Page 592: Java_Comb

ImageIcon("leaf1.gif"); Icon leaf2Icon = newImageIcon("leaf2.gif"); Icon leaf3Icon = newImageIcon("leaf3.gif"); Icon[] leaves = {leaf1Icon, leaf2Icon,leaf3Icon}; JButton printerButton = newJButton("Print",printerIcon); JToggleButton worldButton = newJToggleButton("Connect",worldIcon,true); JList leafList = new JList(leaves); JSlider slider = newJSlider(JSlider.VERTICAL, 0, 100, 60); JProgressBar progressBar = newJProgressBar(); String[] columns = {"ProductID","Description","Price"}; Object[][] cells ={columns,{"zvga-1234","Video Card","$50"}, {"56m-11","56K Modem","$315"}, {"dc-10","Net Card","$499"}}; JTable table = new JTable(cells,columns);

public JSwingStart() { super(TITLE); addWindowListener(new WindowHandler()); buildGUI(); setSize(WIDTH,HEIGHT); setBackground(Color.darkGray);

CKR Java Notes 319

ww

w.n

eevi

aPDF.

com

Page 593: Java_Comb

show(); } void buildGUI() { // Set up tabbed pane String[] tabs ={"Buttons","Bars","Lists","Table"}; String[] tabTips = {"A Button and aToggle Button", "A Slider and a Progress Bar", "An Icon List", "A Cost Table"}; for(int i=0;iabs.length;++i) {

panels[i].setBackground(Color.lightGray); panels[i].setBorder(newTitledBorder(tabTips[i]));

tabbedPane.addTab(tabs[i],null,panels[i],tabTips[i]); } addComponentsToTabs(); add("Center",tabbedPane); }

void addComponentsToTabs() { setupButtonPanel(); setupBarPanel(); setupListPanel(); setupTablePanel();

CKR Java Notes 320

ww

w.n

eevi

aPDF.

com

Page 594: Java_Comb

}

void setupButtonPanel() { printerButton.setBackground(Color.white); worldButton.setBackground(Color.white); buttonPanel.add(printerButton); buttonPanel.add(worldButton); } void setupBarPanel() { slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(5); slider.setPaintTicks(true); slider.addChangeListener(newSliderHandler());

progressBar.setOrientation(JProgressBar.HORIZONTAL); progressBar.setMinimum(0); progressBar.setMaximum(100); progressBar.setValue(60); progressBar.setBorderPainted(true); barPanel.add(new JLabel("Slider")); barPanel.add(slider); barPanel.add(new JLabel("Progress Bar")); barPanel.add(progressBar);} void setupListPanel() { leafList.setFixedCellHeight(123);

CKR Java Notes 321

ww

w.n

eevi

aPDF.

com

Page 595: Java_Comb

listPanel.add(leafList); } void setupTablePanel() { tablePanel.add(table); }

public static void main(String[] args) { JSwingStart app = new JSwingStart(); } public class WindowHandler extendsWindowAdapter { public void windowClosing(WindowEvent e){ System.exit(0); } } public class SliderHandler implementsChangeListener { public void stateChanged(ChangeEvent e) { progressBar.setValue(slider.getValue()); } }}

• This program has the following output.

CKR Java Notes 322

ww

w.n

eevi

aPDF.

com

Page 596: Java_Comb

CKR Java Notes 323

ww

w.n

eevi

aPDF.

com

Page 597: Java_Comb

1

Packages and Packages and Class pathClass path

ww

w.n

eevi

aPDF.

com

Page 598: Java_Comb

2

What are Packages?● A package is a grouping of related types providing

access protection and name space management– Note that types refers to classes, interfaces,

enumerations, and annotation types.– Types are often referred to simply as classes and

interfaces since enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to simply as classes and interfaces.

ww

w.n

eevi

aPDF.

com

Page 599: Java_Comb

3

Benefits of Packaging● You and other programmers can easily determine that

these classes and interfaces are related.● You and other programmers know where to find

classes and interfaces that can provide graphics-related functions.

● The names of your classes and interfaces won't conflict with the names in other packages because the package creates a new namespace.

● You can allow classes within the package to have unrestricted access to one another yet still restrict access for types outside the package.ww

w.n

eevi

aPDF.

com

Page 600: Java_Comb

4

Creating a PackageCreating a Package

ww

w.n

eevi

aPDF.

com

Page 601: Java_Comb

5

Creating a Package● To create a package, you choose a name for the

package and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package

● If you do not use a package statement, your type ends up in an unnamed package– Use an unnamed package only for small or temporary

applications

ww

w.n

eevi

aPDF.

com

Page 602: Java_Comb

6

Placing a Class in a Package● To place a class in a package, we write the following as

the first line of the code (except comments)package <packageName>;package myownpackage;

ww

w.n

eevi

aPDF.

com

Page 603: Java_Comb

7

Example Package● Suppose you write a group of classes that represent

graphic objects, such as circles, rectangles, lines, and points

● You also write an interface, Draggable, that classes implement if they can be dragged with the mouse

//in the Draggable.java filepublic interface Draggable {}

//in the Graphic.java filepublic abstract class Graphic {}

//in the Circle.java filepublic class Circle extends Graphic implements Draggable {}

//in the Rectangle.java filepublic class Rectangle extends Graphic implements Draggable { }

//in the Point.java filepublic class Point extends Graphic implements Draggable {}

//in the Line.java filepublic class Line extends Graphic implements Draggable {}

ww

w.n

eevi

aPDF.

com

Page 604: Java_Comb

8

Example: Placing StudentRecord class in SchoolClasses pacakgepackage SchoolClasses;

public class StudentRecord {private String name;private String address;private int age;:

ww

w.n

eevi

aPDF.

com

Page 605: Java_Comb

9

Importing and Using Importing and Using classes from other classes from other

PackagesPackagesww

w.n

eevi

aPDF.

com

Page 606: Java_Comb

10

Using Classes from Other Packages

● To use a public package member (classes and interfaces) from outside its package, you must do one of the following– Import the package member using import statement– Import the member's entire package using import

statement– Refer to the member by its fully qualified name (without

using import statement)

ww

w.n

eevi

aPDF.

com

Page 607: Java_Comb

11

Importing Packages● To be able to use classes outside of the package you are

currently working in, you need to import the package of those classes.

● By default, all your Java programs import the java.lang.* package, that is why you can use classes like String and Integers inside the program even though you haven't imported any packages.

● The syntax for importing packages is as follows:import <nameOfPackage>;

ww

w.n

eevi

aPDF.

com

Page 608: Java_Comb

12

Example: Importing a Class or a Package

// Importing a classimport java.util.Date;

// Importing all classes in the // java.util packageimport java.util.*;

ww

w.n

eevi

aPDF.

com

Page 609: Java_Comb

13

Using Classes of other packages via fully qualified path

public static void main(String[] args) { java.util.Date x = new java.util.Date(); }

ww

w.n

eevi

aPDF.

com

Page 610: Java_Comb

14

Package & Directory Structure● Packages can also be nested. In this case, the Java

interpreter expects the directory structure containing the executable classes to match the package hierarchy.

● There should have same directory structure, ./myowndir/myownsubdir/myownpackage directory for the following package statementpackage myowndir.myownsubdir.myownpackage;

ww

w.n

eevi

aPDF.

com

Page 611: Java_Comb

15

Managing Sources Managing Sources & Class files & Class files w

ww

.nee

viaP

DF.co

m

Page 612: Java_Comb

16

Managing Source and Class Files ● Create a *.java file for the class you want to create

// in the Rectangle.java file package graphics;public class Rectangle() { . . . }

● Place the source file in a directory whose name reflects the name of the package to which the class belongs– .....\graphics\Rectangle.java

ww

w.n

eevi

aPDF.

com

Page 613: Java_Comb

17

Directory Structure of Java Source Files

● The qualified name of the class file and the path name to the Java source file are parallel

● Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name

● Exampleclass name: graphics.Rectanglepathname to source file: graphics/Rectangle.javapathname to the class file: graphics/Rectangle.classww

w.n

eevi

aPDF.

com

Page 614: Java_Comb

18

Directory Structure of Java Source Files

● However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:<path_one>\sources\com\example\graphics\Rectangle.java<path_two>\classes\com\example\graphics\Rectangle.class

● By doing this, you can give the classes directory to other programmers without revealing your sources

● 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

ww

w.n

eevi

aPDF.

com

Page 615: Java_Comb

19

Class pathClass path

ww

w.n

eevi

aPDF.

com

Page 616: Java_Comb

20

What is a class path?● It is a set of directories where Java class files are

located● Java runtime searches for class files in the directories

specified in the class path in the order specified

ww

w.n

eevi

aPDF.

com

Page 617: Java_Comb

21

Setting the CLASSPATH● Now, suppose we place the package schoolClasses

under the C:\ directory.

● 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 where our classes are stored.

● Before we discuss how to set the classpath, let us take a look at an example on what will happen if we don't set the classpath. ww

w.n

eevi

aPDF.

com

Page 618: Java_Comb

22

Setting the CLASSPATH● Suppose we compile and then run the StudentRecord

class we wrote in the last section, C:\schoolClasses>javac StudentRecord.java

C:\schoolClasses>java StudentRecordException in thread "main" java.lang.NoClassDefFoundError: StudentRecord (wrong name: schoolClasses/StudentRecord) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) 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)

ww

w.n

eevi

aPDF.

com

Page 619: Java_Comb

23

Setting the CLASSPATH● To set the classpath in Windows, we type this at the

command prompt,C:\schoolClasses> set classpath=C:\– assuming C:\ is the directory in which we have placed the

packages meaning there is a directory C:\schoolClasses and there is a C:\schoolClasses\StudentRecord.class

● After setting the classpath, we can now run our program anywhere by typing,C:\schoolClasses> java schoolClasses.StudentRecordww

w.n

eevi

aPDF.

com

Page 620: Java_Comb

24

Setting the CLASSPATH● For Unix base systems, suppose we have our classes

in the directory /usr/local/myClasses, we write,

export classpath=/usr/local/myClasses

ww

w.n

eevi

aPDF.

com

Page 621: Java_Comb

25

Setting the CLASSPATH● Take note that you can set the classpath anywhere.

You can also set more than one classpath, we just have to separate them by ;(for windows) and : (for Unix based systems). For example,set classpath=C:\myClasses;D:\;E:\MyPrograms\Java

● and for Unix based systems,export classpath=/usr/local/java:/usr/myClasses

ww

w.n

eevi

aPDF.

com

Page 622: Java_Comb

1

Java ThreadsJava Threads

ww

w.n

eevi

aPDF.

com

Page 623: Java_Comb

2

Topics● What is a thread?● Thread states● Thread priorities● Thread class● Two ways of creating Java threads

– Extending Thread class– Implementing Runnable interface

● ThreadGroup● Synchronization● Inter-thread communication● Scheduling a task via Timer and TimerTask

ww

w.n

eevi

aPDF.

com

Page 624: Java_Comb

3

What is a Thread? What is a Thread?

ww

w.n

eevi

aPDF.

com

Page 625: Java_Comb

4

Threads● Why threads?

– Need to handle concurrent processes● Definition

– Single sequential flow of control within a program– For simplicity, think of threads as processes executed by

a program– Example:

● Operating System● HotJava web browser

ww

w.n

eevi

aPDF.

com

Page 626: Java_Comb

5

Threadsw

ww

.nee

viaP

DF.co

m

Page 627: Java_Comb

6

Multi-threading in Java Platform● Every application has at least one thread — or

several, if you count "system" threads that do things like memory management and signal handling

● But from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads

ww

w.n

eevi

aPDF.

com

Page 628: Java_Comb

7

Thread StatesThread States

ww

w.n

eevi

aPDF.

com

Page 629: Java_Comb

8

Thread States● A thread can in one of several possible states:

1.Running● Currently running● In control of CPU

2.Ready to run● Can run but not yet given the chance

3.Resumed● Ready to run after being suspended or block

4.Suspended● Voluntarily allowed other threads to run

5.Blocked● Waiting for some resource or event to occurww

w.n

eevi

aPDF.

com

Page 630: Java_Comb

9

Thread PrioritiesThread Priorities

ww

w.n

eevi

aPDF.

com

Page 631: Java_Comb

10

Thread Priorities

● Why priorities?– Determine which thread receives CPU control and gets

to be executed first● Definition:

– Integer value ranging from 1 to 10– Higher the thread priority → larger chance of being

executed first– Example:

● 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

ww

w.n

eevi

aPDF.

com

Page 632: Java_Comb

11

Thread Priorities

● Context switch– Occurs when a thread snatches the control of CPU from

another– When does it occur?

● Running thread voluntarily relinquishes CPU control● Running thread is preempted by a higher priority thread

● More than one highest priority thread that is ready to run– 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

ww

w.n

eevi

aPDF.

com

Page 633: Java_Comb

12

Thread ClassThread Class

ww

w.n

eevi

aPDF.

com

Page 634: Java_Comb

13

The Thread Class: Constructor

● Has eight constructors

ww

w.n

eevi

aPDF.

com

Page 635: Java_Comb

14

The Thread Class: Constants

● Contains fields for priority values

ww

w.n

eevi

aPDF.

com

Page 636: Java_Comb

15

The Thread Class: Methods

● Some Thread methods

ww

w.n

eevi

aPDF.

com

Page 637: Java_Comb

16

Two Ways of Creating Two Ways of Creating Java ThreadsJava Threadsw

ww

.nee

viaP

DF.co

m

Page 638: Java_Comb

17

Two Ways of Creating and Starting a Thread

1.Extending the Thread class2.Implementing the Runnable interface

ww

w.n

eevi

aPDF.

com

Page 639: Java_Comb

18

Extending Thread Extending Thread ClassClassw

ww

.nee

viaP

DF.co

m

Page 640: Java_Comb

19

Extending Thread Class

● The subclass extends Thread class– The subclass overrides the run() method of Thread class

● An object instance of the subclass can then be created

● Calling the start() method of the object instance starts the execution of the thread– Java runtime starts the execution of the thread by

calling run() method of object instance

ww

w.n

eevi

aPDF.

com

Page 641: Java_Comb

20

Two Schemes of starting a thread from a subclass

1.The start() method is not in the constructor of the subclass– The start() method needs to be explicitly invoked after

object instance of the subclass is created in order to start the thread

2.The start() method is in the constructor of the subclass– Creating an object instance of the subclass will start the

thread

ww

w.n

eevi

aPDF.

com

Page 642: Java_Comb

21

Scheme 1: start() method is Not in the constructor of subclass

1 class PrintNameThread extends Thread {2 PrintNameThread(String name) {3 super(name);4 }5 public void run() {6 String name = getName();7 for (int i = 0; i < 100; i++) {8 System.out.print(name);9 }10 }11 }12 //continuedw

ww

.nee

viaP

DF.co

m

Page 643: Java_Comb

22

Scheme 1: start() method needs to be called explicitly

14 class ExtendThreadClassTest1 {15 public static void main(String args[]) {16 PrintNameThread pnt1 = 17 new PrintNameThread("A");18 pnt1.start(); // Start the first thread19 PrintNameThread pnt2 = 20 new PrintNameThread("B");21 pnt2.start(); // Start the second thread22 23 }24 }w

ww

.nee

viaP

DF.co

m

Page 644: Java_Comb

23

Scheme 2: start() method is in a constructor of the subclass

1 class PrintNameThread extends Thread {2 PrintNameThread(String name) {3 super(name);4 start(); //runs the thread once instantiated5 }6 public void run() {7 String name = getName();8 for (int i = 0; i < 100; i++) {9 System.out.print(name);10 }11 }12 }13 //continuedw

ww

.nee

viaP

DF.co

m

Page 645: Java_Comb

24

Scheme 2: Just creating an object instance starts a thread

14 class ExtendThreadClassTest2 {15 public static void main(String args[]) {16 PrintNameThread pnt1 = 17 new PrintNameThread("A");18 PrintNameThread pnt2 = 19 new PrintNameThread("B");2021 }22 }

ww

w.n

eevi

aPDF.

com

Page 646: Java_Comb

25

Scheme 2: Just creating an object instance starts a thread

● Can modify main method as follows:14 class ExtendThreadClassTest3 {15 public static void main(String args[]) {16 new PrintNameThread("A");17 new PrintNameThread("B");18 }19 }

ww

w.n

eevi

aPDF.

com

Page 647: Java_Comb

26

Implementing Implementing Runnable InterfaceRunnable Interfaceww

w.n

eevi

aPDF.

com

Page 648: Java_Comb

27

Runnable Interface

● The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread

● The class must define run() method of no arguments– The run() method is like main() for the new thread

● Provides the means for a class to be active while not subclassing Thread– A class that implements Runnable can run without

subclassing Thread by instantiating a Thread instance and passing itself in as the targetww

w.n

eevi

aPDF.

com

Page 649: Java_Comb

28

Two Ways of Starting a Thread For a class that implements Runnable

1.Caller thread creates Thread object and starts it explicitly after an object instance of the class that implements Runnable interface is created– The start() method of the Thread object needs to be

explicitly invoked after object instance is created2.The Thread object is created and started within the

constructor method of the class that implements Runnable interface– The caller thread just needs to create object instances of

the Runnable classww

w.n

eevi

aPDF.

com

Page 650: Java_Comb

29

Scheme 1: Caller thread creates a Thread object and starts it explicitly

// PrintNameRunnable implements Runnable interfaceclass PrintNameRunnable implements Runnable { String name; PrintNameRunnable(String name) { this.name = name; } // Implementation of the run() defined in the // Runnable interface. public void run() { for (int i = 0; i < 10; i++) { System.out.print(name); } }}w

ww

.nee

viaP

DF.co

m

Page 651: Java_Comb

30

Scheme 1: Caller thread creates a Thread object and starts it explicitly

public class RunnableThreadTest1 { public static void main(String args[]) { PrintNameRunnable pnt1 = new PrintNameRunnable("A"); Thread t1 = new Thread(pnt1); t1.start(); }}

ww

w.n

eevi

aPDF.

com

Page 652: Java_Comb

31

Scheme 2: Thread object is created and started within a constructor

// PrintNameRunnable implements Runnable interfaceclass PrintNameRunnable implements Runnable { Thread thread; PrintNameRunnable(String name) { thread = new Thread(this, name); thread.start(); } // Implementation of the run() defined in the // Runnable interface. public void run() { String name = thread.getName(); for (int i = 0; i < 10; i++) { System.out.print(name); } }}

ww

w.n

eevi

aPDF.

com

Page 653: Java_Comb

32

Scheme 2: Thread object is created and started within a constructor

public class RunnableThreadTest2 { public static void main(String args[]) { // Since the constructor of the PrintNameRunnable // object creates a Thread object and starts it, // there is no need to do it here. new PrintNameRunnable("A"); new PrintNameRunnable("B"); new PrintNameRunnable("C"); }}

ww

w.n

eevi

aPDF.

com

Page 654: Java_Comb

33

Extending Thread Class Extending Thread Class vs. Implementing vs. Implementing

Runnable InterfaceRunnable Interfaceww

w.n

eevi

aPDF.

com

Page 655: Java_Comb

34

Extending Thread vs. Implementing Runnable Interface

● Choosing between these two is a matter of taste● Implementing the Runnable interface

– May take more work since we still ● Declare a Thread object● Call the Thread methods on this object

– Your class can still extend other class● Extending the Thread class

– Easier to implement– Your class can no longer extend any other class

ww

w.n

eevi

aPDF.

com

Page 656: Java_Comb

35

ThreadGroupThreadGroup

ww

w.n

eevi

aPDF.

com

Page 657: Java_Comb

36

ThreadGroup Class

● A thread group represents a set of threads● In addition, a thread group can also include other

thread groups– The thread groups form a tree in which every thread

group except the initial thread group has a parent● A thread is allowed to access information about its

own thread group, but not to access information about its thread group's parent thread group or any other thread groups.

ww

w.n

eevi

aPDF.

com

Page 658: Java_Comb

37

Example: ThreadGroup1 // Start three threads2 new SimpleThread("Jamaica").start();3 new SimpleThread("Fiji").start();4 new SimpleThread("Bora Bora").start();5 6 ThreadGroup group 7 = Thread.currentThread().getThreadGroup();89 Thread[] tarray = new Thread[10];10 int actualSize = group.enumerate(tarray);11 for (int i=0; i<actualSize;i++){12 System.out.println("Thread " +13 tarray[i].getName() + " in thread group "14 + group.getName());15 }

ww

w.n

eevi

aPDF.

com

Page 659: Java_Comb

38

SynchronizationSynchronization

ww

w.n

eevi

aPDF.

com

Page 660: Java_Comb

39

Race condition & How to Solve it

● Race conditions occur when multiple, asynchronously executing threads access the same object (called a shared resource) returning unexpected (wrong) results

● Example:– Threads often need to share a common resource ie a

file, with one thread reading from the file while another thread writes to the file

● They can be avoided by synchronizing the threads which access the shared resourceww

w.n

eevi

aPDF.

com

Page 661: Java_Comb

40

An Unsynchronized Example1 class TwoStrings {2 static void print(String str1, String str2) {3 System.out.print(str1);4 try {5 Thread.sleep(500);6 } catch (InterruptedException ie) {7 }8 System.out.println(str2);9 }10 }11 //continued...

ww

w.n

eevi

aPDF.

com

Page 662: Java_Comb

41

An Unsynchronized Example12 class PrintStringsThread implements Runnable {13 Thread thread;14 String str1, str2;15 PrintStringsThread(String str1, String str2) {16 this.str1 = str1;17 this.str2 = str2;18 thread = new Thread(this);19 thread.start();20 }21 public void run() {22 TwoStrings.print(str1, str2);23 }24 }25 //continued...

ww

w.n

eevi

aPDF.

com

Page 663: Java_Comb

42

An Unsynchronized Example26 class TestThread {27 public static void main(String args[]) {28 new PrintStringsThread("Hello ", "there.");29 new PrintStringsThread("How are ", "you?");30 new PrintStringsThread("Thank you ", 31 "very much!");32 }33 }

ww

w.n

eevi

aPDF.

com

Page 664: Java_Comb

43

An Unsynchronized Example● Sample output:

Hello How are Thank you there.you?very much!

ww

w.n

eevi

aPDF.

com

Page 665: Java_Comb

44

Synchronization: Locking an Object

● A thread is synchronized by becoming an owner of the object's monitor– Consider it as locking an object

● A thread becomes the owner of the object's monitor in one of three ways– Option 1: Use synchronized method – Option 2: Use synchronized statement on a common

object

ww

w.n

eevi

aPDF.

com

Page 666: Java_Comb

45

Option 1: Use synchronized method

1 class TwoStrings {2 synchronized static void print(String str1, 3 String str2) {4 System.out.print(str1);5 try {6 Thread.sleep(500);7 } catch (InterruptedException ie) {8 }9 System.out.println(str2);10 }11 }12 //continued...w

ww

.nee

viaP

DF.co

m

Page 667: Java_Comb

46

Option 1: Use synchronized method 13 class PrintStringsThread implements Runnable {14 Thread thread;15 String str1, str2;16 PrintStringsThread(String str1, String str2) {17 this.str1 = str1;18 this.str2 = str2;19 thread = new Thread(this);20 thread.start();21 }22 public void run() {23 TwoStrings.print(str1, str2);24 }25 }26 //continued...

ww

w.n

eevi

aPDF.

com

Page 668: Java_Comb

47

Option 1: Use synchronized method

27 class TestThread {28 public static void main(String args[]) {29 new PrintStringsThread("Hello ", "there.");30 new PrintStringsThread("How are ", "you?");31 new PrintStringsThread("Thank you ", 32 "very much!");33 }34 }

ww

w.n

eevi

aPDF.

com

Page 669: Java_Comb

48

Option 1: Executing Synchronized Method

● Sample output:Hello there.How are you?Thank you very much!

ww

w.n

eevi

aPDF.

com

Page 670: Java_Comb

49

Option 2: Use synchronized statement on a common object

1 class TwoStrings {2 static void print(String str1, String str2) {3 System.out.print(str1);4 try {5 Thread.sleep(500);6 } catch (InterruptedException ie) {7 }8 System.out.println(str2);9 }10 }11 //continued...

ww

w.n

eevi

aPDF.

com

Page 671: Java_Comb

50

Option 2: Use synchronized statement on a common object

12 class PrintStringsThread implements Runnable {13 Thread thread;14 String str1, str2;15 TwoStrings ts;16 PrintStringsThread(String str1, String str2, 17 TwoStrings ts) {18 this.str1 = str1;19 this.str2 = str2;20 this.ts = ts; 21 thread = new Thread(this);22 thread.start();23 }24 //continued...w

ww

.nee

viaP

DF.co

m

Page 672: Java_Comb

51

Option 2: Use synchronized statement on a common object

25 public void run() {26 synchronized (ts) {27 ts.print(str1, str2);28 }29 }30 }31 class TestThread {32 public static void main(String args[]) {33 TwoStrings ts = new TwoStrings();34 new PrintStringsThread("Hello ", "there.", ts);35 new PrintStringsThread("How are ", "you?", ts);36 new PrintStringsThread("Thank you ", 37 "very much!", ts);38 }}

ww

w.n

eevi

aPDF.

com

Page 673: Java_Comb

52

Inter-threadInter-threadSynchronizationSynchronizationw

ww

.nee

viaP

DF.co

m

Page 674: Java_Comb

53

Inter-thread Communication: Methods from Object Class

ww

w.n

eevi

aPDF.

com

Page 675: Java_Comb

54

wait() method of Object Class

● wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run

● wait() method is defined in the Object class● wait() can only be invoked from within synchronized

code● it should always be wrapped in a try block as it

throws IOExceptions● wait() can only invoked by the thread that own's the

lock on the objectww

w.n

eevi

aPDF.

com

Page 676: Java_Comb

55

wait() method of Object Class● When wait() is called, the thread becomes disabled for

scheduling and lies dormant until one of four things occur:– 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

object– another thread interrupts this thread– the specified wait() time elapses

● 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

ww

w.n

eevi

aPDF.

com

Page 677: Java_Comb

56

notify() method● Wakes up a single thread that is waiting on this

object's monitor– If any threads are waiting on this object, one of them is

chosen to be awakened– The choice is arbitrary and occurs at the discretion of the

implementation● Can only be used within synchronized code● The awakened thread will not be able to proceed

until the current thread relinquishes the lock on this object

ww

w.n

eevi

aPDF.

com

Page 678: Java_Comb

57

Inter-threadInter-threadCommunication:Communication:

Producer-Consumer Producer-Consumer ExampleExamplew

ww

.nee

viaP

DF.co

m

Page 679: Java_Comb

58

Inter-thread Communicationw

ww

.nee

viaP

DF.co

m

Page 680: Java_Comb

59

Producer-Consumer

● Imagine a scenario in which there exists two distinct threads both operating on a single shared data area

● One thread, the Producer inserts information into the data area whilst the other thread, the Consumer, removes information from that same area

● In order for the Producer to insert information into 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.

ww

w.n

eevi

aPDF.

com

Page 681: Java_Comb

60

Producer-Consumer

● For the Consumer to be able to remove information from the data area, there must be information there in the first place– The sole function of the Consumer is to remove data

from the data area● The solution of the Producer-Consumer problem

lies with devising a suitable communication protocol through which the two processes may exchange information.

● The definition of such a protocol is the main factor that makes the Producer-Consumer problem interesting in terms of concurrent systems

ww

w.n

eevi

aPDF.

com

Page 682: Java_Comb

61

Unsynchronized Producer-Consumer Example: CubbyHole.java

1 public class CubbyHole {2 private int contents;34 public int get() {5 return contents;6 }78 public synchronized void put(int value) {9 contents = value;10 }11 }

ww

w.n

eevi

aPDF.

com

Page 683: Java_Comb

62

Unsynchronized Producer-Consumer Example: Producer.java1 public class Producer extends Thread {2 private CubbyHole cubbyhole;3 private int number;45 public Producer(CubbyHole c, int number) {6 cubbyhole = c;7 this.number = number;8 }910 public void run() {11 for (int i = 0; i < 10; i++) {12 cubbyhole.put(i);13 System.out.println("Producer #" + this.number14 + " put: " + i);15 try {16 sleep((int)(Math.random() * 100));17 } catch (InterruptedException e) { }18 }19 }20 }

ww

w.n

eevi

aPDF.

com

Page 684: Java_Comb

63

Unsynchronized Producer-Consumer Example: Consumer.java

1 public class Consumer extends Thread {2 private CubbyHole cubbyhole;3 private int number;45 public Consumer(CubbyHole c, int number) {6 cubbyhole = c;7 this.number = number;8 }910 public void run() {11 int value = 0;12 for (int i = 0; i < 10; i++) {13 value = cubbyhole.get();14 System.out.println("Consumer #" + this.number15 + " got: " + value);16 }17 }18 }19

ww

w.n

eevi

aPDF.

com

Page 685: Java_Comb

64

Unsynchronized Producer-Consumer Example: Main program1 public class ProducerConsumerUnsynchronized {23 public static void main(String[] args) {4 5 CubbyHole c = new CubbyHole();67 Producer p1 = new Producer(c, 1);8 Consumer c1 = new Consumer(c, 1);910 p1.start();11 c1.start();12 }13 }w

ww

.nee

viaP

DF.co

m

Page 686: Java_Comb

65

Result of Unsynchronized Producer-Consumer

● Results are unpredictable– A number may be read before a number has been

produced – Multiple numbers may be produced with only one or two

being read

ww

w.n

eevi

aPDF.

com

Page 687: Java_Comb

66

Result of Unsynchronized Producer-Consumer

Consumer #1 got: 0Producer #1 put: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Consumer #1 got: 0Producer #1 put: 1Producer #1 put: 2Producer #1 put: 3Producer #1 put: 4Producer #1 put: 5Producer #1 put: 6Producer #1 put: 7Producer #1 put: 8Producer #1 put: 9

ww

w.n

eevi

aPDF.

com

Page 688: Java_Comb

67

Synchronized Producer-Consumer Example: CubbyHole.java

1 public class CubbyHole {2 private int contents;3 private boolean available = false;45 public synchronized int get() {6 while (available == false) {7 try {8 wait();9 } catch (InterruptedException e) { }10 }11 available = false;12 notifyAll();13 return contents;14 }15 // continued16

ww

w.n

eevi

aPDF.

com

Page 689: Java_Comb

68

Synchronized Producer-Consumer Example: CubbyHole.java

12 public synchronized void put(int value) {3 while (available == true) {4 try {5 wait();6 } catch (InterruptedException e) { }7 }8 contents = value;9 available = true;10 notifyAll();11 }12 }w

ww

.nee

viaP

DF.co

m

Page 690: Java_Comb

69

Result of Synchronized Producer-Consumer

Producer 1 put: 0Consumer 1 got: 0Producer 1 put: 1Consumer 1 got: 1Producer 1 put: 2Consumer 1 got: 2Producer 1 put: 3Consumer 1 got: 3Producer 1 put: 4Consumer 1 got: 4Producer 1 put: 5Consumer 1 got: 5Producer 1 put: 6Consumer 1 got: 6Producer 1 put: 7Consumer 1 got: 7Producer 1 put: 8Consumer 1 got: 8Producer 1 put: 9Consumer 1 got: 9

ww

w.n

eevi

aPDF.

com

Page 691: Java_Comb

70

Scheduling a task Scheduling a task via Timer & via Timer &

TimerTask ClassesTimerTask Classesww

w.n

eevi

aPDF.

com

Page 692: Java_Comb

71

Timer Class● Provides a facility for threads to schedule tasks for

future execution in a background thread● Tasks may be scheduled for one-time execution, or

for repeated execution at regular intervals.● Corresponding to each Timer object is a single

background thread that is used to execute all of the timer's tasks, sequentially

● Timer tasks should complete quickly– 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.

ww

w.n

eevi

aPDF.

com

Page 693: Java_Comb

72

TimerTask Class● Abstract class with an abstract method called run()● Concrete class must implement the run() abstract

method

ww

w.n

eevi

aPDF.

com

Page 694: Java_Comb

73

Example: Timer Classpublic class TimerReminder { Timer timer; public TimerReminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.format("Time's up!%n"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { System.out.format("About to schedule task.%n"); new TimerReminder(5); System.out.format("Task scheduled.%n"); }}

ww

w.n

eevi

aPDF.

com

Page 695: Java_Comb

74

Thank You!Thank You!

ww

w.n

eevi

aPDF.

com