it2301(JAVA).pdf

download it2301(JAVA).pdf

of 114

Transcript of it2301(JAVA).pdf

  • 8/10/2019 it2301(JAVA).pdf

    1/114

    1

    (c) venkatesh

    P.VETRIVELAN, Sr.Lecturer / CSE,N.SUNITHA , Lecturer / CSE

    Department of Computer Science and EngineeringRajalakshmi Engineering College,

    Thandalam Campus, Chennai-602105.

    Programming Paradigms -JAVA

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    2/114

    2

    (c) venkatesh

    Java - An Introduction

    Java - The new programming language from SunMicrosystemsJava -Allows anyone to publish a web page with

    Java code in itJava - CPU Independent languageCreated for consumer electronicsJava - James , Arthur Van , and others

    Java -The name that survived a patent searchOak -The predecessor of JavaJava is C++ -- ++

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    3/114

    3

    (c) venkatesh

    According to Sun, Java is...

    Simple and PowerfulObject OrientedPortable

    Architecture NeutralDistributedMulti-threadedRobust, Secure/Safe

    InterpretedHigh PerformanceDynamic pogramming language/platform.

    Buzzword compliant!http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    4/114

    4

    (c) venkatesh

    On Closer Inspection, Javais...

    SimplePurePortableSurprisingly effective

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    5/114

    5

    (c) venkatesh

    As a whole, Java is a ComprehensiveProgramming Solution

    Object OrientedPortableHigh PerformanceGeared for Distributed EnvironmentsSecure

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    6/114

    6

    (c) venkatesh

    Java as Object Oriented

    Objects all the way downSimple and Familiar: C++ LiteNo Pointers!Garbage CollectorDynamic BindingSingle Inheritance with Interfaces

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    7/1147

    (c) venkatesh

    Java as Portable

    Unlike other language compilers, Java compliergenerates code (byte codes) for UniversalMachine.

    Java Virtual Machine (JVM): Interprets bytecodesat runtimeArchitecture NeutralNo Link Phase

    Higher Level Portable Features: AWT, Unicode

  • 8/10/2019 it2301(JAVA).pdf

    8/1148

    (c) venkatesh

    Total Platform Independence

    JAVA COMPILER

    JAVA BYTE CODE

    JAVA INTERPRETER

    Windows 95 Macintosh Solaris Windows NT

    (translator)

    (same for all platforms)

    (one for each different system)

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    9/1149

    (c) venkatesh

    Java

    Write Once, Run Anywhere

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    10/11410

    (c) venkatesh

    Architecture Neutral & Portable

    Java Compiler -Java source code to bytecode Bytecode - an intermediate form, closer tomachine representation

    A virtual machine on any target platform interpretsthe bytecodePorting the java system to any new platforminvolves writing an interpreter that supports the

    Java Virtual MachineThe interpreter will figure out what the equivalentmachine dependent code to run

  • 8/10/2019 it2301(JAVA).pdf

    11/11411

    (c) venkatesh

    Java as High Performance

    JVM uses lean and mean bytecodesSmall binary class filtesJust-in-time CompilersMultithreadingNative Methods

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    12/11412

    (c) venkatesh

    Java in the World ofDistributed Computing

    Class LoaderLightweight Binary Class FilesMultithreadingDynamicGood communication constructsSecure

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    13/11413

    (c) venkatesh

    Java as Secure

    Language designed as safeStrict compilerDynamic Runtime Loading (Verifier)Runtime Security Manager

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    14/11414

    (c) venkatesh

    Object Oriented Languages-a Comparison

    Feature C++ ObjectiveC Ada Java

    Encapsulation Yes Yes Yes YesInheritance

    Yes Yes No YesMultiple Inherit. Yes Yes No NoPolymorphism Yes Yes Yes YesBinding (Early/Late) Both Both Early LateConcurrency

    Poor Poor Difficult YesGarbage Collection No Yes No YesGenericity Yes No Yes NoClass Libraries Yes Yes Limited Yes

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    15/11415

    (c) venkatesh

    Java better than C++ ?

    No Typedefs, Defines, or PreprocessorNo Global VariablesNo Goto statementsNo PointersNo Unsafe StructuresNo Multiple InheritanceNo Operator OverloadingNo Automatic CoercionsNo Fragile Data Types

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    16/11416

    (c) venkatesh

    Basic Data Types

    Typesboolean either true of falsechar 16 bit Unicode 1.1

    byte 8-bit integer (signed)short 16-bit integer (signed)int 32-bit integer (signed)long 64-bit integer (singed)float 32-bit floating point (IEEE 754-1985)double 64-bit floating point (IEEE 754-1985)

    String (class for manipulating strings)Java uses Unicode to represent characters

    internally

  • 8/10/2019 it2301(JAVA).pdf

    17/11417

    (c) venkatesh

    Two Types of JavaApplications

    Different ways to write/run a Java codes are:Application - A stand-alone program that can be

    invoked from command line . A program that

    has a main methodApplet - A program embedded in a web page ,

    to be run when the page is browsed . Aprogram that contains no main method

    Application -Java interpreterApplets - Java enabled web browser (Linked toHTML via tag. in html file)

  • 8/10/2019 it2301(JAVA).pdf

    18/11418

    (c) venkatesh

    JavaBytecodes

    move locallyor through

    network

    JavaSource(.java)

    JavaCompiler

    JavaBytecode(.class )

    JavaInterpreter

    Just inTime

    Compiler

    Runtime System

    ClassLoader

    BytecodeVerifier

    JavaClass

    Libraries

    Operating System

    Hardware

    JavaVirtualmachine

    RuntimeEnvironmentCompile-timeEnvironment

    Java Environment/Life Cycle of Java Code

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    19/11419

    (c) venkatesh

    Java Development Kit

    javac - The Java Compiler java - The Java Interpreter

    jdb- The Java Debuggerappletviewer -Tool to run the applets

    javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    20/11420

    (c) venkatesh

    Hello Internet

    // hello.java: Hello Internet program

    class HelloInternet{

    public static void main(String args[]){

    System.out.println(Hello Internet);

    }}

  • 8/10/2019 it2301(JAVA).pdf

    21/114

    21

    (c) venkatesh

    Lifecycle of Java Code

  • 8/10/2019 it2301(JAVA).pdf

    22/114

    22

    (c) venkatesh

    Bytecode Verifier

    Called when class is first loaded in runtimeenvironmentVerifies bytecodes meet certain set of properties

    Verifier uses Theorem ProverVerified code runs fasterAfter verification, interpreter defines memorylayout

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    23/114

    23

    (c) venkatesh

    Class Loader

    Unique Namespace for each originLocal namespace classes are called built - insPrevents class spoofing

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    24/114

    24

    (c) venkatesh

    Security Manager

    Prevents unauthorized disk read/writesRestricts network accessOther access restrictions (native methods)Implementation is browser dependent

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    25/114

    25

    (c) venkatesh

    General Language Features

    C/C++ like syntaxNo pointersObjects all the way downObjects request services of other objects throughmessagesMessages result in invocation of class methods

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    26/114

  • 8/10/2019 it2301(JAVA).pdf

    27/114

    27

    (c) venkatesh

    Added or Improved over C++

    Interfaces: type Vs. classGarbage collectionExceptions (More powerful than C++)

    StringsInstanceofPackageMulti-threads

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    28/114

    28

    (c) venkatesh

    Rich Object Environment

    Core ClasseslanguageUtilities

    Input/OutputLow-Level NetworkingAbstract Graphical User Interface

    Internet ClassesTCP/IP NetworkingWWW and HTMLDistributed Programs

  • 8/10/2019 it2301(JAVA).pdf

    29/114

    29

    (c) venkatesh

    Main Packages

    java.lang java.util

    java.io java.awt java.awt.image

    java.applet java.net

  • 8/10/2019 it2301(JAVA).pdf

    30/114

    30

    (c) venkatesh

    Java Fundamentals

    ConstructsGraphicsMultithreading

    Streams and NetworkingNetworking

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    31/114

    31

    (c) venkatesh

    What is Java ?

    A programming language:

    Object oriented (no friends, all functions aremembers of classes, no function libraries -- justclass libraries)

    simple (no pointer arithmetic, no need for programmer to deallocate memory)

    platform independent dynamic interpreted

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    32/114

    32

    (c) venkatesh

    Types

    Eight basic types

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

    String s;

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    33/114

    33

    (c) venkatesh

    Classes and objects

    declaring a class

    class MyClass {member variables;

    member functions () ;

    } // end class MyClass

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    34/114

    34

    (c) venkatesh

    Java programs

    Two kinds

    Applications have main() run from the OS prompt

    Applets have init(), start(), stop(), paint(), update(), repaint(),

    destroy() run from within a web page

  • 8/10/2019 it2301(JAVA).pdf

    35/114

    35

    (c) venkatesh

    The first Java Application

    class MyApp {public static void main(String s [ ] ) {

    System.out.println(Hello World);

    }} // end class MyApp

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    36/114

    36

    (c) venkatesh

    Declaring and creatingobjects

    declare a reference

    String s;

    create/define an object

    s = new String (India);

    India

  • 8/10/2019 it2301(JAVA).pdf

    37/114

    37

    (c) venkatesh

    Arrays (are objects in Java)

    declare

    int a [ ] ; // 1-dim int [ ] b ; // 1-dim

    int [ ] c [ ]; // 2-dim int c [ ][]; // 2-dimallocate space

    a = new int [7]; c = new int [7][11];

  • 8/10/2019 it2301(JAVA).pdf

    38/114

    38

    (c) venkatesh

    Arrays have length

    used to retrieve the size of an array

    int a [ ] = new int [7]; // 1-dim System.out.println(a.length); will print 7

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

    System.out.println(a.length); will print 7 System.out.println(b.length * b[0].length); will

    print 77

  • 8/10/2019 it2301(JAVA).pdf

    39/114

    39

    (c) venkatesh

    this is because

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

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

    array[3][5][2].length is 7 x 11 x 10 x 21

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    40/114

    40

    (c) venkatesh

    Constructors

    All objects are created through constructorsThey are invoked automatically

    class Weight {

    int lb; int oz;public Weight (int a, int b ) {

    lb = a; oz = b;}

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    41/114

    41

    (c) venkatesh

    this keyword

    refers to this object (object in which it is used)usage:

    with an instance variable or method of thisclass

    as a function inside a constructor of this class as this object, when passed as parameter

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    42/114

    42

    (c) venkatesh

    this :: with a variable

    refers to this objects data memberclass Weight {

    int lb; int oz;public Weight (int lb, int oz ) {

    this.lb = lb; this.oz = oz;}

    }

  • 8/10/2019 it2301(JAVA).pdf

    43/114

    43

    (c) venkatesh

    this :: with a method

    refers to another method of this classclass Weight {

    public int m1 (int a) {int x = this.m2(a); return x;

    }public int m2(int b) { return b*7 ; }}

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    44/114

    44

    (c) venkatesh

    this :: as a function inside a constructor of thisclass

    must be used with a constructorclass Weight {

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

    }

    Constructor is also overloaded (Java allowsoverloading of all methods, including constructors)

  • 8/10/2019 it2301(JAVA).pdf

    45/114

    45

    (c) venkatesh

    this :: as this object, when passed asparameter

    refers to the object that used to call the callingmethod

    class MyApp {

    int a;

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

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

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

  • 8/10/2019 it2301(JAVA).pdf

    46/114

    46

    (c) venkatesh

    static keyword

    means global --all all objects refer to the samestorage.applies to variables or methods

    usage: with an instance variable of a class with a method of a class

    i k d ( i h

  • 8/10/2019 it2301(JAVA).pdf

    47/114

    47

    (c) venkatesh

    static keyword (withvariables)

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

    public static void main(String [] s ) {PurchaseOrder po1 = new PurchaseOrder();

    po1.updatePOCount();}

    public void updatePOCount() { POCount++; }}

    http://www.vidyarthiplus.com

    i k d ( /

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    48/114

    48

    (c) venkatesh

    static keyword (w/methods)

    class Math { public static double sqrt(double x) {

    // calculatereturn result;

    }}class MyApp {

    public static void main(String [] s ) {

    double dd;dd = Math.sqrt(7.11);

    }}

  • 8/10/2019 it2301(JAVA).pdf

    49/114

    49

    (c) venkatesh

    Inheritance (subclassing)

    class Employee {

    protected String name;

    protected double salary;

    public void raise(double dd) {

    salary += salary * dd/100;

    }

    public Employee ( ) { }

    }

  • 8/10/2019 it2301(JAVA).pdf

    50/114

    50

    (c) venkatesh

    sub/derived-class ofEmployee

    class Manager extends Employee {

    private double bonus;

    public void setBonus(double bb) {

    bonus = salary * bb/100;

    }

    public Manager ( ) { }

    }

  • 8/10/2019 it2301(JAVA).pdf

    51/114

    51

    (c) venkatesh

    Overriding (methods)

    class Manager extends Employee {

    private double bonus;

    public void setBonus(double bb) { }

    public void raise(double dd) {

    salary += salary * dd/100 + bonus;

    }

    public Manager ( ) { }

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    52/114

    52

    (c) venkatesh

    class First { public First() { System.out.println ( First class ); }

    } public class Second extends First {

    public Second() { System.out.println (Second class); }

    } public class Third extends Second { public Third() {System.out.println (Third class);}

    }

    Inheritance and Constructors

    First class

    Second classThird class

    Topmost class constructor is invoked first

    (like us grandparent -->parent-->child->)

  • 8/10/2019 it2301(JAVA).pdf

    53/114

    53

    (c) venkatesh

    access modifiers

    private same class onlypublic

    everywhereprotected

    same class, same package, any subclass(default)

    same class, same package

  • 8/10/2019 it2301(JAVA).pdf

    54/114

    54

    (c) venkatesh

    super keyword

    refers to the superclass (base class)usage:

    with a variable or method (mostcommon with a method) as a function inside a constructor of the

    subclass

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    55/114

    55

    (c) venkatesh

    super :: with a method

    class Manager extends Employee {

    private double bonus;

    public void setBonus(double bb) { }

    public void raise(double dd) { //overrides raise() ofEmployee

    super.raise(dd); // call Employees raise()

    salary += bonus;

    }

    public Manager ( ) { }

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    56/114

    56

    (c) venkatesh

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

    class Manager extends Employee {

    private double bonus;

    public void setBonus(double bb) { }

    public Manager ( String name, double salary, double bonus ) {super(name, salary);

    this.bonus = bonus;

    }

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    57/114

    57

    (c) venkatesh

    final keyword

    means constantapplies to

    variables (makes a var. constant), or methods (makes a method non-

    overridable), or classes (makes a class non-subclassable

    means objects cannot be created ).

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    58/114

    58

    (c) venkatesh

    final keyword with a variable

    class Math {

    public final double pi = 3.1412;

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

    }}

    note: variable pi is made read -only

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    59/114

    fi l l

  • 8/10/2019 it2301(JAVA).pdf

    60/114

    60

    (c) venkatesh

    final keyword with a class

    final class Employee { protected String name; protected double salary;

    public void raise(double dd) {salary += salary * dd/100;

    }

    public Employee ( ) { }}then: cannot create class Manager as asubclass of class Employee ( all are equal)

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    61/114

    61

    (c) venkatesh

    abstract classes and interfaces

    abstract classes

    may have both implemented and non-implemented methods

    interfaces

    have only non-implemented methods(concrete classes)

    have all their methods implemented

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    62/114

    62

    (c) venkatesh

    sample abstract class

    abstract class TwoDimensionalGeoFigure { public abstract double area(); public abstract double perimeter(); public abstract void printInfo();

    public void setOutlineColor(Color cc) {// code to set the color

    } public void setInsideColor(Color cc) {

    // code to set the color }

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    63/114

    63

    (c) venkatesh

    sample interface

    interface ResponceToMouseClick { public void mouseDown(); public void mouseUp(); public void mouseDoubleClick();

    }

    class ConcreteMouseClick implementsResponseToMouse Click {// all above methods implemented here

    }

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    64/114

    64

    (c) venkatesh

    Exceptions (error handling)

    code without exceptions:...

    int a = 7, b = 0, result;if ( b != 0) {result = a/b;

    }else {

    System.out.println(b is zero);}...

    code with exceptions:...int a = 7, b = 0, result;try {

    result = a/b;}catch (ArithmeticException e ) {

    System.out.println(b is zero);}

    ...

    A nice way to handle errors in Java programs

  • 8/10/2019 it2301(JAVA).pdf

    65/114

    65

    (c) venkatesh

    Exceptions (contd)...int a = 7, b = 0, result;try {

    result = a/b;/// more code .. reading from a file

    }catch (ArithmeticException e ) {

    System.out.println(b is zero);}catch (IOException e ) {

    System.out.println(Cant read);

    }finally {

    Sysytem.out.println(Closing file);/// code to close file

    }

    ...http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    66/114

    66

    (c) venkatesh

    methods throwing exceptions

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

    if (y == 0 ) {

    throw new ArithmeticException();}else {

    return a/b ;

    }} // end divide()

    http://www.vidyarthiplus.com

    Defining your own exceptions

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    67/114

    67

    (c) venkatesh

    Defining your own exceptions

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

    if (y == 0 ) {throw new MyException();

    }

    else {return a/b ;

    }} // end divide()

    class MyException extends ArithmeticException{}frm

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    68/114

    68

    (c) venkatesh

    GUI Programming in Java(AWT and Event Handling)

    http://www.vidyarthiplus.com

    AWT - Abstract Windowing

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    69/114

    69

    (c) venkatesh

    AWT Abstract WindowingToolkit

    Single Windowing Interface on Multiple PlatformsSupports functions common to all window systemsUses Underlying Native Window system

    AWT providesGUI widgetsEvent HandlingContainers for widgetsLayout managersGraphic operations

    http://www.vidyarthiplus.com

    AWT - Abstract Window

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    70/114

    70

    (c) venkatesh

    AWT Abstract WindowToolkit

    Portable GUI - preserves native look & feelStandard GUI Components (buttons)Containers - Panels, Frames, Dialogs

    Graphics class for custom drawingLayouts responsible for actual positioning ofcomponents:

    BorderLayout, GridLayout, FlowLayout, null

    layoit

    http://www.vidyarthiplus.com

    Adding Components via

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    71/114

    71

    (c) venkatesh

    Adding Components viaLayouts

    setLayout(new BorderLayout());// Add text field to topadd("North",new TextField());// Create the panel with buttons at the bottom...Panel p = new Panel(); // FlowLayout

    p.add(new Button("OK")); p.add(new Button("Cancel"));

    add("South",p);

    http://www.vidyarthiplus.com

    Adding Components via

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    72/114

    72

    (c) venkatesh

    Adding Components viaLayouts

    http://www.vidyarthiplus.com

    B ildi G hi l U I f

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    73/114

    73

    (c) venkatesh

    Building Graphical User Interfaces

    import java.awt.*;Assemble the GUI

    use GUI components, basic components (e.g., Button, TextField) containers (Frame, Panel)

    set the positioning of the components

    use Layout ManagersAttach events

    http://www.vidyarthiplus.com

    A l GUI

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    74/114

    74

    (c) venkatesh

    A sample GUI program

    Import java.awt.*;class MyGui {

    public static void main(String [] s ) {Frame f = new Frame (My Frame);Button b = new Button(OK);TextField tf = new TextField(George, 20);

    f.setLayout(new FlowLayout());f.add(b);

    f.add(tf);f.setSize(300, 300);f.setVisible(true);

    }}

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    75/114

    75

    (c) venkatesh

    output

    http://www.vidyarthiplus.com

    E

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    76/114

    76

    (c) venkatesh

    Events

    b.addActionListener ( );

    method to add a listener listener objectButton

    f.addWindowListener ( );

    Frame

    http://www.vidyarthiplus.com

    Events

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    77/114

    77

    (c) venkatesh

    Events

    Each GUI component (e.g., a Button) that wishes torespond to an event type (e.g., click), must register anevent handler, called a Listener.The listener is an object of a "Listener" interface.A Listener class can be created by subclassing (through"implements") one of Listener interfaces (all listenerinrefaces are in the java.awt.event package = > mustimport java.awt.event.*; )The registration of the listener is done by a call to amethod such as addActionListener().Each GUI component class has one or more suchadd() methods, where applicable.

    http://www.vidyarthiplus.com

    Li t I t f

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    78/114

    78

    (c) venkatesh

    Listener Interfaces

    INTERFACE NAME (IN JAVA.AWT.EVENT )[1] ActionListener [2] ItemListener [3] MouseMotionListener [4] MouseListener [5] KeyListener [6] FocusListener [7] AdjustmentListener

    [8] ComponentListener [9] WindowListener [10] ContainerListener [11] TextListener

    http://www.vidyarthiplus.com

    Li t I t f

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    79/114

    79

    (c) venkatesh

    Listener Interfaces

    Each listener interface has methods that need to beimplemented for handling different kinds of events.

    1) mouseDragged (MouseEvent) - Invoked when a mouse

    button is pressed on a component and then dragged.2) mouseMoved (MouseEvent) - Invoked when the mouse

    button has been moved on a component (with no buttonsdown).

    For example, the MouseMotionListener interface has twomethods:

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    80/114

    80

    (c) venkatesh

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

    ... the WindowListener interface has seven methods:

    How to create an object of

  • 8/10/2019 it2301(JAVA).pdf

    81/114

    81

    (c) venkatesh

    ja listener interface ?

    Interfaces cannot be instantiated.

    Therefore, cannot do new WindowListener();

    Instead, have to subclass the interface and then createobject of the subclass

    Implementing the ActionListener Interfaced hi h dl b

  • 8/10/2019 it2301(JAVA).pdf

    82/114

    82

    (c) venkatesh

    and attaching an event handler to a button

    class MyApp implements ActionListener {Button b = new Button(OK);

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

    } public void go() {

    b.addActionListener( this );}

    public void actionPerformed(ActionEvent e ) {// what to do when the button is clicked

    if( e.getSource() == b ){ System.out.println(OK pressed"); }

    }}

    Implementing 2 interfaces

  • 8/10/2019 it2301(JAVA).pdf

    83/114

    83

    (c) venkatesh

    class MyApp implements ActionListener, WindowListener {Button b = new Button(OK);Frame f = new Frame(My Frame);

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

    b.addActionListener( this );f.addWindowListener( this );

    } public void actionPerformed(ActionEvent e ) { } public void windowActivated(WindowEvent e ) { } public void windowClosed(WindowEvent e ) { } public void windowClosing(WindowEvent e ) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { }

    }

    Implementing 2 interfaces

    or use Adapters

  • 8/10/2019 it2301(JAVA).pdf

    84/114

    84

    (c) venkatesh

    or use Adapters

    class MyApp extends WindowAdapter {Button b = new Button(OK);Frame f = new Frame(My Frame);

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

    f.addWindowListener( this );}

    public void windowClosing(WindowEvent e ) { }}

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

    But, we can only use one Adapter at a time (no multiplei h it )

  • 8/10/2019 it2301(JAVA).pdf

    85/114

    85

    (c) venkatesh

    inheritance)

    I.e., cannot have :

    class MyApp extends WindowAdapter,

    MouseAdapter, ... { ...

    }http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    86/114

    86

    (c) venkatesh

    However can use inner classes instead !!!

    class MyApp {Button b = new Button(OK);Frame f = new Frame(My Frame);

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

    public void go() {f.addWindowListener( new FrameHandler() );

    b.addMouseListener( new ButtonHandler() );}class ButtonHandler extends MouseAdapter {

    public void mousePressed (MouseEvent e ) { }}class FrameHandler extends WindowAdapter {

    public void windowClosing (WindowEvent e ) { }}

    }

    Popup Menu and Event Handling...

  • 8/10/2019 it2301(JAVA).pdf

    87/114

    87

    (c) venkatesh//popup.java: popup menu and event handling

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

    public class popup extends Frame implements ActionListener, MouseListener{

    TextField text1;

    PopupMenu popup; MenuItem menuitem1, menuitem2, menuitem3; public popup()

    {super( "Popup Menu" );setLayout(new FlowLayout());setBounds(10, 10, 300, 200 );setVisible(true);init();

    } public void init()

    { popup = new PopupMenu("Resource Usage" );

    http://www.vidyarthiplus.com

    Popup Menu and Event Handling...

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    88/114

    88

    (c) venkatesh

    Popup Menu and Event Handling...

    menuitem1 = new MenuItem("CPU");

    menuitem1.addActionListener(this); menuitem2 = new MenuItem("Disk"); menuitem2.addActionListener(this); menuitem3 = new MenuItem("Memory"); menuitem3.addActionListener(this); popup.add(menuitem1);

    popup.add(menuitem2); popup.add(menuitem3);add(popup);text1 = new TextField(20);text1.setBounds(20, 40, 120, 30 );add(text1);addMouseListener(this);

    } public void mousePressed(MouseEvent e )

    {if( e.getModifiers() != 0 )

    popup.show(this, e.getX(), e.getY() );}

    http://www.vidyarthiplus.com

    Popup Menu and Event Handling

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    89/114

    89

    (c) venkatesh

    opup e u a d ve t a d g

    public void mouseReleased( MouseEvent e ){ System.out.print("Mouse Released\n" ); }

    public void mouseEntered( MouseEvent e ){ System.out.print("Mouse Entered\n" ); }

    public void mouseExited( MouseEvent e ){ System.out.print("Mouse Exited\n" ); }

    public void actionPerformed( ActionEvent e )

    {if( e.getSource() == menuitem1 ){ text1.setText("CPU"); }if( e.getSource() == menuitem2 ){ text1.setText("Disk"); }if( e.getSource() == menuitem3 )

    { text1.setText("Memory"); }}

    public static void main( String args[] ){

    popup p = new popup();}

    }http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    90/114

    90

    (c) venkatesh

    Multithreading in Java(A built-in feature in Java)

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    91/114

    Threads

  • 8/10/2019 it2301(JAVA).pdf

    92/114

    92

    (c) venkatesh

    Threads

    Java has built in thread support for MultithreadingSynchronizationThread Scheduling

    Inter-Thread Communication:currentThread start setPriorityyield run getPrioritysleep stop suspend

    resumeJava Garbage Collector is a low-priority thread

    Th d

  • 8/10/2019 it2301(JAVA).pdf

    93/114

    93

    (c) venkatesh

    Thread states

    new

    runnable non-runnable

    dead

    wait()sleep()suspend()

    blocked

    notify()sleptresume()unblocked

    start()

    stop()

    http://www.vidyarthiplus.com

    Threading Mechanisms

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    94/114

    94

    (c) venkatesh

    Threading Mechanisms...

    Create a class that extends the Thread classCreate a class that implements the Runnable interface

    http://www.vidyarthiplus.com

    1st method: Extending Thread class

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    95/114

    95

    (c) venkatesh

    1st method: Extending Thread class

    1st Method: Extending the Thread classclass MyThread extends Thread {

    public void run(){

    // thread body of execution}

    }Creating thread:

    MyThread thr1 = new MyThread();Start Execution:

    thr1.start();

    http://www.vidyarthiplus.com

    An example

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    96/114

    96

    (c) venkatesh

    An example

    class MyThread extends Thread { // the thread public void run () {

    System.out.println(" this thread is running ... ");}

    } // end class MyThread

    class ThreadEx2 { // a program that utilizes the thread public static void main(String [] args ) {

    // note, the created object myThreadObject IS A Thread as well.MyThread t = new MyThread();

    // due to extending the Thread class (above)// I can call start(), and this will call// run(). start() is a method in class Thread.

    t.start();} // end main()

    } // end class ThreadEx2

    http://www.vidyarthiplus.com

    2nd method: Threads by implementingR bl i f

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    97/114

    97

    (c) venkatesh

    Runnable interface

    class MyThread implements Runnable{

    ..... public void run()

    {

    // thread body of execution}

    }

    Creating Object: MyThread myObject = new MyThread();

    Creating Thread Object:Thread thr1 = new Thread( myObject );

    Start Execution:thr1.start();

    http://www.vidyarthiplus.com

    An example

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    98/114

    98

    (c) venkatesh

    An example

    class MyThread implements Runnable { public void run() {

    System.out.println(" this thread is running ... ");}

    } // end class MyThread

    class ThreadEx21 { public static void main(String [] args ) {

    Thread t = new Thread(new MyThread());// due to implementing the Runnable interface

    // I can call start(), and this will call run().t.start();

    } // end main()} // end class ThreadEx2

    A program with two threads

  • 8/10/2019 it2301(JAVA).pdf

    99/114

    99

    (c) venkatesh

    class MyThread implements Runnable { public void run() { System.out.println("This is 'MyThread' ); }}

    class YourThread implements Runnable {

    public void run() { System.out.println("This is 'YourThread'); }}

    class ThreadEx4 { public static void main(String [] args ) {

    Thread t1 = new Thread(new MyThread());Thread t2 = new Thread(new YourThread());t1.start();t2.start();

    }} // end class ThreadEx4

    Monitor model (for Syncronisation)

  • 8/10/2019 it2301(JAVA).pdf

    100/114

    100

    (c) venkatesh

    ( y )

    Method 1

    Method 2

    Block 1Key

    Threads

    Monitor (synchronised) solves race-condition problem

    examples :: program with two threads and shared object

  • 8/10/2019 it2301(JAVA).pdf

    101/114

    101

    (c) venkatesh

    class MyThread implements Runnable {Shared so;

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

    } // end class MyThread

    class YourThread implements Runnable {Shared so; public YourThread (Shared s) { so = s; } public void run() { so.method2(); }

    } // end class YourThread

    class HerThread implements Runnable {Shared so;

    public HerThread (Shared s) { so = s; } public void run() {so.method3(); }

    } // end class HerThread

    so

    the monitor (shared object)

  • 8/10/2019 it2301(JAVA).pdf

    102/114

    102

    (c) venkatesh

    class Shared { // the 'monitor'

    // if 'synchronized' is removed, the outcome is unpredictable public synchronized void method1( ) {

    for (int i = 0; i < 200; i++) { System.out.print(" [1] :: " + i ) ; }}

    // if the 'synchronized' is removed, the outcome is unpredictable public synchronized void method2( ) {

    for (int i = 0; i < 200; i++) { System.out.print(" [2] :: " + i ) ; }}

    // if the 'synchronized' is removed, the outcome is unpredictable public synchronized void method3( ) {

    for (int i = 0; i < 200; i++) { System.out.print(" [3] :: " + i ) ; }}

    } // end class Shared

    the driver

  • 8/10/2019 it2301(JAVA).pdf

    103/114

    103

    (c) venkatesh class MyMainClass { public static void main(String [] args ) {

    Shared sharedObject = new Shared ();Thread t1 = new Thread(new MyThread( sharedObject ));Thread t2 = new Thread(new YourThread( sharedObject ));

    Thread t3 = new Thread(new HerThread( sharedObject ));

    t1.start();t2.start();t3.start();

    } // end main()

    } // end class ThreadEx5

    http://www.vidyarthiplus.com

    Threads in Action...Cooperative threads - File Copy

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    104/114

    104

    (c) venkatesh

    Cooperative threads - File Copy

    reader(){

    - - - - - - - - --lock(buff[i]);read(src,buff[i]);unlock(buff[i]);- - - - - - - - --

    }

    writer(){

    - - - - - - - - - -lock(buff[i]);

    write(src,buff[i]);unlock(buff[i]);- - - - - - - - - -

    }

    buff[0]

    buff[1]

    Cooperative Parallel SynchronizedThreads

    http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    105/114

    105

    (c) venkatesh

    Streams and I/O

    http://www.vidyarthiplus.com

    Streams and I/O

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    106/114

    106

    (c) venkatesh

    Streams and I/O

    basic classes for file IO

    FileInputStream, for reading from a file FileOutputStream, for writing to a fileExample:

    Open a file "myfile.txt" for readingFileInputStream fis = new FileInputStream("myfile.txt");

    Open a file "outfile.txt" for writingFileOutputStream fos = new FileOutputStream ("myfile.txt");

    http://www.vidyarthiplus.com

    Display File Contents

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    107/114

    107

    (c) venkateshimport java.io.*;

    public class FileToOut1 { public static void main(String args[]) {

    try {FileInputStream infile = new FileInputStream("testfile.txt");

    byte buffer[] = new byte[50];int nBytesRead;do {

    nBytesRead = infile.read(buffer);System.out.write(buffer, 0, nBytesRead);

    } while (nBytesRead == buffer.length);}

    catch (FileNotFoundException e) {System.err.println("File not found");

    }catch (IOException e) { System.err.println("Read failed"); }

    }}

    Filters

  • 8/10/2019 it2301(JAVA).pdf

    108/114

    108

    (c) venkatesh

    Once a stream (e.g., file) has been opened, we canattach filtersFilters make reading/writing more efficientMost popular filters: For basic types:

    DataInputStream , DataOutputStream For objects:

    ObjectInputStream , ObjectOutputStream

    Writing data to a file using Filters

  • 8/10/2019 it2301(JAVA).pdf

    109/114

    109

    (c) venkateshimport java.io.*;

    public class GenerateData { public static void main(String args[]) {try {

    FileOutputStream fos = new FileOutputStream("stuff.dat");DataOutputStream dos = new DataOutputStream(fos);dos.writeInt(2);

    dos.writeDouble(2.7182818284590451);dos.writeDouble(3.1415926535);dos.close(); fos.close();

    }catch (FileNotFoundException e) {

    System.err.println("File not found");}catch (IOException e) {

    System.err.println("Read or write failed");}

    }

    }

    Reading data from a file usingfilters

  • 8/10/2019 it2301(JAVA).pdf

    110/114

    110

    (c) venkatesh

    filters

    import java.io.*; public class ReadData {

    public static void main(String args[]) {try {

    FileInputStream fis = new FileInputStream("stuff.dat");DataInputStream dis = new DataInputStream(fis);int n = dis.readInt();

    System.out.println(n);for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble());}dis.close(); fis.close();

    }catch (FileNotFoundException e) {

    System.err.println("File not found");}catch (IOException e) { System.err.println("Read or write failed");}

    }

    }

    Object serialization

  • 8/10/2019 it2301(JAVA).pdf

    111/114

    111

    (c) venkatesh

    Write objects to a file, instead of writing primitive types.

    Use the ObjectInputStream ,ObjectOutputStream classes, the same waythat filters are used.

    http://www.vidyarthiplus.com

    Write an object to a file

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    112/114

    112

    (c) venkateshimport java.io.*;

    import java.util.*; public class WriteDate { public WriteDate () {

    Date d = new Date();try {

    FileOutputStream f = new FileOutputStream("date.ser");ObjectOutputStream s = new ObjectOutputStream (f);s.writeObject (d);s.close ();

    }catch (IOException e) { e.printStackTrace(); }

    public static void main (String args[]) {new WriteDate ();

    }}

    http://www.vidyarthiplus.com

    Read an object from a file

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    113/114

    113

    (c) venkatesh import java.util.*; public class ReadDate {

    public ReadDate () {Date d = null;ObjectInputStream s = null;try { FileInputStream f = new FileInputStream ("date.ser");

    s = new ObjectInputStream (f);} catch (IOException e) { e.printStackTrace(); }try { d = (Date) s.readObject (); }catch (ClassNotFoundException e) { e.printStackTrace(); }catch (InvalidClassException e) { e.printStackTrace(); }catch (StreamCorruptedException e) { e.printStackTrace(); }catch (OptionalDataException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }System.out.println ("Date serialized at: "+ d);

    } public static void main (String args[]) { new ReadDate (); }

    }http://www.vidyarthiplus.com

    http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/http://www.vidyarthiplus.com/
  • 8/10/2019 it2301(JAVA).pdf

    114/114