java notes of25sessions

Upload: sourav-sharma

Post on 03-Apr-2018

242 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Java Notes Of25sessions

    1/318

  • 7/29/2019 Java Notes Of25sessions

    2/318

    OOP Definition

    Concepts of Classes and objects

    OOPs Features

    2

    Encapsulation / Data HidingAbstraction

    Inheritance

    Polymorphism

    Dynamic Binding

    Message Passing

    Contents of this session

  • 7/29/2019 Java Notes Of25sessions

    3/318

    OOP is a programming methodology that helps to organizea complex programs through the use of inheritance,encapsulation and polymorphism

    To access the class, we need an instance which can createan logical interface in between class & user (through mainfunction). Such instance is termed as Object. That why thisnew paradigm is termed as Object Oriented ProgrammingParadigm

    3

  • 7/29/2019 Java Notes Of25sessions

    4/318

    OOP increasing the flexibility in coding without disturbingthe other part of the code

    OOP increasing the software development speed by reusing &enhancing the existing code

  • 7/29/2019 Java Notes Of25sessions

    5/318

    An object is like ablack box.

    The internal detailsare hidden.

    Identifying objectsand assigningresponsibilitiesto these objects.

    Objects communicate to otherobjects by sending messages.

    Messages are received by themethodsof an object

    5

  • 7/29/2019 Java Notes Of25sessions

    6/318

    Everything in the world is an object.

    For example-

    Real world objects share two characteristics: They all havestate(attributes)and behavior (action). Dogs have state(name,color etc) and behavior (barking, wagging tails etc).

  • 7/29/2019 Java Notes Of25sessions

    7/318

    Tangible Things as a car, printer, ...

    Roles as employee, boss, ...

    Incidents as flight, overflow, ...

    Specifications as colour, shape,

    7

  • 7/29/2019 Java Notes Of25sessions

    8/318

    An object represents an individual, identifiable item, unit, or

    entity, either real or abstract, with a well-defined role in the

    problem domain.Or

    An "object" is anything to which a concept applies.

    Etc.

    8

  • 7/29/2019 Java Notes Of25sessions

    9/318

    Defining ClassA CLASS is a template (specification, blueprint)for a collection of objects that share a commonset of attributes and operations.

    HealthClubMemberClass

    Objects

    attributesoperations

  • 7/29/2019 Java Notes Of25sessions

    10/31810

    Class & Instance

  • 7/29/2019 Java Notes Of25sessions

    11/318

    Class defines a new data types

    Once defined, this new type can be used to create objects ofthat type

    Class is a template for an object and, an object is an instanceof a class

    The data or variables, defined within a class are calledinstance variables The code is contained within methods Collectively, the methods and variables defined within a class

    are called members of a class

    11

  • 7/29/2019 Java Notes Of25sessions

    12/318

    Furniture

    ChairTable Book self Common Behavior:

    Keeping something

    RealLife Object: State-Variable

    Behavior-method

    Example:-

  • 7/29/2019 Java Notes Of25sessions

    13/318

    Modularity - large software projects can be split up insmaller pieces.

    Reusability - Programs can be assembled from pre-written software components.

    Extensibility - New software components can be writtenor developed from existing ones.

    13

  • 7/29/2019 Java Notes Of25sessions

    14/318

    Features of 100% OOP Languages:1) Encapsulation / DataHiding

    2) Abstraction

    3) Inheritance4) Polymorphism

    5) Dynamic Binding

    6) Message Passing

  • 7/29/2019 Java Notes Of25sessions

    15/318

    ENCAPSULATION / DATAHIDINGABSTRACTION

    ENCAPSULATION Binding or Wrapping of the data andmethods into a single unit is called Encapsulation.

    Encapsulation is used to hide data or protectdata from outside access. So this concept is also called data-hiding.

    ABSTRACTION Abstraction refers to the act of representingessential features without including the background detailsand explanation.

    explanationthe capsule cures the patient.. But the patientdont know what is capsulated inside the capsule..

    CAPSULEMEDICINE INSIDE THE CAP

  • 7/29/2019 Java Notes Of25sessions

    16/318

    16

    Encapsulation ensures that data within an object isprotected; it can be accessed only by its methods

    ENCAPSULATION

  • 7/29/2019 Java Notes Of25sessions

    17/318

    INHERITANCEInheritance is a process, through which we can create a new

    class from an existing class.

    In Java extends key word is used

    Parent , Super, Base Class

    Child , Sub , Derived Class

  • 7/29/2019 Java Notes Of25sessions

    18/318

    18

    Vehicle2 Wheeler 3 Wheeler 4 Wheeler

    Kinetic Scooter

    is-a kind of hierarchyInheritance hierarchy

  • 7/29/2019 Java Notes Of25sessions

    19/318

    INHERITANCE Inheritance is the process by which new classes

    called derived classes are created from existing classescalled baseclasses. The derived classes have all the features of

    the base class and the programmer can choose to add newfeatures specific to the newly created derived class.

    A car is avehicle

    A teacher is aperson

    A dog is ananimal

  • 7/29/2019 Java Notes Of25sessions

    20/318

    POLYMORPHISM=PLOY MORPH(MANY FORMS)

    Anything which has more than one form depending on thesituation.

    Polymorphism means having many forms. It allowsdifferent objects to respond to the same message indifferent ways, the response specific to the type of theobject.

    In Java, polymorphism refers to the fact that you can havemultiple methods with the same name in the same class

    POLYMORPHISM

  • 7/29/2019 Java Notes Of25sessions

    21/318

    21

    Move ( )Move ( )

    Move ( )

    Move ( )

    CORE JAVA-OOP CONCEPTS

  • 7/29/2019 Java Notes Of25sessions

    22/318

    Two types of Polymorphism

    1. Compile-time/Static Polymorphism early binding or staticbinding.. ex: Method Overloading

    Method Overloading is a process where the same functionname is used for more than one type/Functions can beoverloaded based on the function signature.

    Method Signature are:

    The no of Parameters

    Type of Parameters

    Sequence of Parameters

    **Functions can not be overloaded based on return type.

  • 7/29/2019 Java Notes Of25sessions

    23/318

    2. Run-time/Dynamic Polymorphism late binding or dynamicbinding.. ex: Method Overriding

    Replacing an inherited method with another having the samesignature

    Create a method in a subclass having the same signatureas amethod in a superclass

    That is, create a method in a subclass having the same nameand the same number and types of parameters

    Restrictions:

    The return type must be the same

  • 7/29/2019 Java Notes Of25sessions

    24/318

    Message PassingThe most important aspect of an object is its behaviour(thethings it can do). A behaviour is initiated by sending amessageto the object (usually by calling a method).

    24

  • 7/29/2019 Java Notes Of25sessions

    25/318

    For example: Message Passing

    In a banking system there is two object one is customer &other is account number. when any customer object sent amessage to the account object requesting for the balance, theaccount object replies with the figure..

  • 7/29/2019 Java Notes Of25sessions

    26/318

    Code reusability

    Security

    Software complexity decreases

    Easy Debugging

  • 7/29/2019 Java Notes Of25sessions

    27/318

    Encapsulation code quality, ease of maintenance

    Inheritance efficiency, extensibility.

    Polymorphism

    power!

  • 7/29/2019 Java Notes Of25sessions

    28/318

    State the history of Java

    Java Applications

    Describe features of Java

    Summary

    28

  • 7/29/2019 Java Notes Of25sessions

    29/318

    JAVE SE(Java Platform, Standard Edition)-FORMERLY J2SE Java for the desktop / workstation

    JAVA EE(ENTERPRISE EDITION)-FORMERLYJ2EE Java for the server programmingJAVA ME(MOBILE EDITION)-FORMERLYJ2ME(MICRO EDITION) Java platform designedfor embedded system

    29

  • 7/29/2019 Java Notes Of25sessions

    30/318

    ProgramThese are the set of instructions directing the computer to dosome action

    programming languagesLanguages for specifying sequences of directions to acomputer

    Software:It is the logical part of computer system, which is made up byseveral programs. In short, It is set of Programs.

    30

    Programs are written using programming languages.

  • 7/29/2019 Java Notes Of25sessions

    31/318

  • 7/29/2019 Java Notes Of25sessions

    32/318

    Java Authors: James Gosling , Arthur Van , and others

    Originally created for consumer electronics (TV, VCR, Freeze,Washing Machine, Mobile Phone)

    Many ofJavas object-oriented features were influenced byC++

    Oak was renamed to Java in May 1995.

    32

  • 7/29/2019 Java Notes Of25sessions

    33/318

    Its the current hot language

    Its almost entirely object-oriented

    It has a vast library of predefined objects and operations

    Its more platform independent

    this makes it great for Web programming

    Its more secure

    33

  • 7/29/2019 Java Notes Of25sessions

    34/318

    Java is a general purpose ,Object-orientedprogramming language. We can develop three typesof applications in Java

    Stand alone Applications GUI Applications Applet Applications

    Java Applications

  • 7/29/2019 Java Notes Of25sessions

    35/318

    JavaSourceCode

    Java Compiler

    Java Enabled

    Web browser Java Interpreter

    Output Output

    Standalone and GUIapplications

    Applets

    Java Applications cont

  • 7/29/2019 Java Notes Of25sessions

    36/318

    Java Is Simple Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    36

    Java is partially modeled on C++,but greatly simplified and improved.

    No pointers

    Automatic garbage collection

    Does not use header files andpreprocessors (like #include or #define)

    Rich pre-defined class library

  • 7/29/2019 Java Notes Of25sessions

    37/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance Java Is Multithreaded

    Java Is Dynamic

    37

    Focus on the data (objects) andmethods manipulating the data

    Object-oriented programmingprovides great flexibility, modularity,

    clarity, and reusability throughencapsulation, inheritance, andpolymorphism.

  • 7/29/2019 Java Notes Of25sessions

    38/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    38

    Works on a variety of platforms

    Provides support for:Networking: via Socket ProgrammingInternet: The widely used protocolslike HTTP and FTP are developed in

    java

  • 7/29/2019 Java Notes Of25sessions

    39/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    39

    You need an interpreter to run Javaprograms. The programs are compiledinto the Java Virtual Machine codecalled bytecode. The bytecode ismachine-independent and can run onany machine that has a Java interpreter,

    which is part of the Java VirtualMachine (JVM).

  • 7/29/2019 Java Notes Of25sessions

    40/318

    JAVA COMPILER

    JAVA BYTE CODE

    JAVA INTERPRETER

    Windows 95

    Macintosh Solaris Windows NT

    (translator)

    (same for all platforms)

    (one for each different system)

    40

  • 7/29/2019 Java Notes Of25sessions

    41/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust(Reliable) Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance Java Is Multithreaded

    Java Is Dynamic

    41

    Java compilers can detect manyproblems that would first show upat execution time in otherlanguages.

    Memory protection andmanagement(using garbage collection)

    Java has a runtime exception-

    handling feature to provideprogramming support forrobustness.

  • 7/29/2019 Java Notes Of25sessions

    42/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance Java Is Multithreaded

    Java Is Dynamic

    42

    The Java language has built-incapabilities to ensure that violationsof security do not occur.

    Access restrictions are forced(private, public)

    The absence of pointers in javaensures that programs cannot gain

    access to memory location withoutproper authorization.

  • 7/29/2019 Java Notes Of25sessions

    43/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    43

    Write once, run anywhere

    With a Java Virtual Machine (JVM),you can write one program that willrun on any platform.

  • 7/29/2019 Java Notes Of25sessions

    44/318

    A.classA.javaJavaCompiler

    B.class

    Loader

    Verifier

    Linker

    Bytecode Interpreter

    Java Virtual Machine

    Compile source code

    Java Virtual Machine Architecture

    44

  • 7/29/2019 Java Notes Of25sessions

    45/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    45

    Because Java is architectureneutral, Java programs areportable. They can be run on anyplatform without being recompiled.Like

    MacOSWindows XP/Vista/2007 SolarisLinux

    Unix etc

    Byte code

    The sizes of the primitive data

    types are machine independent.

  • 7/29/2019 Java Notes Of25sessions

    46/318

    46

    SourceCode ByteCode

    .Java fileWindows

    Mac

    UNIX

    Compile

    .class file

  • 7/29/2019 Java Notes Of25sessions

    47/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    47

    Javas performance Because Java isarchitecture neutral, Java programs are

    portable. They can be run on anyplatform without being recompiled.

    just-in-time(Midway between compiling

    and interpreting) compiling & native

    code

    JVM runningApplet or

    Application

    JITCOMPILER

    .class file

    machine code

  • 7/29/2019 Java Notes Of25sessions

    48/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance

    Java Is Multithreaded

    Java Is Dynamic

    48

    Multithread programming issmoothly integrated in Java,whereas in other languages youhave to call procedures specific tothe operating system to enablemultithreading.

    multiple concurrent threads ofexecutions can run simultaneously

    Multi tasking.

  • 7/29/2019 Java Notes Of25sessions

    49/318

    Java Is Simple

    Java Is Object-Oriented

    Java Is Distributed

    Java Is Interpreted

    Java Is Robust Java Is Secure

    Java Is Architecture-Neutral

    Java Is Portable

    Java's Performance Java Is Multithreaded

    Java Is Dynamic

    49

    Java was designed to adapt to anevolving environment. New code

    can be loaded on the fly withoutrecompilation. There is no need fordevelopers to create, and for usersto install, major new softwareversions. New features can be

    incorporated transparently asneeded.

    Java provides dynamic linking ofthe binary code at runtime.

  • 7/29/2019 Java Notes Of25sessions

    50/318

    What did make Java so successful?

    Portability

    Reliability

    Safety

    Simplicity

    50

  • 7/29/2019 Java Notes Of25sessions

    51/318

    Java has emerged as a general purpose OO language.

    It supports both stand alone and Internet Applications.

    Makes the Web Interactive and medium for application delivery.

    51

  • 7/29/2019 Java Notes Of25sessions

    52/318

    The major differences between C++ & JAVA

    Getting Started With Java Programming

    Create, Compile and Running a Java Program

    52

  • 7/29/2019 Java Notes Of25sessions

    53/318

    Both Java and C++ are most popular object-orientedprogramming languages

    C++ was created at AT&T Bell Labs in 1979

    Java was born in Sun Microsystems in 1990

    53

    C JavaC++

    Java Vs. C++

  • 7/29/2019 Java Notes Of25sessions

    54/318

    No Preprocessor

    No Global Variables

    No Goto statements

    No Pointers

    No Unsafe Structures

    No Multiple Inheritance

    No Operator Overloading No Fragile Data Types

    54

  • 7/29/2019 Java Notes Of25sessions

    55/318

    Java Powerful language

    Programming

    Clarity - Keep it Simple

    Portability - Java portable, but it is an elusive goal

    Performance

    Interpreted programs run slower than compiled ones

    Compiling has delayed execution, interpreting executesimmediately

    Can compile Java programs into machine code

    Runs faster, comparable to C / C++

    55

  • 7/29/2019 Java Notes Of25sessions

    56/318

    The secret behind the security and portability of Java is thatthe output of a Java compiler is not executable code. Rather, itis byte code

    Byte codeis a highly optimized set of instructions designed tobe executed by the Java run-time system, which is called the

    Java Virtual Machine (JVM)

    JVM is an interpreter of byte code

    56

    Java Vs. C++

  • 7/29/2019 Java Notes Of25sessions

    57/318

    BytecodeJVM

    OS kernelBinary codeOS kernel

    JAVAsource code

    C++source code

    javaccompiler

    C++ compilercc, turboc,turbo c++

    Javainterpreter

    Java compiler

    Both compiled and interpreted Compiled

    Java is Both compiled and interpreted

    Java Vs. C++

    57

  • 7/29/2019 Java Notes Of25sessions

    58/318

    The .class files generated by the compiler are not executablebinaries. Instead, they contain byte-codes to be executed bythe Java Virtual Machine.

    write once, run anywhere language.

    Java Vs. C++

    58

  • 7/29/2019 Java Notes Of25sessions

    59/318

    Everything MUST be in a class. There are no global functions or global data. If you want

    the equivalent of globals, make static methods andstatic data within a class.

    There are no structs or enumerations or unions, onlyclasses.

    Java has both kinds of comments like C++ does.

    59

    Java Vs. C++

  • 7/29/2019 Java Notes Of25sessions

    60/318

    Java has no preprocessor. If you want to use classes in another library, you say import

    and the name of the library.

    There are no preprocessor-like macros.

    60

    All the primitive types in Java have specified sizes that aremachine independent for portability.

    Java Vs. C++

  • 7/29/2019 Java Notes Of25sessions

    61/318

    There is a garbage collection in JAVA Garbage collection means memory leaks are much harder to

    cause in Java, but not impossible. (If you make nativemethod calls that allocate storage, these are typically not

    tracked by the garbage collector.)

    61

    There are no destructors in Java.- There's no need because of garbage collection.

  • 7/29/2019 Java Notes Of25sessions

    62/318

    62

    C++ JAVAC++ supports classes,structures orunions.

    Java supports only classes.

    In C++ class definition, classis closed by semicolon afterthe curly brace.

    In Java class definition is verysimilaras C++, but presence ofsemicolon is

    not required.Uses scope resolutionoperator (::).

    Not using scope resolutionoperator (::).

    Some other differences

  • 7/29/2019 Java Notes Of25sessions

    63/318

    Feature C++ Objective Ada Java

    Encapsulation Yes Yes Yes Yes

    Inheritance Yes Yes No Yes

    Multiple Inherit. Yes Yes No No

    Polymorphism Yes Yes Yes Yes

    Binding (Early or Late) Both Both Early Late

    Concurrency Poor Poor Difficult Yes

    Garbage Collection No Yes No Yes

    Genericity Yes No Yes Limited

    Class Libraries Yes Yes Limited Yes

    63

  • 7/29/2019 Java Notes Of25sessions

    64/318

    class HelloWorld

    {

    public static void main(String args[])

    {

    System.out.println(Hello World);

    }

    }

    64

  • 7/29/2019 Java Notes Of25sessions

    65/318

    class HelloWorld name of the class

    {

    public static void main(String args[])

    {

    System.out.println(Hello World);

    }

    }

    65

  • 7/29/2019 Java Notes Of25sessions

    66/318

    class HelloWorld{

    public static void main(String args[])

    {

    System.out.println(Hello World);

    }

    }

    Public is a access specifier that declares the method adunprotected and therefore making it accessible to all other classes.

    Static static is a keyowrd ,which declares this method as one thatbelongs to the entire class and not a part of any objects of the class.

    Void does not return anything.66

  • 7/29/2019 Java Notes Of25sessions

    67/318

    class HelloWorld

    {

    public static void main(String args[])

    Definingmain method

    {

    System.out.println(Hello World);

    }

    }arr[]takes the values of command line arguments..Suppose we are giving a b cdarr[0]=a,arr[1]=b,arr[2]=c,arr[3]=d

    67

    String array as argument

  • 7/29/2019 Java Notes Of25sessions

    68/318

    class HelloWorld{

    public static void main(String args[])

    { System.out.println ( Hello World);}

    }

    System System is a class under java.langpackage.java.lang.Objectjava.lang.System

    outout is the object of PrintStream class.println()is the method that prints in a new line.

    68

  • 7/29/2019 Java Notes Of25sessions

    69/318

    69

    Text Editor Compiler Interpreter

    Programmer

    Source Code.java file

    Byte Code.classfile

    Hardware andOperating System

    javac

    .exe

    file

  • 7/29/2019 Java Notes Of25sessions

    70/318

    70

  • 7/29/2019 Java Notes Of25sessions

    71/318

    71

  • 7/29/2019 Java Notes Of25sessions

    72/318

    Java is CASE SENSITIVE!!

    Whitespace is ignored by compiler

    Whitespace makes things easier to readhence it affects your

    grade

    File name has to be the same as class name in file.

    Need to import necessary class definitions

    72

  • 7/29/2019 Java Notes Of25sessions

    73/318

    Data types

    Identifier

    Variable

    Comments

    Reserved Words

    Operators

    73

  • 7/29/2019 Java Notes Of25sessions

    74/318

  • 7/29/2019 Java Notes Of25sessions

    75/318

    byte, short, int, and long for integer values of various sizes

    float and double for real (rational) values of differing accuracy

    boolean for logical (true/false) values

    char for individual characters

  • 7/29/2019 Java Notes Of25sessions

    76/318

    PRIMITIVE SIZE IN BITS Default Valueslong 8 bytes 0L

    int 4 bytes 0

    short 2 bytes 0

    byte 1 bytes 0

    float 8 bytes 0.0f

    double 4 bytes 0.0d

    char 2 bytes(unicode)

    \u0000

    bool (boolean inJava)

    1 bytes false

  • 7/29/2019 Java Notes Of25sessions

    77/318

    Integers 4, 19, -5, 0, 1000

    Doubles 3.14, 0.0, -16.123

    Strings Hi Mom Enter the number :

    Character 'A' 'X' '9' '$' '\n'

    Boolean true, false

  • 7/29/2019 Java Notes Of25sessions

    78/318

    An identifier is a sequence of characters that consist of letters,

    digits, underscores (_), and dollar signs ($).

    Identifier = the technical term for a name in a programminglanguage

    Identifier naming rules:

    The first character must not be a digit.

    May begin with a letter or the underline character _

    If these rules are broken, your program won't compile.

    Must not be a Java keyword Names must be descriptive.

    Identifiers

  • 7/29/2019 Java Notes Of25sessions

    79/318

    Identifier examples

    class name identifier: Hello

    method name identifier: main

    variable name identifier: height

    Constants All caps with _ between words

  • 7/29/2019 Java Notes Of25sessions

    80/318

    A variables can be considered as a name given to thelocation in memory where values are stored.

    How does the computer know which type of data a

    particular variable can hold? Before a variable is used, its typemust be declaredin a

    declarationstatement.

    Declaration statement syntax:

    ;

    12

  • 7/29/2019 Java Notes Of25sessions

    81/318

    Syntax:type variable_name;ortype variable_name = expression;

    Note

    type must be known to the compiler variable_name must be a valid identifier expression is evaluated and assigned to variable_name

    location In the first form, a default value is given (0, false, or null,

    depending on type)

  • 7/29/2019 Java Notes Of25sessions

    82/318

    There are two types of comments used in Java. These are:

    In Java, comments are preceded by two slashes (//) in a line

    Or enclosed between /* and */ in one or multiple lines.

    When the compiler sees //, it ignores all text after // in thesame line.

    When it sees /*, it scans for the next */ and ignores any textbetween /* and */.

  • 7/29/2019 Java Notes Of25sessions

    83/318

    Reserved wordsor keywordsare words that have a specificmeaning to the compiler and cannot be used for other purposesin the program.

    For example, when the compiler sees the word class, itunderstands that the word after class is the name for the class.

    Other reserved words are like public, static, and void. Their use

    will be introduced later in the book.

    83

  • 7/29/2019 Java Notes Of25sessions

    84/318

    a va eywor s

    abstract boolean break byte case

    catch char class continue default

    do double else extends false

    final finally float for if

    implements import instanceof int interface

    long native new null package

    private protected public return short

    static super switch synchronized this

    throw throws transient true try

    void volatile while

    Keywords that are reserved but not used by Javaconst goto

    Keywords are words reserved for Java and cannot be used as identifiers or

    variable names

    Java Keywords

  • 7/29/2019 Java Notes Of25sessions

    85/318

    Types of operatorsSimple Assignment Operator

    = (Simple assignment operator)Arithmetic Operators+ (Additive operator (also used for String concatenation))

    - (Subtraction operator)* (Multiplication operator)/ (Division operator)% (Remainder operator)

    85

  • 7/29/2019 Java Notes Of25sessions

    86/318

    Unary Operators+ (Unary plus operator; indicates positive value)- (Unary minus operator; negates an expression)++ (Increment operator; increments a value by 1)-- (Decrement operator; decrements a value by 1)! (Logical compliment operator; inverts the value of aboolean)

    Equality and Relational Operators

    86

    == (Equal to) >= (Greater than or equal to)

    != (Not equal to) < (Less than)

    > (Greater than)

  • 7/29/2019 Java Notes Of25sessions

    87/318

    Conditional Operators&& (Conditional-AND)|| (Conditional-OR)?: (Ternary (shorthand for if-then-else statement))

    Type Comparison Operatorinstanceof (Compares an object to a specified type)

    87

  • 7/29/2019 Java Notes Of25sessions

    88/318

    Bitwise and Bit Shift Operators~ (Unary bitwise complement)> (Signed right shift)

    >>> (Unsigned right shift)

    & (Bitwise AND)

    ^ (Bitwise exclusive OR)

    Operand should be integer type

    88

  • 7/29/2019 Java Notes Of25sessions

    89/318

    Bitwise AND

    10012 & 00112 = 00012

    Bit OR

    10012 | 00112 = 10112 Exclusive OR

    10012 ^ 00112 = 10102

    1s Complement

    ~ 000010102

    = 111101012

    Operators cont

  • 7/29/2019 Java Notes Of25sessions

    90/318

    Control statement

    Array

    90

  • 7/29/2019 Java Notes Of25sessions

    91/318

    if statement

    switch statement

    conditional operator

  • 7/29/2019 Java Notes Of25sessions

    92/318

    Writing if Statements ifstatement:

    Interrogates logical expression enclosed in parentheses

    boolean expressions can use just one word

    example:boolean isFound=true;

    if (isFound)System.out.println(The object is found.);

    Determines whether it is true or false

    Uses logical operators to compare values

  • 7/29/2019 Java Notes Of25sessions

    93/318

  • 7/29/2019 Java Notes Of25sessions

    94/318

  • 7/29/2019 Java Notes Of25sessions

    95/318

    Writing if Statements You dont need the brackets for only one statement.

    ifstatements can contain compound expressions

    Two expressions joined using logical operators

    OR ||

    AND &&

    Nested ifstatement

    ifstatement written inside another ifstatement

    the elsestatement always corresponds with the closest if

    statement

  • 7/29/2019 Java Notes Of25sessions

    96/318

    Using the Conditional Operator

    Conditional operator (?)

    Provides a shortcut to writing an if-else statement

    Structure:

    variable = expression ? value1:value2;

    exampleint smallerNumber = (a < b) ? a : b;

  • 7/29/2019 Java Notes Of25sessions

    97/318

    Writing switchStatements

    Acts like a multiple-way ifstatement

    Transfers control to one of several statements or blocksdepending on the value of a variable

    Used when there are more than two values to evaluate

    Restrictions:

    Each case evaluates a single variable for equality only

    Variable being evaluated must be: char, byte, short, or int

  • 7/29/2019 Java Notes Of25sessions

    98/318

    char eventType;

    switch (eventType){

    case A:eventCoordinator = Dustin;

    break;case B:eventCoordinator = Heather;

    break;case C:

    eventCoordinator = Will;break;default:eventCoordinator = Invalid Entry;

    }

  • 7/29/2019 Java Notes Of25sessions

    99/318

    Loops

    Provides for repeated execution of one or more statementsuntil a terminating condition is reached

    Three basic types:

    while

    do

    for

    What is the difference between the while and do loops?

  • 7/29/2019 Java Notes Of25sessions

    100/318

  • 7/29/2019 Java Notes Of25sessions

    101/318

    Following figure shows a while loop that prints the integersthrough 10

  • 7/29/2019 Java Notes Of25sessions

    102/318

    Post-test loop Tests terminating condition at the end of the loop

    Forces execution of statements in the loop body at leastonce

    Example:

    do

    {System.out.println(count = + count);count++;

    }

    while (count

  • 7/29/2019 Java Notes Of25sessions

    103/318

    Pre-test loop Tests terminating condition at the beginning of the loop

    Includes counter initialization and incrementing code in thestatement itself

    Example:

    for (int count=1; count

  • 7/29/2019 Java Notes Of25sessions

    104/318

    An array is a group of contiguous or related data items thatshare a common name.

    Used when programs have to handle large amount of data

    Each value is stored at a specific position

    Position is called a index or superscript. Base index = 0

    The ability to use a single name to represent a collection ofitems and refer to an item by specifying the item numberenables us to develop concise and efficient programs.

    For example, a loop with index as the control variable can beused to read the entire array, perform calculations, and printout the results.

  • 7/29/2019 Java Notes Of25sessions

    105/318

    Creating an array is a 2 step process

    It must be declared (declaration does not specify size)

    It must be created (ie. memory must be allocated for thearray)

    Creating Arrays

    type[] arrayName;declaration syntax:

    note the location of the []

    int[] grades; // declaration

    grades = new int[5]; // Create array.// specify size

    // assign new array to

    // array variable

  • 7/29/2019 Java Notes Of25sessions

    106/318

    int[] grades = new int[5];

    When an array is created, all of its elements are automaticallyinitialized

    0 for integral types

    0.0 for floating point types

    false for boolean types

    null for object types

    Creating Arrays

    0

    0

    0

    0

    0

    4

    3

    2

    1

    0array indices

    Note: maximum array index is length -1

    grades

  • 7/29/2019 Java Notes Of25sessions

    107/318

    Because array elements are initialized to 0, the array should beinitialized with usable values before the array is used.

    This can be done with a loop

    Arrays have a length attribute which can be used for boundschecking

    Elements are accessed using an index and []

    Initializing and Using Arrays

    int[] sequence = new int[5];

    for (int i=0; i< sequence.length; i++)

    {

    sequence[i] = i * 25;

    }

    array length: ensures loop

    won't go past end of the arrayArray element being accessed. In this

    case, it is being assigned a value.

  • 7/29/2019 Java Notes Of25sessions

    108/318

    Another way of initializing lists is by using initializer lists.

    The array is automatically created

    The array size is computed from the number of items in thelist.

    Using initialize lists

    int[] grades = {100, 96, 78, 86, 93};

    type[] arrayName = {initializer_list};

    String[] colours = { "Red", "Orange",

    "Yellow", "Green",

    "Blue", "Indigo",

    "Violet"};

  • 7/29/2019 Java Notes Of25sessions

    109/318

    Two dimensional arraysallows us to store datathat are recorded in table.For example:

    Table contains 12 items,we can think of this as amatrix consisting of 4rows and 3 columns.

    Item1 Item2 Item3

    Salesgirl #1 10 15 30

    Salesgirl #2 14 30 33

    Salesgirl #3 200 32 1

    Salesgirl #4 10 200 4

    109

    Sold

    Person

  • 7/29/2019 Java Notes Of25sessions

    110/318

    Declaration: int myArray [][];

    Creation: myArray = new int[4][3]; // OR

    int myArray [][] = new int[4][3];

    Initialisation: Single Value;

    myArray[0][0] = 10;

    Multiple values:

    int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};

    int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

    11

    0

  • 7/29/2019 Java Notes Of25sessions

    111/318

    Arrays can be used to store objects

    Circle[] circleArray;circleArray = new Circle[25];

    The above statement creates an array that can storereferences to 25 Circle objects.

    Circle objects are not created.

    11

    1

  • 7/29/2019 Java Notes Of25sessions

    112/318

    Create the Circle objects and stores them in the array.

    //declare an array for Circle

    Circle circleArray[] = new Circle[25];

    int r = 0;

    // create circle objects and store in array

    for (r=0; r

  • 7/29/2019 Java Notes Of25sessions

    113/318

    Classes and objects

    Constructors

    this keyword

    Garbage Collection

    finalize() Method

    11

    3

  • 7/29/2019 Java Notes Of25sessions

    114/318

    Defining ClassA CLASS is a template (specification, blueprint)for a collection of objects that share a commonset of attributes and operations.

    HealthClubMemberClass

    Objects

    attributesoperations

  • 7/29/2019 Java Notes Of25sessions

    115/318

    11

    5

    Class & Instance

  • 7/29/2019 Java Notes Of25sessions

    116/318

    Class defines a new data types Once defined, this new type can be used to create objects of

    that type

    Class is a template for an object and, an object is an instanceof a class

    The data or variables, defined within a class are calledinstance variables The code is contained within methods Collectively, the methods and variables defined within a class

    are called members of a class

    116

  • 7/29/2019 Java Notes Of25sessions

    117/318

    class classname{access modifiers:

    type instance-variable1

    //

    type instance-variable N

    access modifiers:type methodname1(parameter-list){

    //body of the method

    }

    //

    type methodname N(parameter-list){//body of the method

    }

    }

    117

  • 7/29/2019 Java Notes Of25sessions

    118/318

  • 7/29/2019 Java Notes Of25sessions

    119/318

    General form of a class does not specify a main( ) method

    Class declaration and implementation of the methods are

    stored in the same place and not defined separately (Differentfrom the C++)

    Sometimes .java files become very large

    119

  • 7/29/2019 Java Notes Of25sessions

    120/318

    class Box{

    double width;

    double height;

    double depth;

    }

    This code does not cause any objects of type Box to comeinto existence

    To actually create a Box object, you will use a statement like:Box mybox = new Box(); // create a Box object called mybox

    120

  • 7/29/2019 Java Notes Of25sessions

    121/318

    Here is a complete program that uses the Box classclass Box {

    double width;

    double height;

    double depth;

    }

    // This class declares an object of type Box.

    class BoxDemo {

    public static void main(String args[]) {Box mybox = new Box();

    double vol;

    // assign values to mybox's instance variables

    mybox.width = 10;

    mybox.height = 20;

    mybox.depth = 15;

    // compute volume of boxvol = mybox.width * mybox.height * mybox.depth;

    System.out.println("Volume is " + vol);

    }

    }

    121

  • 7/29/2019 Java Notes Of25sessions

    122/318

    To obtain objects of a class, we need

    First declare a variable of the class type

    Second, acquire an actual, physical copy of the object andassign it to that variable (by new operator)

    In Java, all class objects must be dynamically allocated

    Object references appear to be similar to pointers, but youcan not manipulate references as you actual pointers

    122

  • 7/29/2019 Java Notes Of25sessions

    123/318

    123

    Statement Effect

    Box mybox;

    mybox

    mybox=new Box( );

    mybox

    Box object

    null

    Width

    HeightDepth

  • 7/29/2019 Java Notes Of25sessions

    124/318

    mybox=new Box();

    The class name followed by parentheses specifies theconstructor for the class

    If a class dont explicitly define its own constructor, the Java

    automatically supply a default constructor We dont need to use new for integers or characters.

    Becausejavas simple types are not implemented as objects

    It is possible that new will not be able to allocate memoryfor an object because of insufficient memory. In that case, arun-time exception will occur

    124

  • 7/29/2019 Java Notes Of25sessions

    125/318

    Box b1=mew Box();Box b2=b1;

    b1 and b2 will both refer to the same object

    b1

    b2

    Box object If b1 is assigned null (b1=null;), the b2 still points to the

    original object

    125

    WidthHeight

    Depth

  • 7/29/2019 Java Notes Of25sessions

    126/318

    class Box {

    double width;

    double height;

    double depth;

    // display volume of a box

    void volume() {

    System.out.print("Volume is ");

    System.out.println(width * height * depth);

    }

    }class BoxDemo3 {

    public static void main(String args[]) {

    Box mybox1 = new Box();

    // assign values to mybox1's instance variables

    mybox1.width = 10;

    mybox1.height = 20;

    mybox1.depth = 15;

    // display volume of first boxmybox1.volume();

    }

    }

    126

  • 7/29/2019 Java Notes Of25sessions

    127/318

    class Box {

    double width;double height;

    double depth;

    double volume( ) { // compute and return volume

    return width * height * depth;

    }

    }

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

    Box mybox1 = new Box();

    double vol;

    mybox1.width = 10; // assign values to mybox1's instance variables

    mybox1.height = 20;

    mybox1.depth = 15;

    vol = mybox1.volume( ); // get volume of first boxSystem.out.println("Volume is " + vol);

    }

    }

    127

  • 7/29/2019 Java Notes Of25sessions

    128/318

    There are two problems in the previous code Its is clumsy and error prone (you may forget to set

    dimension)

    Instance variables should be accessed only throughmethods defined by their class

    void setDim(double w, double h, double d) {

    width = w;

    height = h;

    depth = d;

    } mybox1.setDim(10, 20, 15);

    128

  • 7/29/2019 Java Notes Of25sessions

    129/318

    A constructor is automatically called immediately after theobject is created, before the new operator completes

    Its has no return types, not even void

    Constructors have the same name as the classname

    When we write Box mybox1=new Box( );actually theconstructor for the class is being called

    As you know, Java creates a default constructor for the class,which initializes all instance variables to zero

    129

    Constructor

  • 7/29/2019 Java Notes Of25sessions

    130/318

    Box() {

    System.out.println("Constructing Box");

    width = 10;

    height = 10;

    depth = 10;}

    When you write Box mybox1=new Box( ); the values of height,width and depth are automatically assigned

    130

  • 7/29/2019 Java Notes Of25sessions

    131/318

    Box(double w, double h, double d) {

    width = w;

    height = h;

    depth = d;

    }

    Box mybox1 = new Box(10, 20, 15);

    131

  • 7/29/2019 Java Notes Of25sessions

    132/318

    Sometimes a method will need to refer to the object thatinvoked it. To allow this, Java defines the this keyword

    this can be used inside any method to refer to the currentobject. this always refers to the object on which the methodwas invoked

    132

  • 7/29/2019 Java Notes Of25sessions

    133/318

  • 7/29/2019 Java Notes Of25sessions

    134/318

    Sometimes an object will need to perform some action when

    it is destroyed (i.e. release some non-java resources such asfile handle or windows character font)

    finalize( ) method allows us to define specific actions that

    will occurs when an object is just about to be reclaimed bythe garbage collector

    protected void finalize( )

    {

    //finalization code here

    } You cannot know when- or even if- finalize( ) will be

    executed. Therefore, you must not rely on it for normalprogram execution

    134

  • 7/29/2019 Java Notes Of25sessions

    135/318

  • 7/29/2019 Java Notes Of25sessions

    136/318

    Methods are distinguished by their signature:

    name

    number of arguments

    type of arguments

    position of arguments

    That means, a class can also have multiple usual methodswith the same name.

    Not to confuse with method overriding(coming up), methodoverloading:

    13

    6

  • 7/29/2019 Java Notes Of25sessions

    137/318

    class OverloadDemo {void test() {

    System.out.println("No parameters");

    }

    // Overload test for one integer parameter.

    void test(int a) {

    System.out.println("a: " + a);}

    // Overload test for two integer parameters.

    void test(int a, int b) {

    System.out.println("a and b: " + a + " " + b);

    }

    // overload test for a double parameterdouble test(double a) {

    System.out.println("double a: " + a);

    return a*a;

    }

    }137

  • 7/29/2019 Java Notes Of25sessions

    138/318

  • 7/29/2019 Java Notes Of25sessions

    139/318

    Constructor is a special method that gets invokedautomatically at the time of object creation.

    Constructor is normally used for initializing objects with defaultvalues unless different values are supplied.

    Constructorhas the same name as the class name.

    Constructor cannot return values.

    A class can have more than one constructor as long as they havedifferent signature (i.e., different input arguments syntax).

    13

    9

  • 7/29/2019 Java Notes Of25sessions

    140/318

    Sometimes want to initialize in a number of different ways,

    depending on circumstance.

    This can be supported by having multiple constructorshaving different input arguments.

    14

    0

  • 7/29/2019 Java Notes Of25sessions

    141/318

    14

    1

    public class Circle {public double x,y,r; //instance variables// Constructors

    public Circle(double centreX, double cenreY, doubleradius) {

    x = centreX; y = centreY; r = radius;}public Circle(double radius) { x=0; y=0; r = radius; }public Circle() { x=0; y=0; r=1.0; }

    //Methods to return circumference and areapublic double circumference() { return 2*3.14*r; }public double area() { return 3.14 * r * r; }

    }

  • 7/29/2019 Java Notes Of25sessions

    142/318

    14

    2

    public class TestCircles {

    public static void main(String args[]){Circle circleA = new Circle( 10.0, 12.0, 20.0);Circle circleB = new Circle(10.0);Circle circleC = new Circle();

    }}

    circleA = new Circle(10, 12, 20)circleB = new Circle(10)

    Centre = (0,0)

    Radius=10

    circleC = new Circle()

    Centre = (0,0)Radius = 1

    Centre = (10,12)Radius = 20

  • 7/29/2019 Java Notes Of25sessions

    143/318

    14

    3

    Method Overloading

    Using one object wecan call all themethods having samename

    Example:A a=new A();

    a.add(12,14);

    a.add(11.5,16.8);

    a.add(10,15,20);

    Constructor Overloading

    We need different objectsto call each constructors

    Example:

    Area a=new Area();

    Area a1=new Area(4);

    Area a2=new Area(4.0);

  • 7/29/2019 Java Notes Of25sessions

    144/318

    Java supports definition of global methods and variables that

    can be accessed without creating objects of a class. Suchmembers are called Static members.

    Define a variable by marking with the static methods.

    This feature is useful when we want to create a variablecommon to all instances of a class.

    One of the most common example is to have a variable thatcould keep a count of how many objects of a class have beencreated.

    Note: Java creates only one copy for a static variable whichcan be used even if the class is never instantiated.

    14

    4

  • 7/29/2019 Java Notes Of25sessions

    145/318

    Using static variables:

    14

    5

    public class Circle {// class variable, one for the Circle class, how many

    circlesprivate static int numCircles = 0;private double x,y,r;

    // Constructors...Circle (double x, double y, double r){

    this.x = x;this.y = y;

    this.r = r;numCircles++;

    }}

  • 7/29/2019 Java Notes Of25sessions

    146/318

    Using static variables:

    14

    6

    public class CountCircles {

    public static void main(String args[]){

    Circle circleA = new Circle( 10, 12, 20); // numCircles = 1

    Circle circleB = new Circle( 5, 3, 10); // numCircles = 2

    }

    }

    circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10)

    numCircles

  • 7/29/2019 Java Notes Of25sessions

    147/318

    Instance variables : One copy per object. Every object hasits own instance variable.

    E.g. x, y, r (centre and radius in the circle)

    Static variables : One copy per class. E.g. numCircles (total number of circle objects created)

    14

    7

  • 7/29/2019 Java Notes Of25sessions

    148/318

  • 7/29/2019 Java Notes Of25sessions

    149/318

    public class HowToAccessStaticMethod

    {int i;

    static int j;

    public static void staticMethod(){

    System.out.println("you can access a static method this way");

    }

    public void nonStaticMethod(){

    i=100;

    j=1000;

    System.out.println("Don't try to access a non static method");

    }

    public static void main(String[] args) {

    //i=100;

    j=1000;

    //nonStaticMethod();

    staticMethod();

    }}

    14

    9

  • 7/29/2019 Java Notes Of25sessions

    150/318

    They can only call other static methods.

    They can only access static data.

    They cannot refer to this or super (more later) in anyway.

    15

    0

  • 7/29/2019 Java Notes Of25sessions

    151/318

    Inheritance

    Method overriding

    Difference between Method overloading & Method overriding

    15

    1

  • 7/29/2019 Java Notes Of25sessions

    152/318

    Inheritance is a process, through which we can create a newclass from an existing class.

    In Java extends key word is used

    Parent , Super, Base Class

    Child , Sub , Derived Class

  • 7/29/2019 Java Notes Of25sessions

    153/318

    A class that is inherited is called superclass

    The class that inherits is called subclass

    A subclass is a specialized version of a superclass

    extends keyword is used to inherit superclass Java does not support multiple superclasses into single

    subclass (This differs from C++)

    A subclass can be a superclass of another subclass

    So class can be a superclass of itself

    153

  • 7/29/2019 Java Notes Of25sessions

    154/318

    1.Single Inheritance:

    class A

    {

    //code

    }

    class B extends A

    {

    //code

    }

    A

    B

  • 7/29/2019 Java Notes Of25sessions

    155/318

    Types:-1.Single 2.Multilevel 4.Hierarchical

  • 7/29/2019 Java Notes Of25sessions

    156/318

    3.Multiple Inheritance:

    A

    BC D

    Types: 1.Single 2.Multilevel 3.Multiple 4.Hierarchical

  • 7/29/2019 Java Notes Of25sessions

    157/318

  • 7/29/2019 Java Notes Of25sessions

    158/318

    3.Multiple Inheritance: Not supported by

    Java.

    Diamond ProblemBut supported by

    C++To Overcome this problem we

    have the concept of Interface..

    A

    B

    C D

  • 7/29/2019 Java Notes Of25sessions

    159/318

    Inheritance: Inheritance is a process, through which we can create a new class from an

    existing class.4.Hierarchical Inheritance:

    class A

    {

    //code

    }

    class B extends A

    {//code

    }

    class C extends A

    {

    //code

    }

    class D extends A{

    //code

    }

    A

    BC D

  • 7/29/2019 Java Notes Of25sessions

    160/318

    If a superclass keeps its data members private, then therewould be no way for subclass to directly access or initializeits parents instance variables

    The solution is the use of keyword super Whenever a subclass needs to refer to its immediate

    superclass, it can do so by use of the keyword super Super has two general forms,

    For accessing constructors For accessing hidden member of superclass

    160

  • 7/29/2019 Java Notes Of25sessions

    161/318

    super (parameter-list)

    super( ) must always be the first statement executed inside asubclass constructor

    // BoxWeight now uses super to initialize its Box attributes.

    class BoxWeight extends Box {

    double weight; // weight of box

    // initialize width, height, and depth using super()

    BoxWeight(double w, double h, double d, double m) {

    super(w, h, d); // call superclass constructor

    weight = m;}

    }

    161

  • 7/29/2019 Java Notes Of25sessions

    162/318

    Here super acts as somewhat like thissuper.member

    Mostly applicable when member names of a subclass hidemembers by the same name in the superclass

    // Using super to overcome name hiding.class A {

    int i;}// Create a subclass by extending class A.class B extends A {

    int i; // this i hides the i in A

    B(int a, int b) {super.i = a; // i in Ai = b; // i in B

    }

    162

  • 7/29/2019 Java Notes Of25sessions

    163/318

    Method Overriding is a process through which a base classmethod overridden by a derived class method

    For method Overriding Method name and signature shouldbe same.

    When a overridden method is called from within a subclass, itwill always refer to the version of that method defined by thesubclass

    Like virtual functions in C++

    163

  • 7/29/2019 Java Notes Of25sessions

    164/318

  • 7/29/2019 Java Notes Of25sessions

    165/318

    class B extends A {

    int k;

    B(int a, int b, int c) {

    super(a, b);

    k = c;

    }

    void show() {

    super.show( ); // this calls A's show()

    System.out.println("k: " + k);

    }}

    165

  • 7/29/2019 Java Notes Of25sessions

    166/318

    Method overriding occurs only when the names and the typesignatures of the two methods are identical

    If they are not, then two methods are simply overloaded

    166

  • 7/29/2019 Java Notes Of25sessions

    167/318

    Methods declared as final cannot be overriddenclass A {

    final void meth() {

    System.out.println("This is a final method.");

    }

    }

    class B extends A {void meth() { // ERROR! Can't override.

    System.out.println("Illegal!");

    }

    }

    Normally Java resolves calls to methods dynamically, atrun time (late binding)

    Since, final methods cannot be overridden, a call to onecan be resolved at compile time (early binding)

    167

  • 7/29/2019 Java Notes Of25sessions

    168/318

  • 7/29/2019 Java Notes Of25sessions

    169/318

  • 7/29/2019 Java Notes Of25sessions

    170/318

    Final classes

    Abstract classes

    String Class

    17

    0

  • 7/29/2019 Java Notes Of25sessions

    171/318

  • 7/29/2019 Java Notes Of25sessions

    172/318

  • 7/29/2019 Java Notes Of25sessions

    173/318

    We can prevent an inheritance of classes by other classes bydeclaring them as final classes.

    This is achieved in Java by using the keyword final as follows:final class Marks{ // members}final class Student extends Person{ // members}

    Any attempt to inherit these classes will cause an error.

    17

    3

  • 7/29/2019 Java Notes Of25sessions

    174/318

  • 7/29/2019 Java Notes Of25sessions

    175/318

  • 7/29/2019 Java Notes Of25sessions

    176/318

  • 7/29/2019 Java Notes Of25sessions

    177/318

    What about the object of abstract classes?

    There can not be any object of any Abstract Classes.

    i.e-An abstract class can not be directly instantiated with thenew operator

    Why?

    As the abstract class is not fully defined..

  • 7/29/2019 Java Notes Of25sessions

    178/318

  • 7/29/2019 Java Notes Of25sessions

    179/318

  • 7/29/2019 Java Notes Of25sessions

    180/318

    A class with one or more abstract methods is automaticallyabstract and it cannot be instantiated.

    A class declared abstract, even with no abstract methods cannot be instantiated.

    A subclass of an abstract class can be instantiated if itoverrides all abstract methods by implementation them.

    A subclass that does not implement all of the superclassabstract methods is itself abstract; and it cannot beinstantiated.

    18

    0

  • 7/29/2019 Java Notes Of25sessions

    181/318

    Every string you create is actually an object of type String.Even string constants are actually String objects

    String objects are immutable; once a String object is created,its contents cannot be altered

    Java defines a peer class of String, called StringBuffer, whichallows strings to be altered

    One way to create a string is:

    String mystring=this is a test

    + operator is used to concatenate two strings

    181

  • 7/29/2019 Java Notes Of25sessions

    182/318

    equals( ) is used to test two string for equality

    length( ) is used to obtain the length of string

    charAt( ) is used to obtain the character at a specified indexwithin a string

    Also you can have arrays of string

    String str[ ]={one, two, three};

    182

  • 7/29/2019 Java Notes Of25sessions

    183/318

    If you do not want (properties of) your class to be extended

  • 7/29/2019 Java Notes Of25sessions

    184/318

    If you do not want (properties of) your class to be extendedor inherited by other classes, define it as a final class. Java supports this is through the keyword final. This is applied to classes.

    You can also apply the final to only methods if you do notwant anyone to override them.

    If you want your class (properties/methods) to be extendedby all those who want to use, then define it as an abstractclass or define one or more of its methods as abstractmethods. Java supports this is through the keyword abstract. This is applied to methods only. Subclasses should implement abstract methods; otherwise,

    they cannot be instantiated.

    18

    4

    Contents

  • 7/29/2019 Java Notes Of25sessions

    185/318

    Understanding the concepts of :

    Introduction to Package

    Creating package

    Importing package

    Using package in java programs

    18

    5

  • 7/29/2019 Java Notes Of25sessions

    186/318

    Packages:

    Putting Classes Together

    18

    6

  • 7/29/2019 Java Notes Of25sessions

    187/318

    18

    7

    The features in basic form limited to reusing the classeswithin a program. What if we need to use classes from other programs withoutphysically copying them into the program under development

    ? In Java, this is achieved by using what is known as packages,a concept similar to classlibraries in other languages.

  • 7/29/2019 Java Notes Of25sessions

    188/318

    Types of packages

  • 7/29/2019 Java Notes Of25sessions

    189/318

    package

    System packagesEx:

    java.lang.*java.util.*java.io.*java.sql.*

    User DefinedPackages

    Created by user .

    We have to follow

    some steps .

    package

    Key word is used

    to create a

    package

  • 7/29/2019 Java Notes Of25sessions

    190/318

    Java provides a large number of classes groped into differentpackages based on their functionality. The six foundation Java packages are:

    java.lang Contains classes for primitive types, strings, mathfunctions, threads, and exception

    java.util Contains classes such as vectors, hash tables, date etc.

    java.io Stream classes for I/O

    java.awt Classes for implementing GUI windows, buttons, menusetc.

    java.net Classes for networking java.applet Classes for creating and implementing applets

    19

    0

  • 7/29/2019 Java Notes Of25sessions

    191/318

  • 7/29/2019 Java Notes Of25sessions

    192/318

  • 7/29/2019 Java Notes Of25sessions

    193/318

    Java supports a keyword called package for creating user-defined packages. The package statement must be the firststatement in a Java source file (except comments and whitespaces) followed by one or more classes.

    Package name is myPackage and classes are considred aspart of this package; The code is saved in a file calledClassA.java and located in a directory called myPackage.

    19

    3

    package myPackage;public class ClassA {

    // class body}class ClassB {// class body

    }

  • 7/29/2019 Java Notes Of25sessions

    194/318

  • 7/29/2019 Java Notes Of25sessions

    195/318

  • 7/29/2019 Java Notes Of25sessions

    196/318

    Within the current directory (abc) store the following code in

  • 7/29/2019 Java Notes Of25sessions

    197/318

    Within the current directory ( abc ) store the following code in

    a file named ClassX.java

    19

    7

    import myPackage.ClassA;

    public class ClassX{

    public static void main(String args[]){

    ClassA objA = new ClassA();objA.display();

    }}

  • 7/29/2019 Java Notes Of25sessions

    198/318

  • 7/29/2019 Java Notes Of25sessions

    199/318

    Let us store the code listing below in a file namedClassA.java within subdirectory named secondPackagewithin the current directory (say abc).

    19

    9

    package secondPackage;public class ClassC {// class body

    public void display(){

    System.out.println("Hello, I am ClassC");}

    }

  • 7/29/2019 Java Notes Of25sessions

    200/318

  • 7/29/2019 Java Notes Of25sessions

    201/318

  • 7/29/2019 Java Notes Of25sessions

    202/318

  • 7/29/2019 Java Notes Of25sessions

    203/318

    Public keyword applied to a class, makes it available/visible

    everywhere. Applied to a method or variable, completelyvisible.

    Privatefields or methods for a class only visible within thatclass. Private members are notvisible within subclasses, andare notinherited.

    Protectedmembers of a class are visible within the class,subclasses and alsowithin all classes that are in the same

    package as that class.

    20

    3

  • 7/29/2019 Java Notes Of25sessions

    204/318

    20

    4

    Accessible to: public protected Package

    (default)

    private

    Same Class Yes Yes Yes Yes

    Class in package Yes Yes Yes No

    Subclass in

    different package

    Yes Yes No No

    Non-subclass

    different package

    Yes No No No

  • 7/29/2019 Java Notes Of25sessions

    205/318

  • 7/29/2019 Java Notes Of25sessions

    206/318

    When packages are developed by different organizations it is

  • 7/29/2019 Java Notes Of25sessions

    207/318

    When packages are developed by different organizations, it is

    possible that multiple packages will have classes with the samename, leading to name classing.

    We can import and use these packages like:

    import pack1.*; import pack2.*; Student student1; // Generates compilation error

    20

    7

    class Teacher

    package pack1;

    class Student

    class Student

    package pack2;

    class Courses

  • 7/29/2019 Java Notes Of25sessions

    208/318

  • 7/29/2019 Java Notes Of25sessions

    209/318

  • 7/29/2019 Java Notes Of25sessions

    210/318

    Packages allow grouping of related classes into a single

    united.

    Packages are organised in hierarchical structure.

    Packages handle name classing issues.

    Packages can be accessed or inherited without actual copy of

    code to each program.

    21

    0

    Contents

  • 7/29/2019 Java Notes Of25sessions

    211/318

    Introduction about interface

    Defining an interface

    Use of interface?

    Different between interface and abstract class

    21

    1

  • 7/29/2019 Java Notes Of25sessions

    212/318

    21

    2212

    Interfaces

    Design Abstraction and a way forloosing realizing Multiple Inheritance

  • 7/29/2019 Java Notes Of25sessions

    213/318

  • 7/29/2019 Java Notes Of25sessions

    214/318

  • 7/29/2019 Java Notes Of25sessions

    215/318

    2

    1

    5

    speak()

    Politician Priest

    Speaker

    speak() speak()

    Lecturer

    speak()

    Syntax (appears like abstract class):

  • 7/29/2019 Java Notes Of25sessions

    216/318

    Example:

    21

    6

    interface InterfaceName {

    // Constant/Final Variable Declaration

    // Methods Declaration only method body

    }

    interface Speaker {

    public void speak( );

    }

  • 7/29/2019 Java Notes Of25sessions

    217/318

    Interfaces are used like super-classes who properties areinherited by classes. This is achieved by creating a class thatimplements the given interface as follows:

    21

    7

    class ClassName implements InterfaceName [, InterfaceName2, ]

    {

    // Body of Class

    }

  • 7/29/2019 Java Notes Of25sessions

    218/318

  • 7/29/2019 Java Notes Of25sessions

    219/318

    A general form of interface implementation:

  • 7/29/2019 Java Notes Of25sessions

    220/318

    This shows a class can extended another class whileimplementing one or more interfaces. It appears like amultiple inheritance (if we consider interfaces as special kindof classes with certain restrictions or special features).

    22

    0

    class ClassName extends SuperClass implements InterfaceName [,

    InterfaceName2, ]

    {

    // Body of Class}

    Consider a university where students who participate in the

  • 7/29/2019 Java Notes Of25sessions

    221/318

    national games or Olympics are given some grace marks.Therefore, the final marks awarded = Exam_Marks +Sports_Grace_Marks. A class diagram representing thisscenario is as follow:

    22

    1

    Student Sports

    Exam

    Results

    extends

    extendsimplements

  • 7/29/2019 Java Notes Of25sessions

    222/318

    interface A{ class D

  • 7/29/2019 Java Notes Of25sessions

    223/318

    void display();}

    interface B extends A{

    void show();

    }

    class C implements B{

    void display(){

    System.out.println(interface A);

    }

    void show(){

    System.out.println(Interface B);

    }}

    {public static void main(String arr[])

    {

    C c=new C();

    c.display();

    c.show();

    }

    }

  • 7/29/2019 Java Notes Of25sessions

    224/318

    Like abstract class,

    1. if a class implement an interface, you have to override theinterfaces methods in the class.

    2. You cannot create instances from an interface by using newoperator.

    3. Interface can be a type as well.

    Runnable r;

    4. the purpose of creating interface is because ofpolymorphism.

    224

  • 7/29/2019 Java Notes Of25sessions

    225/318

  • 7/29/2019 Java Notes Of25sessions

    226/318

    4. In the relationships, we say that:4.1. A relationship between class/abstract class and class isa strong relationship. It is known as IS-A relationship.E.g: A duck is a bird. It clearly means the duck is really abird. So the bird can be a superclass of a duck. It could be

    either concrete or abstract class.4.2. A relationship between class and interface is a weakrelationship. It is known as Is-kind-of relationship.E.g: A duck is flyable. Flyable can never ever be thesuperclass of the duck. It just means this duck can fly. So

    flyable is interface.

    226

  • 7/29/2019 Java Notes Of25sessions

    227/318

  • 7/29/2019 Java Notes Of25sessions

    228/318

    To explain Exception in java

    Show how programmer-defined exceptions are created,

    thrown and caught

    To provide the concepts of exception handling

    Explain the use of try, catch, finally, throw, throws keywords.

    22

    8

  • 7/29/2019 Java Notes Of25sessions

    229/318

    The compilation process will detect programming mistakessuch as syntax errors and type mismatches. Such errors cantherefore be referred to as compilation errors.

    But once code is compiled and running, it will have to face thereal world of erroneous input, inexistent files, hardwarefailure Such problems are commonly known as runtimeerrors, which are likely to cause the program to abort.

    22

    9

    An exception is a condition that is caused by a runtime error

  • 7/29/2019 Java Notes Of25sessions

    230/318

    e cept o s a co d t o t at s caused by a u t e e oin the program.

    Need of Exception Handling If a program does not handle the exception at all, the

    program will terminate abnormally and produce a messagethat describes what exception occurred, and where it wasproduced.

    The purpose of exception handling is to provide a means todetect and report an exceptional circumstance so thatappropriate action can be taken.

  • 7/29/2019 Java Notes Of25sessions

    231/318

  • 7/29/2019 Java Notes Of25sessions

    232/318

    A Java exception is an object that describes an exceptionalcondition that has occurred in a piece of code

    When an exceptional condition arises, an object representingthat exception is created and thrownin the method thatcaused the error

    An exception can be caught to handle it or pass it on

    Exceptions can be generated by the Java run-time system, orthey can be manually generated by your code

  • 7/29/2019 Java Notes Of25sessions

    233/318

  • 7/29/2019 Java Notes Of25sessions

    234/318

  • 7/29/2019 Java Notes Of25sessions

    235/318

    Any code that absolutely must be executed before a method

  • 7/29/2019 Java Notes Of25sessions

    236/318

    returns is put in a finally block General form of an exception-handling blocktry{

    // block of code to monitor for errors}catch (ExceptionType1 exOb){

    // exception handler for ExceptionType1}catch (ExceptionType2 exOb){

    // exception handler for ExceptionType2}//

    finally{// block of code to be executed before try block ends

    }

    If an exception is not caught by user program, then executionof the program stops and it is caught by the default handler

  • 7/29/2019 Java Notes Of25sessions

    237/318

    provided by the Java run-time system Default handler prints a stack trace from the point at which

    the exception occurred, and terminates the program

    Ex:

    class Exc0 {

    public static void main(String args[]) {int d = 0;

    int a = 42 / d;

    }

    }Output:java.lang.ArithmeticException: / by zero

    at Exc0.main(Exc0.java:4)

    Exception in thread "main"

  • 7/29/2019 Java Notes Of25sessions

    238/318

    Handling an exception has two benefits,

    It allows you to fix the error

    It prevents the program from automatically terminating

    The catch clause should follow immediately the try block

  • 7/29/2019 Java Notes Of25sessions

    239/318

    PROGRAM:

    Output:

    Division by zero.

    After catch statement.

    http://c/excep/Handle.javahttp://c/excep/Handle.java
  • 7/29/2019 Java Notes Of25sessions

    240/318

  • 7/29/2019 Java Notes Of25sessions

    241/318

    Program Output

    http://c/excep/MultiCatch.javahttp://c/excep/MultiCatch.java
  • 7/29/2019 Java Notes Of25sessions

    242/318

    If no command line argument is provided, then you will seethe following output:

    a = 0

    Divide by 0: java.lang.ArithmeticException: / by zero

    After try/catch blocks

    If any command line argument is provided, then you will seethe following output:a = 1Array index oob: java.lang.ArrayIndexOutOfBoundsException

    After try/catch blocks.

  • 7/29/2019 Java Notes Of25sessions

    243/318

    Remember that, exception subclass must come before any ofof their superclasses

    Because, a catch statement that uses a superclass will catchexceptions of that type plus any of its subclasses. So, thesubclass would never be reached if it come after its

    superclass

    For example, ArithmeticException is a subclass ofException Moreover, unreachable code in Java generates error

    Multiple Catch Statements (Contd.):Catch-all block

    Catch-all block- Accepts more generic Exception argument type

    catch(Exception e)

  • 7/29/2019 Java Notes Of25sessions

    244/318

    - Good approach to handle multiple exception throws by a code block

    public class TwoMistakes3

    { public static void main(String[] args)

    { int num[] = {4, 0, 0};

    try{ num[2] = num[0] / num[1];

    num[2] = num[3] / num[0];

    }

    catch( Exception e) // multiple exceptions can be handle by this block

    { System.out.println(e.getMessage());

    }

    }

    }14

    EXAMPLE PROGRAM

    Throwing an Exception

    Throw

    http://c/excep/catchall.javahttp://c/excep/catchall.java
  • 7/29/2019 Java Notes Of25sessions

    245/318

    - Mostly exceptions are implicitly thrown by the Java run-time system

    - Programmers can throw an exception explicitly too

    throw ThrowableInstance;

    //ThrowableInstance must be the object of class which is derived from Throwable

    e.g. throw new MyException();

    derived from

    When exception thrown

    - Control exits current try block

    Throwable

    - Proceeds to catch handler (if exists)

    21

    Preceding step

  • 7/29/2019 Java Notes Of25sessions

    246/318

    try block

    throw

    statement

    unmatched catch

    matching catch

    unmatched catch

    next step

    EXAMPLE PROGRAM

    Example: Throw Statementclass ThrowDemo

    { static void demoproc()

    {

    try

    {

    Output:Caught inside demoproc.Recaught: java.lang.NullPointerException: demothrow new NullPointerException("demo");

    http://c/excep/Throwte.javahttp://c/excep/Throwte.java
  • 7/29/2019 Java Notes Of25sessions

    247/318

    }

    catch(NullPointerException e)

    {

    System.out.println("Caught inside demoproc.");

    throw e; // re-throw the exception

    }

    }

    public static void main(String args[])

    {

    try

    { //Re-throwingdemoproc();

    }

    catch(NullPointerException e)

    { System.out.println("Recaught: " + e); }

    }

    }

  • 7/29/2019 Java Notes Of25sessions

    248/318

  • 7/29/2019 Java Notes Of25sessions

    249/318

    Preceding step

  • 7/29/2019 Java Notes Of25sessions

    250/318

    250

    try block

    throw

    statement

    unmatchedcatch

    matching catch

    unmatchedcatch

    next step

    finally

    try

    try{

  • 7/29/2019 Java Notes Of25sessions

    251/318

    {..

    ...}

    finally{..

    ...}

    .....}catch(.){ . }

    catch(..){ . }....finally{

    ....

    }

    Finally Example Program

    http://c/excep/Finally2.javahttp://c/excep/Finally2.java
  • 7/29/2019 Java Notes Of25sessions

    252/318

    25

    2

    A t t t b i id th bl k f th t

  • 7/29/2019 Java Notes Of25sessions

    253/318

    A try statement can be inside the block of another try Each time a try statement is entered, the context of that

    exception is pushed on the stack

    If an inner try statement does not have a catch, then the nexttrystatements catch handlers are inspected for a match If a method call within a try block has try block within it, then

    then it is still nested try

    try

    {

  • 7/29/2019 Java Notes Of25sessions

    254/318

    { try

    {

    }

    catch(Exception e)

    {

    }

    }

    catch(Exception e)

    {

    }

    Example Program

    http://c/excep/NestTry.javahttp://c/excep/NestTry.java
  • 7/29/2019 Java Notes Of25sessions

    255/318

  • 7/29/2019 Java Notes Of25sessions

    256/318

    FORMAT:type mthod-name(parameter list) throws exception-list

    {

    //body of method.}

    Example Program

    25

    6

    Ja a has its b ilt in capabilit to ens re that e ceptions are

    http://c/excep/ThrowsDemo.javahttp://c/excep/ThrowsDemo.java
  • 7/29/2019 Java Notes Of25sessions

    257/318

    Java has its built-in capability to ensure that exceptions arehandled within the java program.

    Exceptions handled by:

    Programmer

    JVM(Java Runtime System)

    Object

  • 7/29/2019 Java Notes Of25sessions

    258/318

    25

    8

    Throwable

    Error

    LinkageError

    ThreadDeath

    VirtualMachineError

    AWTError

    Exception

    RunTimeException

    ArithmeticException

    IndexOutOfBoundsException

    NullPointerEXception

    IllegaAccessException

    NoSuchMethodException

    ClassNotFoundException

  • 7/29/2019 Java Notes Of25sessions

    259/318

    Throwable The base class for all exceptions, it is required for a class to bethe rvalue to a throw statement.

    Error Any exception so severe it should be allowed to pass uncaughtto the Java runtime.

    Exception Anything which should be handled by the invoker is of this type,and all but five exceptions are.

    Checked Exceptions Unchecked Exceptions

    Checked exceptions inability to acquire system

    ( h i ffi i t fil d t

  • 7/29/2019 Java Notes Of25sessions

    260/318

    resources (such as insufficient memory, file does not

    exist)

    Java checks at compile time that some mechanism is explicitly in

    place to receive and process an exception object that may be created

    during runtime due to one of these exceptions occurring.Unchecked exceptions exceptions that occur because of the user

    entering bad data, or failing to enter data at all.

    Unchecked exceptions can be avoided by writing more robust code that

    protects against bad input values. Java does not check at compile timeto ensure that there is a mechanism in place to handle such errors.

    Java Built-in Exceptions: Checked Exceptions

    Table: Javas Checked Exceptions defined in java.lang

    Exception Meaning

  • 7/29/2019 Java Notes Of25sessions

    261/318

    Exception MeaningClassNotFoundException Class not foundCloneNotSupportedException Attempt to clone an object that does not implement

    the Cloneable interface.llegalAccessException Access to a class is denied.InstantiationException Attempt to create an object of an abstract class orinterface.nterruptedException One thread has been interrupted by another thread.NoSuchFieldException A requested field does not exist.NoSuchMethodException A requested method does not exist.

    Java Built-in Exceptions: Unchecked Exceptions

    Table: Javas Unchecked RuntimeException Subclasses

    Exception Meaning

  • 7/29/2019 Java Notes Of25sessions

    262/318

    Exception MeaningArithmeticException Arithmetic error, such as divide-by-zero

    ArrayIndexOutOfBoundsException Array index is out-of-bounds

    ArrayStoreException Assignment to an array element of an incompatible type

    ClassCastException Invalid cast

    IllegalArgumentException Illegal argument used to invoke a method

    IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread

    IllegalStateException Environment or application is in incorrect state

    IllegalThreadStateException Requested operation not compatible with current thread state

    IndexOutOfBoundsException Some type of index is out-of-bounds

    NegativeArraySizeException Array created with a negative size

    NullPointerException Invalid use of a null reference

    NumberFormatException Invalid conversion of a string to a numeric format

    SecurityException Attempt to violate security

    StringIndexOutOfBounds Attempt to index outside the bounds of a string

    UnsupportedOperationException An unsupported operation was encountered20

  • 7/29/2019 Java Notes Of25sessions

    263/318

    We can also create our own exceptions specific to ourapplications.

    It is quite easy, just we create a class by extending

    Exception class. Since it is user defined we must tell the situation

    where it will be occurred and the exception objectmust be created and throw by ourselves.

    26

    3

    Problem Statement :

    Consider the example of the Circle class

  • 7/29/2019 Java Notes Of25sessions

    264/318

    Consider the example of the Circle class Circle class had the following constructor

    public Circle(double radius){r = radius;

    }

    How would we ensure that the radius is not zero

    or negative?

    26

    4

    import java.lang.Exception;

    class InvalidRadiusException extends Exception {

  • 7/29/2019 Java Notes Of25sessions

    265/318

    26

    5

    class InvalidRadiusException extends Exception {

    public InvalidRadiusException (String msg){

    super(msg);

    }

    }

    class Circle {double r;

  • 7/29/2019 Java Notes Of25sessions

    266/318

    26

    6

    public Circle (double radius ) {if (radius

  • 7/29/2019 Java Notes Of25sessions

    267/318

    26

    7

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

    Circle c1 = new Circle(-1);System.out.println("Circle created");

    }catch(InvalidRadiusException e){

    System.out.println(e.getMessage());}

    }}

    Example

    http://c/excep/Usere.javahttp://c/excep/Usere.java
  • 7/29/2019 Java Notes Of25sessions

    268/318

    26

    8

  • 7/29/2019 Java Notes Of25sessions

    269/318

    Multitasking:

    refers to a computer's ability to perform multiple jobs concurrently

    Multitasking is divided into two types:

  • 7/29/2019 Java Notes Of25sessions

    270/318

    Multitasking is divided into two types:

    Process-based: Here two or more programs runs concurrently. You can

    run Windows calculator and a Text editor (Notepad) at the same time.

    Thread-based: A single program can perform two or more tasks

    simultaneously. For example, text editor can print while formatting is

    being done.

    more than one program are running concurrently

    270

  • 7/29/2019 Java Notes Of25sessions

    271/318

    What is Thread?

    A thread is a single sequential flow of control

    within a program

  • 7/29/2019 Java Notes Of25sessions

    272/318

    within a program. Thread does not have its own address space but

    uses the memory and other resources of theprocess in which it executes.

    There may be several threads in one process The Java Virtual Machine (JVM) manages these

    and schedules them for execution.

  • 7/29/2019 Java Notes Of25sessions

    273/318

    A thread is a single sequence of execution within

    a program

  • 7/29/2019 Java Notes Of25sessions

    274/318

    a program

    refers to multiple threads of control within asingle program

    each program can run multiple threads of controlwithin it, e.g., Web Browser

    Multithreading enables programmers to do multiple

    things at one time

  • 7/29/2019 Java Notes Of25sessions

    275/318

    things at one time.

    For ex, we can send tasks such as printing into thebackground and continue to perform some othertask in the foreground.

    CPU CPU1 CPU2

  • 7/29/2019 Java Notes Of25sessions

    276/318

    276

    CPU

  • 7/29/2019 Java Notes Of25sessions

    277/318

    277

    Process 1 Process 3Process 2 Process 4

    main

    run

    GC

    Processes & Threads

  • 7/29/2019 Java Notes Of25sessions

    278/318

    THREADS

  • 7/29/2019 Java Notes Of25sessions

    279/318

    4: Threads279

    When multiple events/actions need to occur

    at the same time

  • 7/29/2019 Java Notes Of25sessions

    280/318

    at the same time Examples:

    Download 10 pages.

    Single-threaded program: sequentially

    Multithreaded: all at the same time save time Download data from the network and respond to

    mouse at the same time

    class ABC

    {

  • 7/29/2019 Java Notes Of25sessions

    281/318

    {.

    .....

    .

    .....

    .

    .....

    }

    Beginning

    Single-threaded

    Body of

    Execution

    End

    Main Method

  • 7/29/2019 Java Notes Of25sessions

    282/318

    start start start

    switchingswitching

    Module

    Threads are implemented as objects that contains a method called run()

    class MyThread extends Thread

    {

    public void run()

    {// th d b d f ti

    :: Extending the thread class

    EXAMPLE

    http://localhost/var/MultiT/ThreadEx1.javahttp://localhost/var/MultiT/ThreadEx1.java
  • 7/29/2019 Java Notes Of25sessions

    283/318

    // thread body of execution

    }

    }

    Create a thread:

    MyThread thr1 = new MyThread();

    Start Execution of threads:

    thr1.start();

    Create and Execute:

    new MyThread().start();

    ThreadEx1 .java

    http://localhost/var/MultiT/ThreadEx1.javahttp://localhost/var/MultiT/ThreadEx1.java
  • 7/29/2019 Java Notes Of25sessions

    284/318

    class MyThread implements Runnable

    {

    .....