object oriented technic notes(unit4)

Upload: amir-khan

Post on 04-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    1/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    ECSECSECSECS----503: Object Oriented Techniques503: Object Oriented Techniques503: Object Oriented Techniques503: Object Oriented Techniques

    UnitUnitUnitUnit IIIIVVVV

    Introduction to Java:Introduction to Java:Introduction to Java:Introduction to Java:The term Java refers to more than just a computer language like C or Pascal. Java encompasses

    several distinct components:

    A highA highA highA high----level languagelevel languagelevel languagelevel language Java is an object-oriented computer programming language whose

    source code at a glance looks very similar to C and C++ but is unique in many ways.

    Java bytecodeJava bytecodeJava bytecodeJava bytecode A compiler transforms the Java language source code to files of binary

    instructions and data called bytecode that run in the Java Virtual Machine.

    Java Virtual Machine (JVM)Java Virtual Machine (JVM)Java Virtual Machine (JVM)Java Virtual Machine (JVM) A JVM program takes bytecode as input and interprets the instructions just as if it were a

    physical processor executing machine code.

    All language compilers translate source code in machine code for a specific computer. Java

    compiler does the same thing. Java compiler produces an intermediate code known as byte

    code for a machine that does not exist physically, this machine is called Java Virtual

    Machine(JVM) and it exists only inside the computer memory, it is a simulated computer with

    in a computer. This virtual machine is not machine specific code, the machine specific code is

    generated by the java interpreter by acting as a intermediate between virtual machine and real

    machine.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    2/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    History ofHistory ofHistory ofHistory of Java:Java:Java:Java:

    During 1990, James Gosling, Bill Joy and others at Sun Microsystems began developing a

    language called Oak. They primarily intended it as a language for microprocessors embedded

    in consumer devices such as cable set-top boxes, VCRs, and handheld computers (now known

    as personal data assistants or PDAs). To serve these goals, Oak needed the following features:

    platform independenceplatform independenceplatform independenceplatform independence, since it must run on devices from multiple manufacturers extremeextremeextremeextreme

    reliabilityreliabilityreliabilityreliability (cant expect consumers to reboot their VCRs!) compactnesscompactnesscompactnesscompactness, since embedded

    processors typically have limited memory.

    They also wanted a next-generation language that built on the strengths and avoided the

    weaknesses of earlier languages. Such features would help the new language provide more

    rapid software development and faster debugging.

    By 1993 the interactiveTVand PDAmarkets had failed to take off, but internet and web activitybegan its upward zoom. So Sun shifted the target market to internet applications and changed

    the name of the project to Java. The portability of Java made it ideal for the Web, and in 1995

    Suns HotJava browser appeared. Written in Java in only a few months, it illustrated the power

    of applets programs that run within a browser and the ability of Java to accelerate program

    development.

    Versions of JavaVersions of JavaVersions of JavaVersions of Java::::

    Since its introduction, Sun has released new versions of the Java core language with significant

    enhancements about every two years or so. Until recently, Sun denoted the versions with a 1.x

    number, where x reached up to 4. (Less drastic releases with bug fixes were indicated with a

    third number as in 1.4.2.) The next version, however, will be called Java 5.0. Furthermore, Sun

    has split its development kits into so-called editions, each aimed towards a platform with

    different capabilities.

    Standard EditionStandard EditionStandard EditionStandard Edition

    Below is a time line for the different versions of the Standard Edition (SE) of Java, which offers

    the core language libraries (called packages in Java) and is aimed at desktop platforms. We

    include a sampling of the new features that came with each release.

    1995199519951995 Version 1.0. The Java Development Kit (JDK) included:

    8 packages with 212 classes.

    Netscape 2.04.0 included Java 1.0.

    Microsoft and other companies licensed Java.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    3/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    1997199719971997 Version 1.1

    23 packages, 504 classes.

    Improvements included better event handling, inner classes, improved VM. Microsoft

    developed its own 1.1-compatible Java Virtual Machine for the Internet Explorer.

    Many browsers in use are still compatible only with 1.1. Swing packages with greatly improved

    graphics became available during this time but were not included with the core language.

    1999199919991999 Version 1.2. Sun began referring to the 1.2 and above versions as the Java 2 Platform.

    The Software Development Kit (SDK) included: 59 packages, 1520 classes.

    Java Foundation Classes (JFC), based on Swing, for improved graphics and user interfaces, now

    included with the core language. Collections Framework API included support for various lists,

    sets, and hash maps.

    2000200020002000 Version 1.3:76 packages, 1842 classes.

    Performance enhancements including the Hotspot virtual machine.

    2002200220022002 Version 1.4:

    135 packages, 2991 classes.

    2004200420042004 Version 5.0 (previously known as 1.5).

    It includes a number of tools and additions to the language to enhance program development,

    such as: 4faster startup and smaller memory footprint, metadata, formatted output, genericsimproved multithreading features.

    165 packages, over 3000 classes

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    4/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Features Of Java:Features Of Java:Features Of Java:Features Of Java:

    Before we examine how Java can benefit technical applications, we look at the features that

    make Java a powerful and popular general programming language.

    These features include:

    Compiler/interpreter combinationCompiler/interpreter combinationCompiler/interpreter combinationCompiler/interpreter combination

    Code is compiled to bytecode, which is interpreted by a Java Virtual Machine (JVM). This

    provides portability to any base operating system platform for which a virtual machine has

    been written.The two-step procedure of compilation and interpretation allows for extensive

    code checking and improved security.

    SimpleSimpleSimpleSimple

    Java was designed to be easy for the professional programmer to learn and use effectively.

    Assuming that you have some programming experience, you will not find Java hard to master.If you already understand the basic concepts of object-oriented programming, learning Java

    will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will

    require very little effort. Because Java inherits the C/C++ syntax and many of the object-

    oriented features of C++, most programmers have little trouble learning Java.

    ObjectObjectObjectObject----orientedorientedorientedoriented

    Object-oriented programming (OOP) throughout no coding outside of class definitions.

    The bytecode retains an object structure.

    An extensive class library available in the core language packages.

    Automatic memory managementAutomatic memory managementAutomatic memory managementAutomatic memory management

    A garbage collector in the JVM takes care of allocating and reclaiming memory.

    RobustRobustRobustRobust

    Exception handling built-in, strong type checking (that is, all variables must be assigned an

    explicit data type), local variables must be initialized.

    Platform independencePlatform independencePlatform independencePlatform independence

    The bytecode runs on any platform with a compatible JVM.

    The Write Once Run Anywhere ideal has not been achieved (tuning for different

    platforms usually required), but is closer than with other languages.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    5/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    SecureSecureSecureSecure

    The elimination of direct memory pointers and automatic array limit checking .

    Untrusted programs are restricted to run inside the virtual machine sandbox. Access to

    the platform can be strictly controlled by a Security Manager.

    Code is checked for pathologies by a class loader and a bytecode verifier.

    MultithreadedMultithreadedMultithreadedMultithreaded

    Java was designed to meet the real-world requirement of creating interactive, networked

    programs. To accomplish this, Java supports multithreaded programming, which allows you to

    write programs that do many things simultaneously

    Dynamic bindingDynamic bindingDynamic bindingDynamic binding

    Classes, methods, and variables are linked at runtime.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    6/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Object Oriented Concepts of Java:Object Oriented Concepts of Java:Object Oriented Concepts of Java:Object Oriented Concepts of Java:

    ObjectObjectObjectObject----Oriented ProgrammingOriented ProgrammingOriented ProgrammingOriented Programming

    Object-oriented programming is at the core of Java. In fact, all Java programs are object

    orientedthis isnt an option the way that it is in C++, for example. OOP is so integral to Java

    that you must understand its basic principles before you can write even simple Java programs.

    Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.

    Two ParadigmsTwo ParadigmsTwo ParadigmsTwo Paradigms

    As you know, all computer programs consist of two elements: code and data. Furthermore, a

    program can be conceptually organized around its code or around its data. That is, some

    programs are written around what is happening and others are written around who is being

    affected. These are the two paradigms that govern how a program is constructed.

    The first way is called theThe first way is called theThe first way is called theThe first way is called theprocessprocessprocessprocess----oriented model.oriented model.oriented model.oriented model. This approach characterizes a program as aseries of linear steps (that is, code). The process-oriented model can be thought of as code

    acting on data. Procedural languages such as C employ this model to considerable success. The

    problems with this approach appear as programs grow larger and more complex. To manage

    increasing complexity,

    The second approachThe second approachThe second approachThe second approach, called object-oriented programming, was conceived. Object-oriented

    programming organizes a program around its data (that is, objects) and a set of well-defined

    interfaces to that data. An object-oriented program can be characterized as data controlling

    access to code

    The Three OOP PrThe Three OOP PrThe Three OOP PrThe Three OOP Principlesinciplesinciplesinciples

    All object-oriented programming languages provide mechanisms that help you implement the

    object-oriented model. They are encapsulation, inheritance, and polymorphism.

    EncapsulationEncapsulationEncapsulationEncapsulation

    Encapsulationis the mechanism that binds together code and the data it manipulates, and

    keeps both safe from outside interference and misuse. One way to think about encapsulation is

    as a protective wrapper that prevents the code and data from being arbitrarily accessed by

    other code defined outside the wrapper/class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    7/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    InheritanceInheritanceInheritanceInheritance

    Inheritanceis the process by which one object acquires the properties of another object. This is

    important because it supports the concept of hierarchical classification. Without the use of

    hierarchies, each object would need to define all of its characteristics explicitly. However, by

    use of inheritance, an object need only define those qualities that make it unique within its

    class. It can inherit its general attributes from its parent.

    PolymorphismPolymorphismPolymorphismPolymorphism

    Polymorphism(from the Greek, meaning many forms) is a feature that allows one interface to

    be used for a general class of actions. The specific action is determined by the exact nature of

    the situation. Polymorphism is a way by which an object can exhibit multiple behaviour in

    multiple instances or situations.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    8/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Class & Object:Class & Object:Class & Object:Class & Object:Class:Class:Class:Class: A class denotes a category of objects, and acts as a blueprint for creating such objects. A

    class models an abstraction by defining the properties and behaviors for the objects

    representing the abstraction. An object exhibits the properties and behaviors defined by its

    class. The properties of an object of a class are also called attributes, and are defined by fields in

    Java. A field in a class definition is a variable which can store a value that represents a

    particular property. The behaviors of an object of a class are also known as operations, and are

    defined using methods in Java. Fields and methods in a class definition are collectively called

    members.

    Object:Object:Object:Object: Class Instantiation:Class Instantiation:Class Instantiation:Class Instantiation: The process of creating objects from a class is called instantiation.

    An object is an instance of a class. The object is constructed using the class as a blueprint and is

    a concrete instance of the abstraction that the class represents. An object must be created

    before it can be used in a program. In Java, objects are manipulated through object references(also called reference values or simply references). The process of creating objects usually

    involves the following steps:

    1. Declaration of a variable to store the object referenceDeclaration of a variable to store the object referenceDeclaration of a variable to store the object referenceDeclaration of a variable to store the object reference ---- This involves declaring areference variable of the appropriate class to store the reference to the object.

    // Declaration of two reference variables that will denote/refer two distinct objects,

    ClassName ob1, ob2;

    2. Creating an objectCreating an objectCreating an objectCreating an object ---- This involves using the new operator in conjunction with a call to aconstructor, to create an instance of the class.

    // Create two distinct objects.

    Ob1 = new ClassName();

    Ob2 = new ClassName();

    The new operator returns a reference to a new instance of class. This reference can be

    assigned to a reference variable of the appropriate class. Each object has a unique

    identity and has its own copy of the fields declared in the class definition.

    The purpose of the constructor call on the right side of the new operator is to initialize

    the newly created object.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    9/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Constructors in Java:Constructors in Java:Constructors in Java:Constructors in Java: Constructors are special methods of class. A constructor initializes an object immediately after creation. Once defined, the constructor is automatically called immediately after the object is

    creation.Constructors look a little strange because :Constructors look a little strange because :Constructors look a little strange because :Constructors look a little strange because :

    They dont have any return type, not even void. It has the same name as the class in which it resides. The constructor is automatically invoked.

    Types OfTypes OfTypes OfTypes Of Constructors:Constructors:Constructors:Constructors:

    Default Constructor:Default Constructor:Default Constructor:Default Constructor: Constructor with zero parameter called default constructor.

    Parameterized Constructor:Parameterized Constructor:Parameterized Constructor:Parameterized Constructor: A constructor with one or more parameter calledparameterized constructor.

    ConstructorConstructorConstructorConstructor Example :Example :Example :Example :

    class ConstructorDemo {

    ConstructorDemo() {

    System.out.println(Default Constructor!!!);

    }

    ConstructorDemo(int a) {

    System.out.println(Parameterized Constructor!!!);

    }

    }

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    10/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Inheritance in Java:Inheritance in Java:Inheritance in Java:Inheritance in Java:

    Inheritance is the process by which one object acquires the properties of another object. This is

    important because it supports the concept of hierarchical classification. Without the use of

    hierarchies, each object would need to define all of its characteristics explicitly. However, by

    use of inheritance, an object need only define those qualities that make it unique within itsclass. It can inherit its general attributes from its parent.

    FeaturesFeaturesFeaturesFeatures of Inheritance:of Inheritance:of Inheritance:of Inheritance:

    One of the key concepts of OOP. Establishes a hierarchical relationship among classes. Establishes a super class/sub class relationship. Establishes is a relationships. A super class defines a general set of functionality, whereas subclasses define

    functionalities specific to them.

    In other sense, inheritance in Java builds a hierarchy of classes & thus supports theconcept of classification.

    Inheritance is implemented in Java using extends keyword.

    Benefits ofBenefits ofBenefits ofBenefits of Inheritance:Inheritance:Inheritance:Inheritance:

    Reusability of code. Put code in one class, use it in all the subclasses. Write general purpose code designed for a super type that works for all subtypes.

    Points to Remember :Points to Remember :Points to Remember :Points to Remember :

    Private members of the super class are not accessible by the sub class and can only beindirectly accessed.

    Constructors and Initializer blocks are not inherited by a subclass.

    When you construct an object, the default base class constructor is called implicitly,before the body of the derived class constructor is executed. So, objects are constructed

    top-down under inheritance.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    11/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Example :Example :Example :Example :

    class A{

    A(){

    System.out.println("Default constructor of class A");

    }

    A(int val){

    System.out.println(Parameterized constructor of class A");

    }

    }

    class B extends A{

    B(){

    System.out.println("Default constructor of class B");

    }

    B(int val){

    System.out.println(Parameterized constructor of class B");

    }

    }

    Predict the output.Predict the output.Predict the output.Predict the output.

    B ref1 = new B();

    B ref2 = new B(5);

    Output :Output :Output :Output :

    Default constructor of class A

    Default constructor of class B

    Default constructor of class A

    Parameterised constructor of class B

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    12/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    InheritanceInheritanceInheritanceInheritance Example :Example :Example :Example :

    class Calculator {

    float num1, num2, ans;

    float add() {

    ans = num1 + num2;

    return ans;

    }

    float sub() {

    ans = num1 + num2;

    return ans;

    }

    float mul() {

    ans = num1 * num2;

    return ans;

    } }//End of Calculator Class

    class ScientificCalculator extends Calculator {

    float sqrt()

    {

    ans = (float)Math.sqrt(num1);

    return ans;

    } }//End of ScientificCalculator Class

    class CalculatorDemo {

    public static void main(String [] args) {

    ScientificCalculator sc = new ScientificCalculator();

    sc.num1 = 20.0f; sc.num2 = 10.0f;sc.add(); sc.sub();

    sc.mul(); sc.sqrt();

    } }//End of CalculatorDemo Class

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    13/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    String Handling in Java:String Handling in Java:String Handling in Java:String Handling in Java:

    Unlike many other languages that implement strings as character arrays, Java implements

    strings as objects of type java.lang.StringStringStringString.

    String are immutable objects in java means when you create a StringStringStringString object, you are creating a

    string that cannot be changed. That is, once a StringStringStringString object has been created, you cannotchange the characters that comprise that string.

    In some cases in which a modifiable string is desired, there is a companion class to StringStringStringString called

    StringBufferStringBufferStringBufferStringBuffer, whose objects contain strings that can be modified after they are created. Both the

    StringStringStringString and StringBufferStringBufferStringBufferStringBuffer classes are defined in java.langjava.langjava.langjava.lang. Thus, they are available to all programs

    automatically.

    Constructor Of String Class :Constructor Of String Class :Constructor Of String Class :Constructor Of String Class :

    String s = new String();String s = new String();String s = new String();String s = new String();

    String s = new String(abcd);String s = new String(abcd);String s = new String(abcd);String s = new String(abcd);

    char [] ch = {a,b,c,dchar [] ch = {a,b,c,dchar [] ch = {a,b,c,dchar [] ch = {a,b,c,d};};};};

    String s = new String(ch);String s = new String(ch);String s = new String(ch);String s = new String(ch);

    Using String Literal ;Using String Literal ;Using String Literal ;Using String Literal ;

    String s = abcd;String s = abcd;String s = abcd;String s = abcd;

    String Operation :String Operation :String Operation :String Operation :1.1.1.1. Concatenation :Concatenation :Concatenation :Concatenation :

    Method that concatenates two strings, producing a StringStringStringString object as the result.

    Eg :

    String s1 = abcd;

    String s2 = xyz;

    String s3 = s1.concat(s2); //Using concat method of String class.

    String s3 = s1 + s2; // Using + Operator for concatenation.

    2.2.2.2. Length :Length :Length :Length :Returns the length of String as integer represents number of character encapsulated in

    String objects

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    14/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Eg:

    String s = new String(Elephant);

    Int len = s.length(); // return 8

    3.3.3.3. Character Extraction :Character Extraction :Character Extraction :Character Extraction :char charAt(int index)

    byte [] getBytes()

    char [] toCharArray()

    4.4.4.4. Comparison :Comparison :Comparison :Comparison :boolean equals(String str ) and

    boolean equalsIgnoreCase(String str)

    Here, stris the StringStringStringString object being compared with the invoking StringStringStringString object.It returns truetruetruetrue if the strings contain the same characters in the same order, and falsefalsefalsefalse otherwise.

    The comparison is case-sensitive. To perform a comparison that ignores case differences, call

    equalsIgnoreCaequalsIgnoreCaequalsIgnoreCaequalsIgnoreCase( )se( )se( )se( ). When it compares two strings, it considers AAAA----ZZZZ to be the same as aaaa----zzzz.

    5.5.5.5. Other Utility Method :Other Utility Method :Other Utility Method :Other Utility Method :String toUpperCase()

    String toLowerCase()

    String trim()int indexOf(char)

    int indexOf(String str)

    .etc

    Java.lang.Java.lang.Java.lang.Java.lang.StringBufferStringBufferStringBufferStringBuffer :::: StringBuffer is a peer class of String, that represents mutable type

    String objects in Java.

    StringBufferStringBufferStringBufferStringBuffer defines these three constructors:

    StringBuffer( ) Default Constructor

    StringBuffer(int size) - int Defines size of String Object

    StringBuffer(String str) to get StringBuffer object from String object

    Example:Example:Example:Example:

    String s = new String(abc);

    StringBuffer sb = new StringBuffer(s);

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    15/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Package in Java:Package in Java:Package in Java:Package in Java:Java provides a mechanism for partitioning the class name space into more manageable

    chunks. This mechanism is the package. The package is both a naming and a visibility control

    mechanism. You can define classes inside a package that are not accessible by code outside that

    package.

    Defining a PackageDefining a PackageDefining a PackageDefining a Package

    To create a package is quite easy: simply include a packagepackagepackagepackage command as the first statement in a

    Java source file. Any classes declared within that file will belong to the specified package. The

    packagepackagepackagepackage statement defines a name space in which classes are stored.

    package MyPackage;

    Finding Packages and CLASSPATHFinding Packages and CLASSPATHFinding Packages and CLASSPATHFinding Packages and CLASSPATH

    As just explained, packages are mirrored by directories. This raises an important question: Howdoes the Java run-time system know where to look for packages that you create? The answer

    has two parts. First, by default, the Java run-time system uses the current working directory as

    its starting point. Thus, if your package is in the current directory, or a subdirectory of the

    current directory, it will be found. Second, you can specify a directory path or paths by setting

    the CLASSPATHCLASSPATHCLASSPATHCLASSPATH environmental variable.

    ImportingImportingImportingImporting Packages:Packages:Packages:Packages:

    Java includes the importimportimportimport statement to bring certain classes, or entire packages, into visibility.Once imported, a class can be referred to directly, using only its name. The importimportimportimport statement is

    a convenience to the programmer and is not technically needed to write a complete Java

    program. If you are going to refer to a few dozen classes in your application, however, the

    importimportimportimport statement will save a lot of typing. In a Java source file, importimportimportimport statements occur

    immediately following the packagepackagepackagepackage statement (if it exists) and before any class definitions.

    This is the general form of the importimportimportimport statement:

    import pack1.subaack.* or class/interface Name

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    16/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Package Example :Package Example :Package Example :Package Example :

    SourceCode : Message.javaSourceCode : Message.javaSourceCode : Message.javaSourceCode : Message.java

    package com;

    public class Message {

    public void showMessage(String name) {

    System.out.println("Hello "+name);}

    } // End Of Message Class

    Compiling Message.javaCompiling Message.javaCompiling Message.javaCompiling Message.java javacjavacjavacjavac d . Message.javad . Message.javad . Message.javad . Message.java

    SourceCode : TestSourceCode : TestSourceCode : TestSourceCode : Test.java.java.java.java

    import com.Message;

    class Test {

    public static void main(String [] args) {Message m = new Message();

    m.showMessage("United, Allahabad");

    }

    }//End Of Test Class.

    Compile and Run Test.javaCompile and Run Test.javaCompile and Run Test.javaCompile and Run Test.java javac Test.javajavac Test.javajavac Test.javajavac Test.java

    javajavajavajava TestTestTestTest

    OutputOutputOutputOutput Hello United, AllahabadHello United, AllahabadHello United, AllahabadHello United, Allahabad

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    17/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Access ProtectionAccess ProtectionAccess ProtectionAccess Protection::::Classes and packages are both means of encapsulating and containing the name space and

    scope of variables and methods. Packages act as containers for classes and other subordinate

    packages. Classes act as containers for data and code. The class is Javas smallest unit of

    abstraction. Because of the interplay between classes and packages,Java addresses four categories of visibility for class members:

    Subclasses in the same package Non-subclasses in the same package Subclasses in different packages Classes that are neither in the same package nor subclasses

    The three access specifiers, privateprivateprivateprivate, publicpublicpublicpublic, and protectedprotectedprotectedprotected, provide a variety of ways to producethe many levels of access required by these categories. While Javas access control mechanism

    may seem complicated, we can simplify it as follows:

    PUBLIC :PUBLIC :PUBLIC :PUBLIC : Anything declared publicpublicpublicpublic can be accessed from anywhere.

    PRIVATE :PRIVATE :PRIVATE :PRIVATE : Anything declared privateprivateprivateprivate cannot be seen outside of its class.

    DEFAULT :DEFAULT :DEFAULT :DEFAULT : When a member does not have an explicit access specification, it is visible to

    subclasses as well as to other classes in the same package. This is the default access.

    PROTECTED :PROTECTED :PROTECTED :PROTECTED : If you want to allow an element to be seen outside your current package, but

    only to classes that subclass your class directly, then declare that element protecprotecprotecprotectedtedtedted....

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    18/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Abstract methods and classes:Abstract methods and classes:Abstract methods and classes:Abstract methods and classes:An abstract method is a method that's been declared(as abstract) but not implemented.

    In other words, the method contains no functional code. And if you recall from the

    earlier section " Abstract Classes," an abstract method declaration doesn't even have curly

    braces for where the implementation code goes, but instead closes with a semicolon. Inother words, it has no method body. You mark a method abstract when you want to

    force subclasses to provide the implementation.

    A super class that only defines a generalized form that will be shared by all its subclasses, leaving the implementation details to its subclasses is said to an abstract class.

    A concrete class has concrete methods, including implementations of any abstractmethods inherited from its super classes.

    Any class with abstract methods should be declared abstract.Abstract Method & ClassAbstract Method & ClassAbstract Method & ClassAbstract Method & Class Example :Example :Example :Example :

    abstractabstractabstractabstract class Shape { //abstract class

    abstractabstractabstractabstract double area(); //abstract method

    void displayDetail() { //concrete method

    System.out.println(Showing Details of Shape.);

    }

    }

    class Square extends Shape{

    double side;

    double area() { //Overriding the abstract method.

    return side*side;}

    }

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    19/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Pointes to remember : Abstract classePointes to remember : Abstract classePointes to remember : Abstract classePointes to remember : Abstract classes and methodss and methodss and methodss and methods An abstract class cannot have objects because it is not complete, but it can have

    references.

    Eg :Eg :Eg :Eg : Shape s = new Square();

    Static methods and constructors cannot be declared abstract.Eg:Eg:Eg:Eg: abstract static void show();

    Any subclass of an abstract class must either implement all the abstract methods in thesuper class or be itself declared abstract.

    A concrete method can be overridden to become abstract. It is illegal to declare a class and method both final and abstract.

    Eg:Eg:Eg:Eg: abstract final void show();

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    20/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Interface in Java:Interface in Java:Interface in Java:Interface in Java: Javas interfaces are an improvement over multiple inheritance mechanism of C++. While designing a software system in java, Interfaces help us defining the interfaces

    between the components.

    Interfaces help us achieve a special kind of multiple inheritance : multipleinheritance of interfaces without multiple inheritance of implementation.

    When you create an interface, you're defining a contract for whata class can do,

    without saying anything about how the class will do it. An interface is a contract.

    Interfaces can be implemented by any class, from any inheritance tree. This lets you

    take radically different classes and give them a common characteristic.

    But while an abstract class can define both abstract and non-abstract methods, an

    interface can have only abstract methods. Another way interfaces differ from abstract

    classes is that interfaces have very little flexibility in how the methods and variables

    defined in the interface are declared.

    These rules areThese rules areThese rules areThese rules are strict:strict:strict:strict:

    All interface methods are implicitly public and abstract. In other words, you do not needto actually type the public or abstract modifiers in the method declaration, but themethod is still always public and abstract.

    All variables defined in an interface must be public, static, and finalin other words,interfaces can declare only constants, not instance variables.

    Interface methods must not be static. Because interface methods are abstract, they cannot be marked final. An interface can extendone or more other interfaces. An interface cannot extend any class.

    An interface cannot implement another interface or class. An interface must be declared with the keyword interface.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    21/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    InterfaceInterfaceInterfaceInterface Example :Example :Example :Example :

    interface Shape {

    float PI = 3.14F; //by default public, static and final

    float area(); //by default public and abstract

    }

    class Square implements Shape {

    float side ;

    public void area() { //overriding area method of Shape Interface

    return side*side

    }

    }

    class ShapeDemo {

    public static void main(String [] ar) {

    Square s = new Square();

    s.side = 2.3f;

    float sarea = s.area();

    System.out.println(AREA IS : +sarea);

    }

    }

    OUTPUT:OUTPUT:OUTPUT:OUTPUT:

    AREA IS : 5.29

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    22/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Polymorphism:Polymorphism:Polymorphism:Polymorphism:Polymorphism(from the Greek, meaning many forms) is a feature that allows one

    interface to be used for a general class of actions. The specific action is determined by

    the exact nature of the situation. Polymorphism is a way by which an object can

    exhibit multiple behaviour in multiple instances or situations.

    Types of polymorphism:Types of polymorphism:Types of polymorphism:Types of polymorphism: Compile Time Polymorphism Method Overloading Run Time Polymorphism Method Overriding

    Method Overloading :Method Overloading :Method Overloading :Method Overloading :Method overloading is a mechanism by which we can create more than one method

    with the same name in the same class but their parameter or argument list should

    be different.When this is the case, the methods are said to be overloaded, and theprocess is referred to as method overloading.

    When an overloaded method is invoked, Java uses the type and/or number of

    arguments as its guide to determine which version of the overloaded method to

    actually call. Thus, overloaded methods must differ in the type and/or number of

    their parameters. While overloaded methods may have different return types, the

    return type alone is insufficient to distinguish two versions of a method. When Java

    encounters a call to an overloaded method, it simply executes the version of themethod whose parameters match the arguments used in the call.

    We can overload the method by any one of the following changes in argument list:

    Change the number of arguments. Change the type of arguments. Change the order of arguments.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    23/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Method Overloading Example :Method Overloading Example :Method Overloading Example :Method Overloading Example :

    class Result {

    void showResult() {

    //Display the result of all students.

    System.out.println("Display Results);

    }

    void showResult(String rollno) {

    //Display the result of a student whose rollno is passed as argument.

    System.out.println("Display Result : "+rollno);

    }

    }

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

    Result ob = new Result();

    ob.showResult();

    ob.showResult("0901010071");

    }

    }

    Output:Output:Output:Output:

    Display Results

    Display Result : 0901010071.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    24/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Method Overriding :Method Overriding :Method Overriding :Method Overriding :

    In a class hierarchy, when a method in a subclass has the same name and type signature

    as a method in its super class, then the method in the subclass is said to overridethe

    method in the super class. When an overridden method is called from within a subclass,

    it will always refer to the version of that method defined by the subclass

    MethodMethodMethodMethod Overriding Example :Overriding Example :Overriding Example :Overriding Example :

    class Alto {{{{

    void speedoMeter() {{{{

    System.out.println("Analog System.");

    }}}}

    void breakControl() {{{{

    System.out.println("Power Break System.");

    }}}} }}}}//End Of Alto Class

    class AltoK10 extendsextendsextendsextends Alto {{{{

    void speedoMeter() {{{{

    System.out.println("Digital System.");

    }}}} }}}}//End Of AltoK10 Class

    class TestDrive {{{{

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

    Alto ob1 = new Alto();

    Alto ob2 = new AltoK10();

    ob1.speedoMeter(); ob1.breakControl();

    ob2.speedoMeter(); ob2.breakControl();

    }}}} }}}} //End Of TestDrive Class

    Output :Output :Output :Output :Analog System.

    Power Break System.

    Digital System.

    Power Break System.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    25/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Inner / Member Classes:Inner / Member Classes:Inner / Member Classes:Inner / Member Classes:Sometimes, though, you find yourself designing a class where you discover you need

    behavior that belongs in a separate, specialized class, but also needs to be intimately tied

    to the class youre designing.

    Member classes let you define one class within another. They provide a type of scoping for your classes since you can make one class a

    member of another class.

    Just as classes have member variables and methods, a class can also have memberclasses.

    Types of Member Class :Types of Member Class :Types of Member Class :Types of Member Class :o Inner Class.o Nested Class.o Method Local Inner Class.o Anonymous Inner Class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    26/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Inner Class :Inner Class :Inner Class :Inner Class :o One of the key benefits of an inner class is the special relationship an inner

    class instance shares with an instance of the outer class.

    o That special relationship gives code in the inner class access to members of theenclosing (outer) class.

    o An inner class instance has access to all members of the outer class, even thosemarked private.

    o The members of inner of class cannot be declared as static.Inner Class Example :Inner Class Example :Inner Class Example :Inner Class Example :

    class Outer {

    void show() {

    System.out.println("Hello From Show of Outer Class.");

    }

    class Inner {

    void display() {

    System.out.println("Hello From Display of Inner Class.");

    }

    }//End Of Inner Class

    }//End Of Outer Class

    class MemberClassDemo {

    public static void main(String [] args) {

    Outer o = new Outer();

    o.show();

    Outer.Inner i = o.new Inner();

    //or

    Outer.Inner i = new Outer.new Inner();

    i.display();

    }

    }//End Of MemberClassDemo

    Output :Output :Output :Output :

    Hello From Show of Outer Class.

    Hello From Display of Inner Class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    27/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Nested Class :Nested Class :Nested Class :Nested Class :o If we mark or specify the member class as static that member class is called

    Nested Class.

    o Nested Class can have static member data and methods.o We can instantiate static member class outside the outer class without object of

    outer class.

    NestedNestedNestedNested Class Example :Class Example :Class Example :Class Example :

    class Outer {

    static class Nested {

    void display() {

    System.out.println("Hello From Display of Nested Class.");}

    static void show() {

    System.out.println("Hello From Static Show of Nested Class.");

    }

    }//End Of Nested Class

    }//End Of Outer Class

    class MemberClassDemo {

    public static void main(String [] args) {

    Outer.Nested.show();

    Outer.Nested n = Outer.new Nested();

    n.display();

    }

    }//End Of MemberClassDemo

    Output :Output :Output :Output :

    Hello From Static Show of Nested Class.

    Hello From Display of Nested Class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    28/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Method Local Inner Class (MLIC):Method Local Inner Class (MLIC):Method Local Inner Class (MLIC):Method Local Inner Class (MLIC):o We can define class with in a method that type of classes are called method local

    inner class.

    o A method-local inner class can be instantiated only within the method wherethe inner class is defined.

    o We cant mark a method-local inner class as public, private, protected, static,transient . The only modifiers you can apply to a method-local inner class are

    abstract and final.

    MLI Class Demo :MLI Class Demo :MLI Class Demo :MLI Class Demo :

    class Test {

    void show() {class Local {

    void print() {

    System.out.println("Hello From Local Inner Class.");

    }

    }//End Of Local Class

    Local l = new Local();

    l.print();

    }

    }//End Of Test Class

    class MLICDemo {

    public static void main(String [] ar) {

    Test t = new Test();

    t.show();

    }

    }//End Of MLICDemo Class.

    Output :Output :Output :Output :

    Hello From Local Inner Class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    29/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Anonymous Inner Class :Anonymous Inner Class :Anonymous Inner Class :Anonymous Inner Class :o An anonymousinner class is one that is not assigned a name.o Were going to look at the most unusual syntax you might ever see in Java, inner

    classes declared without any class name at all (hence the word anonymous).

    Anonymous Inner Class Example :Anonymous Inner Class Example :Anonymous Inner Class Example :Anonymous Inner Class Example :

    class Test {

    void show() {

    System.out.println("Hello World from United!!!");

    }

    }//End Of Test Class

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

    Test t1 = new Test();

    //Anonymous Inner Class//Anonymous Inner Class//Anonymous Inner Class//Anonymous Inner Class

    Test t2 = new Test(){{{{

    void show() {

    System.out.println("Hello World from UCER!!!");

    }

    };};};}; //End Of Anonymous Inner Class//End Of Anonymous Inner Class//End Of Anonymous Inner Class//End Of Anonymous Inner Class

    t1.show();

    t2.show();

    }

    }//End Of AICDemo Class

    OutpuOutpuOutpuOutput :t :t :t :

    Hello World from United!!!

    Hello World from UCER!!!

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    30/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Java IO (InputJava IO (InputJava IO (InputJava IO (Input----Output)Output)Output)Output)Java programs perform Input Output through streams. A stream is an abstraction that

    either produces or consumes information. A streamstreamstreamstream is simply a sequence of bytes that flows

    into or out of our program. Its an abstract representation of an input or output device.

    A stream is linked to a physical device by the Java IO stream. All streams behave in the same manner even if the actual physical devices to

    which they are linked differ.

    Thus, the same IO classes and method can be applied to any type of decvice. This means that an input stream can abstract many different kinds of input:

    from a disk file, a keyboard or a network socket.

    Java implements stream within class hierarchies define in the java.iojava.iojava.iojava.io package.Types Of Streams:Types Of Streams:Types Of Streams:Types Of Streams:

    o Byte or Binary Stream.o Character Stream.

    Byte/Binary Stream :Byte/Binary Stream :Byte/Binary Stream :Byte/Binary Stream :Byte stream provide a convenient means for handling IO of bytes. Byte streams are

    used for example, when reading and writing binary data.

    Byte streams are defined by using two class hierarchies. At the top are two abstract

    class: java.io.InputStreamjava.io.InputStreamjava.io.InputStreamjava.io.InputStream and java.io.OutputStreamjava.io.OutputStreamjava.io.OutputStreamjava.io.OutputStream. Each of these abstract classes has

    several concrete sub classes, that handle the differences between various devices. The

    abstract classes InputStreamInputStreamInputStreamInputStream and OutputStreamOutputStreamOutputStreamOutputStream several key methods, that the other

    stream classes implement. Two of the most important methods are read()read()read()read() and write(),write(),write(),write(),

    which respectively read and write bytes of data. Both methods are declared as abstract

    inside InputStream and OutputStream. They are overridden by drived stream classes.

    int read() throws IOExceptionint read() throws IOExceptionint read() throws IOExceptionint read() throws IOExceptionReturns the next byte available from the stream as type int. If the end of the

    stream is reached, the method will return the value -1.

    inininint read(bytet read(bytet read(bytet read(byte [] array) throws IOException[] array) throws IOException[] array) throws IOException[] array) throws IOExceptionThis method reads bytes from the stream into successive elements of

    array. The maximum of array.length bytes will be read.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    31/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Similarly, we have methods for writing byte to stream;

    void writevoid writevoid writevoid write((((int dataint dataint dataint data) throws IOE) throws IOE) throws IOE) throws IOExceptionxceptionxceptionxception void writevoid writevoid writevoid write(byte(byte(byte(byte [] array) throws IOException[] array) throws IOException[] array) throws IOException[] array) throws IOException

    Character Stream:Character Stream:Character Stream:Character Stream:Character streams provide a convenient means for handling IO of characters. They

    use Unicode and therefore internationalized. Also, in some cases character stream are

    more efficient than byte stream.

    Character streams are defined by using two class hierarchies. At the top are two abstract

    class: java.io.java.io.java.io.java.io.ReaderReaderReaderReader and java.io.java.io.java.io.java.io.WriterWriterWriterWriter. These abstracter class handle Unicode character

    streams. Java has several concrete subclasses of each of these. . The abstract classes

    ReaderReaderReaderReader and WriterWriterWriterWriter several key methods, that the other stream classes implement. Two of

    the most important methods are read()read()read()read() and write()write()write()write()....

    Methods for performing character based reading operation:

    int readint readint readint read(((( ) throws IOExcept) throws IOExcept) throws IOExcept) throws IOExceptionionionion int readint readint readint read((((char [] arraychar [] arraychar [] arraychar [] array) throws IOException) throws IOException) throws IOException) throws IOExceptionMethods for performing character based writing operation:

    void writevoid writevoid writevoid write((((int dataint dataint dataint data) throws IOException) throws IOException) throws IOException) throws IOException void write(charvoid write(charvoid write(charvoid write(char [] array) throws IOException[] array) throws IOException[] array) throws IOException[] array) throws IOException

    Read User Input from Standard IORead User Input from Standard IORead User Input from Standard IORead User Input from Standard IO ::::Java does not have a generalized and standard console input methods like

    scanf(), getc(), and gets() functions of C language. In Java, console input is accomplished

    by reading from System.inSystem.inSystem.inSystem.in (represents Standard Input Device i.e. Keyboard). We wrap

    System.inSystem.inSystem.inSystem.inin a BufferedReader, Scanner, DataInputStream..etc type objects to performread operation. BufferedReader supports buffered input stream, it is most commonly

    used for taking user input in Java.

    UsingUsingUsingUsing java.io.BufferReaderjava.io.BufferReaderjava.io.BufferReaderjava.io.BufferReader classclassclassclass::::----

    InputStreamReader isr = new InputStreamReader(System.in);

    BufferedReader br = new BufferedReader(isr);

    System.out.println(Please Enter Your Name : );

    String name = br.readLine();

    System.out.println(Hello : +name);

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    32/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    File Handling in Java:File Handling in Java:File Handling in Java:File Handling in Java:Java provides a number of classes and methods that allow you to read and write files.

    In Java, all files are byte-oriented, and Java provides methods to read and write bytes

    from and to a file. However, Java allows you to wrap a byte-oriented file stream within

    a character-based object. This technique is described in Part II. This chapter examines

    the basics of file I/O.

    Two of the most often-used stream classes are FileInputStreamFileInputStreamFileInputStreamFileInputStream and FileOutputStreamFileOutputStreamFileOutputStreamFileOutputStream,

    which create byte streams linked to files. To open a file, you simply create an object of

    one of these classes, specifying the name of the file as an argument to the constructor.

    While both classes support additional, overridden constructors,

    FileInputStream(String fileName) throws FileNotFoundException

    FileOutputStream(String fileName) throws FileNotFoundException

    FileOutputStream(String filename,boolean mode) throws FileNotFoundException

    The FileReaderFileReaderFileReaderFileReader and FileWriterFileWriterFileWriterFileWriter classes creates a ReaderReaderReaderReader and Writerand Writerand Writerand Writer that you can use to

    read and write the contents from and to a file. Its most commonly used constructors are

    shown here:

    FileReader(String filePath) throws FileNotFoundException

    FileWriter(String filePath)throws IOException

    FileWriter(String filePath, boolean mode)throws IOException

    FileFileFileFile Content:

    Content:Content:Content: Data.txt

    Data.txtData.txtData.txt

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    33/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    File Reading Example :File Reading Example :File Reading Example :File Reading Example : Read File(DRead File(DRead File(DRead File(Data.ata.ata.ata.txt) Content byte by bytetxt) Content byte by bytetxt) Content byte by bytetxt) Content byte by byte

    import java.io.*;

    class ReadFileByteByByte {

    public static void main(String [] args) throws Exception {

    FileInputStream fis = new FileInputStream("Data.txt");

    int ch;while(true) { //infinite loop

    ch = fis.read();

    if(ch==-1) { //Check for EOF(End Of File)

    break;

    }

    System.out.print((char)ch);

    }//End Of While Block.

    }//End Of Main Method.}//End Of ReadFileByteByByte Class.

    File Reading Example :File Reading Example :File Reading Example :File Reading Example : Read File(DRead File(DRead File(DRead File(Data.txt) Content Line Byata.txt) Content Line Byata.txt) Content Line Byata.txt) Content Line By LineLineLineLine

    import java.io.*;

    class ReadFileLineByLine {

    public static void main(String [] args) throws Exception {

    FileInputStream fis = new FileInputStream("Data.txt");

    InputStreamReader isr = new InputStreamReader(fis);

    BufferedReader br = new BufferedReader(isr);

    String line;

    while(true) { //infinite loop

    line = br.readLine();

    if(line==null) { //Check for EOL(End Of Line)

    break;

    }

    System.out.println(line);

    }//End Of While Block.}//End Of Main Method.

    }//End Of ReadFileLineByLine Class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    34/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    File WritingFile WritingFile WritingFile Writing Example :Example :Example :Example : WriteWriteWriteWrite Content toContent toContent toContent to File(File(File(File(WriteDWriteDWriteDWriteData.txt) byte by byteata.txt) byte by byteata.txt) byte by byteata.txt) byte by byte

    import java.io.*;

    class WriteFileByteByByte {

    public static void main(String [] args) throws Exception {

    FileOutputStream fos = new FileOutputStream("WriteData.txt");

    String data = "Pepsi - Nothing Official About It.";for(int i=0;i

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    35/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Exception Handling in JavaException Handling in JavaException Handling in JavaException Handling in Java::::What is an Exception ?What is an Exception ?What is an Exception ?What is an Exception ?

    Exception is an abnormal condition that occurs during the execution of a program, &

    due to which the normal flow of the program's instructions may disrupt.

    For exampleFor exampleFor exampleFor example::::----

    class Test{

    public static void main(String[] args){

    System.out.println("Hello");

    System.out.println(5/0);

    System.out.println("Hello Again");

    // do something else

    }}

    outputoutputoutputoutput

    Hello

    Exception in thread "main" java.lang.ArithmeticException: / by zero

    at NewClass.main(NewClass.java:3)

    Throwing an Exception:Throwing an Exception:Throwing an Exception:Throwing an Exception:

    When an error occurs within a method, the run-time system creates an object and

    hands it off to the method. The object, called an exception object, contains information

    about the error, including its type and the state of the program when the error

    occurred. Creating an exception object and handing it to the relevant method is called

    throwing an exception.

    After a method throws an exception, the runtime system attempts to find the ordered list

    of methods that had been called to get to the method where the error occurred. The list

    of methods is known as the call stack.call stack.call stack.call stack.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    36/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Exception Handler:Exception Handler:Exception Handler:Exception Handler:

    The runtime system searches the call stack for a method that contains a block of codethat can handle the exception. This block of code is called an exception handler.exception handler.exception handler.exception handler.

    The search begins with the method in which the error occurred and proceeds throughthe call stack in the reverse order in which the methods were called.

    When an appropriate handler is found, the runtime system passes the exception objectto the handler.

    An exception handler is considered appropriate if the type of the exception objectthrown matches the type that can be handled by the handler.

    HandlingHandlingHandlingHandling an Exceptionan Exceptionan Exceptionan Exception::::

    Java exception handling is managed via five keywords: trytrytrytry, catchcatchcatchcatch, finallyfinallyfinallyfinally,,,, throwthrowthrowthrow, and

    throwsthrowsthrowsthrows. Briefly, here is how they work. Program statements that you want to monitor for

    exceptions are contained within a trytrytrytry block. If an exception occurs within the trytrytrytry block,

    it is thrown. Your code can catch this exception (using catchcatchcatchcatch) and handle it in some

    rational manner. System-generated exceptions are automatically thrown by the Java

    run-time system. To manually throw an exception, use the keyword throwthrowthrowthrow. Any

    exception that is thrown out of a method must be specified as such by a throwsthrowsthrowsthrows clause.

    Any code that absolutely must be executed before a method returns is put in a finallyfinallyfinallyfinally

    block.

    This is the general form of an exception-handling block:trytrytrytry {

    // block of code to monitor for errors

    }

    catchcatchcatchcatch (ExceptionType1 exOb) {

    // exception handler for ExceptionType1

    }

    catchcatchcatchcatch (ExceptionType2 exOb) {

    // exception handler for ExceptionType2}

    // ...

    finallyfinallyfinallyfinally {

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

    }

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    37/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Type Of Exception:Type Of Exception:Type Of Exception:Type Of Exception:All exception types are subclasses of

    the built-in class ThrowableThrowableThrowableThrowable. Thus,

    ThrowableThrowableThrowableThrowable is at the top of the

    exception class hierarchy.

    Immediately below ThrowableThrowableThrowableThrowable are

    two subclasses that partition

    exceptions into two distinct

    branches. One branch is headed by

    ExceptioExceptioExceptioExceptionnnn. This class is used for

    exceptional conditions that user

    programs should catch. This is also

    the class that you will subclass to create your own custom exception types. There is an

    important subclass of ExceptionExceptionExceptionException, called RuntimeExceptionRuntimeExceptionRuntimeExceptionRuntimeException.

    Points To RemePoints To RemePoints To RemePoints To Remember:mber:mber:mber:o java.lang.Exceptionjava.lang.Exceptionjava.lang.Exceptionjava.lang.Exception and its sub classes are checked or compile time exception.o For checked exceptions, compiler prompts either to provide exception handler

    block or exception to be thrown.o java.lang.RuntimeExceptionjava.lang.RuntimeExceptionjava.lang.RuntimeExceptionjava.lang.RuntimeException and its sub classes are unchecked or run time

    exception.o For unchecked exceptions, compiler does not prompt to provide handler.o Exception handler blocks contains trytrytrytry, catchcatchcatchcatch and finallyfinallyfinallyfinally(optional) blocks.o A trytrytrytry block can be associated with zero or more catchcatchcatchcatch blocks.o trytrytrytry block can be associated with zero or one finallyfinallyfinallyfinally block.o Each trytrytrytry statement requires at least one catchcatchcatchcatch or a finallyfinallyfinallyfinally block.o We cannot write catchcatchcatchcatch or finallyfinallyfinallyfinally block without trytrytrytry block.o The finallyfinallyfinallyfinally block will execute whether or not an exception is thrown.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    38/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Exception HandlingException HandlingException HandlingException Handling ExampExampExampExample :le :le :le :

    class Calculator {

    void divide(int a,int b) {

    try {

    System.out.println(Result : +(a/b));

    }catch(ArithmeticException ae) {

    System.out.println("Error Found : "+ae.getMessage());

    }

    finally {

    System.out.println("Task Completed.");

    }

    } // End Of Divide Method.

    } // End Of Calulator Class.

    class TestCalulator {

    public static void main(String [] ar) {

    Calculator ob = new Calculator();

    ob.divide(20,10);

    ob.divide(20, 0);

    } //End Of Main Method.

    } //End Of TestCalculator Class.

    Output:Output:Output:Output:

    Result : 2

    Task Completed.

    Error Found : java.lang.ArithmeticException: /by zero

    Task Completed.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    39/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    throw Keyword:throw Keyword:throw Keyword:throw Keyword:So far, you have only been catching exceptions that are thrown by the Java run-time

    system. However, it is possible for your program to throw an exception explicitly, using

    the throwthrowthrowthrow statement. The general form of throwthrowthrowthrow is shown here:

    throwThrowableInstance;

    Here, ThrowableInstance must be an object of type ThrowableThrowableThrowableThrowable or a subclass of

    ThrowableThrowableThrowableThrowable.

    The flow of execution stops immediately after the throwthrowthrowthrow statement; any subsequent

    statements are not executed. The nearest enclosing trytrytrytry block is inspected to see if it has a

    catchcatchcatchcatch statement that matches the type of the exception. If it does find a match, control is

    transferred to that statement. If not, then the next enclosing trytrytrytry statement is inspected,

    and so on.

    throw Example :throw Example :throw Example :throw Example :

    class ThrowDemo {

    public static void main(String args[]) {

    int a = 10;

    int b = 20;

    int c = a / b;

    if(c < 1){

    ArithmeticException ae = new ArithmeticException(Denominator is Greater);

    throw ae;

    }

    System.out.println(Division : +c);

    }//End Of Main

    }//End Of ThrowDemo class

    Output :Output :Output :Output :

    Exception in thread "main" java.lang.ArithmeticException: Denominator is Greater.

    at NewClass.main(NewClass.java:8)

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    40/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    MultiMultiMultiMulti----Threading:Threading:Threading:Threading:Unlike most other computer languages, Java provides built-in support for multithreaded

    programming. A multithreaded program contains two or more parts that can run

    concurrently. Each part of such a program is called a thread, and each thread defines a

    separate path of execution. Thus, multithreading is a specialized form of multitasking.

    The benefit of Javas multithreading is that the main loop/polling mechanism is

    eliminated. One thread can pause without stopping other parts of your program. For

    example, the idle time created when a thread reads data from a network or waits for

    user input can be utilized elsewhere. Multithreading allows animation loops to sleep for

    a second between each frame without causing the whole system to pause. When a thread

    blocks in a Java program, only the single thread that is blocked pauses. All other threads

    continue to run.

    Life Cycle Of Thread :Life Cycle Of Thread :Life Cycle Of Thread :Life Cycle Of Thread :Threads exist in several

    states. A thread can be

    running. It can be ready to

    run as soon as it gets CPU

    time. A running thread can

    be suspended, which

    temporarily suspends its

    activity. A suspended thread

    can then be resumed,

    allowing it to pick up where

    it left off. A thread can be

    blockedwhen waiting for a

    resource. At any time, a

    thread can be terminated, which halts its execution immediately. Once terminated, a

    thread cannot be resumed.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    41/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Implementing MultiImplementing MultiImplementing MultiImplementing Multi----Threading in Java :Threading in Java :Threading in Java :Threading in Java :In Java, Multi-Threading can be implement in two different ways. That is

    by

    Extending java.lang.Thread class Implementing java.lang.Runnable interface.

    Extending java.lang.Thread class:Extending java.lang.Thread class:Extending java.lang.Thread class:Extending java.lang.Thread class:class MyThread extends Thread {

    public void run() { // overriding run

    // code that the thread will execute

    }

    }

    ------------------------------------------------

    public static void main(String[] args) {

    Thread t = new MyThread();

    t.start(); // creating a thread executing a task parallel to others// code the main thread will execute

    }

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    42/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Implementing java.lang.Runnable Interface:Implementing java.lang.Runnable Interface:Implementing java.lang.Runnable Interface:Implementing java.lang.Runnable Interface:class MyThread implements Runnable {

    public void run() { // overriding run

    // code that the thread will execute

    }

    }

    ------------------------------------------------

    public static void main(String[] args) {

    Runnable r = new MyThread();

    Thread t = new Thread( r );

    t.start(); // creating a thread executing a task parallel to others

    // code the main thread will execute

    }

    Methods Of Runnable Interface:Methods Of Runnable Interface:Methods Of Runnable Interface:Methods Of Runnable Interface:o pulic void run() Defines the JOB/TASK of the thread.

    Methods Of ThreadMethods Of ThreadMethods Of ThreadMethods Of Thread ClassClassClassClasso String getName() -Obtain a threads name.o

    int getPriority() - Obtain a threads priority.o void setPriority(int prioritiy) - Set a threads priority.o void setName(String name) - Set a threads name.o boolean isAlive() - Determine if a thread is still running.o void join() - Wait for a thread to terminate.o void run() - Entry point for the thread.o start() - Start a thread by calling its run method.o boolean isDaemon() - Checks wheather thread is daemon or not.o void setDaemon(boolean state) - Makes daemon thread.o static void sleep(long time) - Suspend a thread for a period of time.o void suspend() - Send active thread to wait state.o void resume() - Resumes suspended thread from wait to active state.o void stop() - Terminate active thread.o static Thread currentThread() - Returns the reference of current Thread.o int activeCount() - Returns the number of active threads.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    43/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Thread Example : To print thread name & priority.Thread Example : To print thread name & priority.Thread Example : To print thread name & priority.Thread Example : To print thread name & priority.

    class ThreadDemo {

    public static void main(String [] ar) {

    Thread t = Thread.currentThread();

    System.out.printlb("Thread Name : "+t.getName());

    System.out.printlb("Thread Priority : "+t.getPriority());}//End Of Main

    }//End Of ThreadDemo.

    Output:Output:Output:Output:

    Thread Name: main

    Thread Priority: 5

    Thread Example : To print digital clock on console.Thread Example : To print digital clock on console.Thread Example : To print digital clock on console.Thread Example : To print digital clock on console.

    import java.util.Date;class ClearScreen extends Thread {

    public void run() {

    while(true) {

    System.out.print("\r");

    try {

    Thread.sleep(1000); }catch(Exception e){}

    } //End Of While Loop

    }//End Of run method }//End Of ClearScreen class

    class ThreadDemo {

    public static void main(String ... a)throws Exception {

    ClearScreen cs = new ClearScreen();

    cs.start();

    while(true) {

    Date d = new Date();

    System.out.printf("%tr",d);

    Thread.sleep(1000);}//End Of While Loop

    }//End Of main method }//Enf Of ThreadDemo class

    Output :Output :Output :Output :

    03:53:27 pm

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    44/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    SynchronizationSynchronizationSynchronizationSynchronizationWhen two or more threads need access to a shared resource, they need some way to

    ensure that the resource will be used by only one thread at a time. The process by which

    this is achieved is called synchronization. As you will see, Java provides unique,

    language-level support for it.

    Key to synchronization is the concept of the monitor (also called a semaphore). A

    monitoris an object that is used as a mutually exclusive lock, or mutex. Only one thread

    can owna monitor at a given time. When a thread acquires a lock, it is said to have

    entered the monitor. All other threads attempting to enter the locked monitor will be

    suspended until the first thread exits the monitor. These other threads are said to be

    waitingfor the monitor.

    Using Synchronized MethodsUsing Synchronized MethodsUsing Synchronized MethodsUsing Synchronized Methods ----Synchronization is easy in Java, because all objects have their own implicit monitor

    associated with them. To enter an objects monitor, just call a method that has been

    modified with the synchronizedsynchronizedsynchronizedsynchronized keyword. While a thread is inside a synchronized

    method, all other threads that try to call it (or any other synchronized method) on the

    same instance have to wait.

    synchronized return-type method-name(Argument-list) {

    // Method Body}

    TheTheTheThe SSSSynchronized Statementynchronized Statementynchronized Statementynchronized Statement/Block/Block/Block/Block ----While creating synchronizedsynchronizedsynchronizedsynchronized methods within classes that you create is an easy and

    effective means of achieving synchronization, it will not work in all cases. To

    understand why, consider the following. Imagine that you want to synchronize access

    to objects of a class that was not designed for multithreaded access. That is, the class

    does not use synchronizedsynchronizedsynchronizedsynchronized methods. Further, this class was not created by you, but by a

    third party, and you do not have access to the source code. Thus, you cant add

    synchronizedsynchronizedsynchronizedsynchronized to the appropriate methods within the class. How can access to an object

    of this class be synchronized? Fortunately, the solution to this problem is quite easy: You

    simply put calls to the methods defined by this class inside a synchronizedsynchronizedsynchronizedsynchronized block. This is

    the general form of the synchronizedsynchronizedsynchronizedsynchronized statement:

    synchronized(object) {

    // statements to be synchronized }

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    45/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    NetworkingNetworkingNetworkingNetworking in Javain Javain Javain Java::::The term network programming refers to writing programs that execute across

    multiple devices, in which the devices are all connected to each other using a

    network.

    The java.netjava.netjava.netjava.net package contains a collection of classes and interfaces that provide the

    low-level communication details, allowing you to write programs that focus on

    solving the problem at hand.

    In java network programming is done by using socket paradigm:

    What is SOCKETWhat is SOCKETWhat is SOCKETWhat is SOCKET ?:?:?:?:A network socket is a lot like an electrical socket. Various plugs around the network

    have a standard way of delivering their payload. Anything that understands the

    standard protocol can plug in to the socket and communicate.With electrical sockets, it doesnt matter if you plug in a lamp or a toaster; as long as

    they are expecting 60Hz, 115-volt electricity, the devices will work. Think how

    your electric bill is created. There is a meter somewhere between your house and

    the rest of the network. For each kilowatt of power that goes through that meter,

    you are billed. The bill comes to your address. So even though the electricity flows

    freely around the power grid, all of the sockets in your house have a particular

    address.

    The same idea applies to network sockets, except we talk about TCP/IP packets andIP addresses rather than electrons and street addresses.

    Internet Protocol (IP)Internet Protocol (IP)Internet Protocol (IP)Internet Protocol (IP) : is alow-level routing protocol that breaks datainto small packets and sends them to an address across a network, which

    does not guarantee to deliver said packets to the destination.

    Transmission Control Protocol (TCP) :Transmission Control Protocol (TCP) :Transmission Control Protocol (TCP) :Transmission Control Protocol (TCP) : is a higher-level protocol thatmanages to robustly string together these packets, sorting and

    retransmitting them as necessary to reliably transmit your data.

    User Datagram Protocol (UDP)User Datagram Protocol (UDP)User Datagram Protocol (UDP)User Datagram Protocol (UDP):::: sits next to TCP and can be used directlyto support fast, connectionless, unreliable transport of packets. UDP is a

    connection-less protocol that allows for packets of data to be transmitted

    between applications.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    46/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Reserved SocketsReserved SocketsReserved SocketsReserved SocketsOnce connected, a higher-level protocol ensues, which is dependent on which port you

    are using. TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these

    will seem familiar to you if you have spent any time surfing the Internet. Port number

    21 is for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP and the

    list goes on. It is up to each protocol to determine how a client should interact with the

    port.

    You often hear the term client/servermentioned in the context of networking.

    Server :Server :Server :Server :A server is anything that has some resource that can be shared. Thereare compute servers, which provide computing power;print servers, which

    manage a collection of printers; disk servers, which provide networked disk

    space; and web servers, which store web pages.

    Client :Client :Client :Client : A client is simply any other entity that wants to gain access to aparticular server. The interaction between client and server is just like the

    interaction between a lamp and an electrical socket. The power grid of the house

    is the server, and the lamp is a power client. The server is a permanently

    available resource, while the client is free to unplug after it is has been served.

    Socket Programming in Java:Socket Programming in Java:Socket Programming in Java:Socket Programming in Java:When a connection is made, the server creates a socket object on its end of thecommunication. The client and server can now communicate by writing to and

    reading from the socket.

    Socket provides the communication mechanism between two computers using TCP.

    A client program creates a socket on its end of the communication and attempts to

    connect that socket to a server.

    Java supports both the TCP and UDP protocol families. TCP is used for reliable

    stream-based I/O across the network. UDP supports a simpler, hence faster, point-

    to-point datagram-oriented model.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    47/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Java Network API :Java Network API :Java Network API :Java Network API :All java classes and interfaces for network programming lies in the package name

    java.net.java.net.java.net.java.net. Following are the main classes of java.net package responsible for basic

    networking operation:

    InetAddressInetAddressInetAddressInetAddress class:class:class:class:Whether you are making a phone call, sending mail, or establishing a connection across

    the Internet, addresses are fundamental. The InetAddressInetAddressInetAddressInetAddress class is used to encapsulate

    both the numerical IP address and the domain name for that address.

    The InetAddressInetAddressInetAddressInetAddress class has no visible constructors. To create an InetAddressInetAddressInetAddressInetAddress object, you

    have to use one of the available factory methods.

    Three commonly used InetAddressInetAddressInetAddressInetAddress factory methods are shown here:

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    48/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    InetAddress Example :InetAddress Example :InetAddress Example :InetAddress Example :

    import java.net.*;

    class InetDemo {

    public static void main(String args[]) throws UnknownHostException {

    InetAddress address = InetAddress.getLocalHost();

    System.out.println("Address : "+address);

    System.out.println("Host Address : "+address.getHostAddress());

    System.out.println("Host Name : "+address.getHostName());

    } // End Of main method.

    } // End Of InetDemo class.

    OUTPUT :OUTPUT :OUTPUT :OUTPUT :Address : United-Lab5/192.168.1.20

    Host Address : 192.168.1.20

    Host Name : United-Lab5

    ServerSocket class:ServerSocket class:ServerSocket class:ServerSocket class:The java.net.ServerSocketjava.net.ServerSocketjava.net.ServerSocketjava.net.ServerSocket class is used to create server that listen for either local

    machine or remote machine.The ServerSocket class has following contructors:

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    49/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    If the ServerSocket constructor does not throw an exception, it means that our

    application has successfully bound to the specified port and is ready for client

    request.

    The ServerSocket class has following instance method:

    Socket class:Socket class:Socket class:Socket class:The java.net.java.net.java.net.java.net.SocketSocketSocketSocket class is design to connect to server socket and initiate protocol

    exchanges. The client obtains a Socket object by instantiating one, whereas the sever

    obtains a Socket object from the return value of the accept() method.

    The Socket class has the following constructors:

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    50/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    The Socket class has following instance method:

    Example:Example:Example:Example: Client and Server interaction through console.

    SOURCE : ServerConsole.javaSOURCE : ServerConsole.javaSOURCE : ServerConsole.javaSOURCE : ServerConsole.java

    import java.io.*;

    import java.net.*;

    public class ServerConsole {

    public static void main(String [] args) {

    ServerSocket server=null;

    Socket client;try {

    server = new ServerSocket(1234); //1234 is an unused port number

    } catch (IOException ie) {

    System.out.println("Cannot open socket.");

    System.exit(1);

    }

    while(true) {

    try {client = server.accept();

    OutputStream clientOut = client.getOutputStream();

    PrintWriter pw = new PrintWriter(clientOut, true);

    InputStream clientIn = client.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    51/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    String msg = br.readLine();

    System.out.println("Client : "+msg);

    msg = System.console().readLine("Server : ");

    pw.println(msg);

    } catch (IOException ie) {}

    }//End Of Main method}//End Of SeverConsole class.

    SOURCE :SOURCE :SOURCE :SOURCE : ClientClientClientClientConsole.javaConsole.javaConsole.javaConsole.java

    import java.io.*;

    import java.net.*;

    public class ClientConsole {

    public static void main(String args[]) {

    try {Socket client =new Socket("localhost", 1234);

    InputStream clientIn = client.getInputStream();

    OutputStream clientOut = client.getOutputStream();

    PrintWriter pw = new PrintWriter(clientOut,true);

    BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Client : ");

    pw.println(stdIn.readLine());

    System.out.print("Server : ");

    System.out.println(br.readLine());

    pw.close(); br.close(); client.close();

    } catch (ConnectException ce) {

    System.out.println("Cannot connect to the server.");

    } catch (IOException ie) {

    System.out.println("I/O Error.");

    }

    }//End Of Main method}//End Of ClientConsole class.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    52/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    OOOOutput:utput:utput:utput:

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    53/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    Collection API:Collection API:Collection API:Collection API: Collections Framework provides a well-designed set of interfaces and classes for

    storing and manipulating groups of data as a single unit, a collection.

    It provides a convenient API to many of the ADTs like maps, sets, lists, trees, arrays,hash tables, and other collections.

    All the classes and interfaces of collection framework are available in a java.utiljava.utiljava.utiljava.utilpackage.

    The java.utiljava.utiljava.utiljava.util package contains one of Javas most powerful subsystems: collections.

    Collections were added by the initial release of Java 2, and enhanced by Java 2, version

    1.4. A collectionis a group of objects.

    Collection Framework Hierarchy :Collection Framework Hierarchy :Collection Framework Hierarchy :Collection Framework Hierarchy :

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    54/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    java.util.java.util.java.util.java.util.Collection InterfaceCollection InterfaceCollection InterfaceCollection Interface

    The CollectionCollectionCollectionCollection interface is the foundation upon which the collections framework

    is built. It declares the core methods that all collections will have.

    TheTheTheThe ArrayList ClassArrayList ClassArrayList ClassArrayList Class::::

    The ArrayList class implements the List interface. ArrayList supports dynamic arrays

    that can grow as needed.

    TheTheTheThe VectorVectorVectorVector Class:Class:Class:Class:

    Vector implements a dynamic array. It is similar to ArrayList, but with two differences:

    Vector is synchronized, and it contains many legacy methods that are not part of the collectionsframework.

    The LinkedList ClassThe LinkedList ClassThe LinkedList ClassThe LinkedList Class

    The LinkedList class implements the List and Deque interfaces. It provides a linked-list

    data structure.

  • 7/30/2019 Object Oriented Technic Notes(Unit4)

    55/69

    Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai

    The HashSet ClassThe HashSet ClassThe HashSet ClassThe HashSet Class

    HashSet implements the Set interface. It creates a collection that uses a hash table for

    storage. As most readers likely know, a hash table stores information by using a mechanism

    called hashing. In hashing, the informational content of a key is used to determine a unique

    value, called its hash code. In HashSet collection, objects are stored in un-ordered way and it

    does not allow duplicated elements.

    The Tre