MCS-024(11-12) (1)

download MCS-024(11-12) (1)

of 66

Transcript of MCS-024(11-12) (1)

  • 8/2/2019 MCS-024(11-12) (1)

    1/66

    1

    Course Code : MCS-024

    Course Title : Object Oriented Technologies and Java Programming

    Assignment Number : MCA (2)/024/Assign/11

    Assignment Marks : 100

    Maximum Marks : 25%

    Last Date of Submission : 15th

    October, 2011 (for July, 2011 session)

    15th April, 2012 (for January, 2012 session)

    There are eight questions in this assignment which carried 80 marks. Rest 20 marks are for

    viva-voce. Answer all the questions. Also in your programs give appropriate comments to

    increase understandability. Please go through the guidelines regarding assignments given in the

    Program Guide for the format of presentation.

    Question 1: a) What is Object Oriented Paradigm? Explain advantages of Object

    Oriented Programming. (5 Marks)

    Solution : Object Oriented paradigm: The Object Oriented paradigm is centered on the

    concept of the object. Everything is focused on objects. In this language, program

    consists of two things: first, a set of objects and second the way they interact with

    each other. Computation in this paradigm is viewed as the simulation of real world

    entities. The popular programming languages in this paradigm are C++, Simula,

    Smalltalk and Java.

    Object Oriented programming: The world and its applications are not organized as

    functions and values separate from one another. The problem solvers do not think

    about the world in this manner. They always deal with their problems by

    concentrating on the objects, their characteristics and behavior.

    The world is Object Oriented, and Object Oriented programming expresses programs

    in the ways that model how people perceive the world. Figure 2 shows different real

    world objects around us which we often use for performing different functions. This

    shows that problem solving using the objects oriented approach is very close to our

    real life problem solving techniques.

    The basic difference in Object Oriented programming (OOP) is that the program is

    organized around the data being operated upon rather than the operations performed.

    The basic idea behind OOP is to combine both, data and its functions that operate on

    the data into a single unit called object.

  • 8/2/2019 MCS-024(11-12) (1)

    2/66

    2

    Object Oriented methods are favored because many experts agree that Object

    Oriented techniques are more disciplined than conventional structured techniques.

    (Martin and Odell 1992)

    The main components of Object Oriented technology are objects and classes, data

    abstraction and encapsulation, inheritance and polymorphism. It is very

    important for you to understand these concepts. Further, in this unit you can find the

    details of these concepts.

    Objects:The first thing that we should do in the Object Oriented approach is to start thinking

    in terms of Objects. The problem to be solved is divided into objects. Start analyzing

    the problem in terms of objects and the nature of communication between them.

    Program object should be chosen such that they match closely with real-world

    objects. Lets start creating objects using real-life things, for example, the dog. You

    can create an object representing a dog, It would have data like How hungry is it?

    How happy is it? Where is it? Now think, what are the different functions you can

    perform on a dog, like eat, bark, run and dig. Similarly, the following can be treatedas objects in different programming problems:

    Employees in a payroll system

    Customers and accounts in a banking system

    Salesman, products, customers in a sales tracking system

    Data structures like linked lists, stacks, etc.

    Hardware devices like magnetic tape drive, keyboard, printer etc.

    GUI elements like windows, menus, events, etc. in any window-based application.

    Each object contains data and the functions that operate on the data. Objects can

    interact without having to know details of each others data or functions. It is

    sufficient to know the type of message accepted and the type of response returned bythe object. For example, in the banking system, customer object may send a message

    named as check balance to the account object to get the response, i.e. bank balance.

    An Object Oriented system can be considered as network of cooperating objects

    which interact by sending messages to each other. Lets see in the Figure 4, how

    objects interact by sending messages to one another.

    Objects of the similar type can be grouped together to form a class. Can you tell to

    which class dog belongs? Yes, of course, it belongs to the animal class. Now, let us

    concentrate on the creation of objects. This can be easily answered if we look at the

    way of creating any variable in common programming languages. Almost all

    computer languages have built-in data types, for example integer, character, real,boolean, etc. One can declare as many variables of any built-in type as needed in any

  • 8/2/2019 MCS-024(11-12) (1)

    3/66

    3

    problem solution. In the similar way one can define many objects of the same class.

    You can take a class as a type created by a programmer. A class serves as a plan or

    template. The programmer has to specify the entire set of data and functions for

    various operations on the data for an object as a user-defined type in the form of a

    class. In other words, the programmer defines the object format and behavior by

    defining a class. The compiler of that language does not know about this user-

    defined data type. The programmer has to define the data and functionality associated

    with it by designing a class.

    Finally, defining the class doesnt create an object just as the existence of a built-in

    type integer doesnt create any variable. Once the class has been defined, you can

    create any number of objects belonging to that class. A class is thus a collection of

    objects of similar type. For example, in a collection of potatoes each individual potato

    is an object and belongs to the class potato. Similarly, each individual car running on

    the road is an object, Collectively these cars are known as cars.

    Data abstraction and encapsulation

    The wrapping up of data and functions into a single unit is known as encapsulation.This is one of the strong features of the object oriented approach. The data is not

    directly accessible to the outside world and only the functions, which are wrapped in

    the class, can access it. Functions are accessible to the outside world. These functions

    provide the interface to access data. If one wants to modify the data of an object, s/he

    should know exactly what functions are available to interact with it. This insulation of

    the data from direct access by the program is known as data hiding.

    Abstraction refers to the act of representing essential features without including the

    background details to distinguish objects/ functions from other objects/functions. In

    case of structured programming, functional abstraction was provided by telling,

    which task is performed by function andhiding how that task is performed. A step

    further, in the Object Oriented approach, classes use the concept ofdata abstraction.

    With data abstraction, data structures can be used without having to be concerned

    about the exact details of implementation. As in case of built-in data types like

    integer, floating point, etc. The programmer only knows about the various operations

    which can be performed on these data types, but how these operations are carried out

    by the hardware or software is hidden from the programmer. Similarly in Object

    Oriented approach, classes act asabstract data types. Classes are defined as a set of

    attributes and functions to operate on these attributes. They encapsulate all the

    essential properties of the objects that are to be created.

    Inheritance

    Inheritance is the process by which objects of one class acquire the properties ofobjects of another class in the hierarchy. For example, the scooter is a type of the

    class two-wheelers, which is again a type of (or kind of) the class motor vehicles. As

    shown in the Figure 5 the principle behind it is that the derived class shares common

    characteristics with the class from which it is derived.

    New classes can be built from the existing classes. It means that we can add

    additional features to an existing class without modifying it. The new class is referred

    as derived class or sub class and the original class is known as base class or super

    class. Therefore, the concept of inheritance provides the idea of reusability. This

    inheritance mechanism allows the programmer to reuse a class that is made almost,

    but not exactly, similar to the required one by adding a few more features to it. As

    shown in Figure 5, three classes have been derived from one base class. Feature A

    and Feature B of the base class are inherited in all the three derived classes. Also,

  • 8/2/2019 MCS-024(11-12) (1)

    4/66

    4

    each derived class has added its own features according to the requirement.

    Therefore, new classes use the concept of reusability and extend their functionality.

    PolymorphismPolymorphism means the ability to take more than one form of the same

    property. For example, consider an addition operation. It shows a different behaviour

    in different types of data. For two numbers, it will generate a sum. The numbers may

    integers or float. Thus the addition for integers is different from the addition to floats.

    BENEFITS OF OOPSOOP offers several benefits to both the program developer and the user. The new

    technology provides greater programmer productivity, better quality of software and

    lesser maintenance cost. The major benefits are:

    Ease in division of job: Since it is possible to map objects of the problemdomain to those objects in the program, the work can be easily partitioned based

    on objects.

    Reduce complexity: Software complexity can be easily managed. Provide extensibility: Object Oriented systems can be easily upgraded from

    small to large system.

    Eliminate redundancy: Through inheritance we can eliminate redundant codeand extend the use of existing classes.

    Saves development time and increases productivity: Instead of writing code

    from scratch, solutions can be built by using standard working modules. Allows building secure programs: Data hiding principle helps programmer tobuild secure programs that cannot be accessed by code in other parts of the

    program.

    Allows designing simpler interfaces: Message passing techniques betweenobjects allows making simpler interface descriptions with external systems.

  • 8/2/2019 MCS-024(11-12) (1)

    5/66

    5

    b) What is inheritance? What are different types of inheritance?

    Explain the advantages of inheritance. (5 Marks)

    Solution :

    Inheritance is probably the most powerful feature of object-oriented programming.

    Inheritance is an ability to derive new classes from existing classes. A derived class is

    known as subclass which inherits the instance variables and methods of the super

    class or base class, and can add some new instance variables and methods. [Katrin

    Becker 2002].

    Generally speaking, objects are defined in terms of classes. You know a lot about an

    object by knowing its class. If I tell you that the object is a bicycle, you can easily tell

    that it has two wheels, a handle bar, and pedals. Object-oriented systems take this a

    step further and allow classes to be defined in terms of other classes. For example,

    mountain bikes, racing bikes, and tandems are all kinds of bicycles as shown in

    Figure 10. In OOP, mountain bikes, racing bikes, and tandems are all subclass (i.e.

    derived class or child class) of the bicycle class. Similarly, the bicycle class is the

    superclass (i.e., base class or parent class) of mountain bikes, racing bikes, andtandems. This relationship you can see shown in the Figure.

    Each subclass inherits state (in the form of variable declarations) from the superclass.

    Mountain bikes, racing bikes, and tandems share some states: cadence, speed, etc.

    Also, each subclass inherits methods from the superclass. Mountain bikes, racing

    bikes, and tandems share some behaviors: for example braking and changing pedaling

    speed. However, subclasses are not limited to the state and behaviors provided to

    them by their superclass. Subclasses can add variables and methods to the ones they

    inherit from the superclass. Tandem bicycles have two seats and two sets of handlebars; some mountain bikes have an extra set of gears with a lower gear ratio.

    Subclasses can also override inherited methods and provide specialized

    mplementations for those methods. For example, if you had a mountain bike with an

    extra set of gears, you would override the change gears method so that the rider could

    use those new gears.

    We are not limited to just one layer of inheritance. The inheritance tree, or class

    hierarchy can be as deep as needed. Methods and variables are inherited down

    through the levels. In general, the farther down in the hierarchy a class appears, the

    more specialized its behavior. Inheritance may have different forms as shown in

    Figure 11:

  • 8/2/2019 MCS-024(11-12) (1)

    6/66

    6

    Single Inheritance (Fig. 11a): In this form, a subclass can have only one superclass.

    Multiple Inheritance (Fig. 11b): This form of inheritance can have severalsuperclasses.

    Multilevel Inheritance (Fig. 11c): This form has subclasses derived fromanother subclass. The example can be grandfather, father and child.

    Hierarchical Inheritance (Fig. 11d): This form has one superclass and manysubclasses. More than one class inherits the traits of one class. For example: bank

    accounts.

    These forms of inheritance could be used for writing extensible programs. The

    direction of arrow indicates the direction of inheritance. For example, in case of

    single inheritance, traits of class A are inherited by class B.

    Benefits of InheritanceSubclasses provide specialized behaviors from the basis of common elements

    provided by the superclass. Through the use of inheritance, programmers can reuse

    the code in the superclass many times. Once a superclass is written and debugged, it

    need not be touched again but at the same time can be adapted to work in different

    situations. Reusing existing code saves time and money and increases a programs

    reliability.

    Programmers can implement superclasses called abstract classes that define genericbehaviors. A class for which objects doesnt exist. Example: Further class has no

    object, but its derived classes-chair, table-that have objects. The abstract superclass

    defines and may partially implement the behavior, but much of the abstract class is

    undefined and unimplemented. These undefined and unimplemented behaviors fill in

    the details with specialized subclasses. Hence, Inheritance can also help in the

    original conceptualization of a programming problem, and in the overall design of the

    program.

    The code reusability helps in case of distributing class libraries. A programmer

    canuse a class created by another person or company, and, without modifying it,

    derive other classes from it that are suited to particular programming situations.

  • 8/2/2019 MCS-024(11-12) (1)

    7/66

    7

    Question 2: a) What is platform independence? Explain why java is platform independent.

    (2 Marks)

    Solution :

    Platform IndependentJava is Platform independent. The meaning of platform here may be

    confusing for you but actually this word is poorly defined. In the computer

    industry it typically means some combination of hardware and system

    software but here you can understand it as your operating system.

    Java is compiled to an intermediate form called Java byte-code or simply

    byte code. A Java program never really executes immediately after

    compilation on the host machine. Rather, this special program called the Java

    interpreter or Java Virtual Machine reads the byte code, translates it into the

    corresponding host machine instructions and then executes the machine

    instruction. A Java program can run on any computer system for which a

    JVM (Java Virtual Machine) and some library routines have been installed.

    The second important part which makes Java portable is the elimination ofhardware architecture dependent constructs. For example, Integers are always

    four bytes long and floating-point variables follow the IEEE 754.You dont

    need to worry that the interpretation of your integer is going to change if you

    move from one hardware to another hardware like Pentium to a PowerPC.

    We can develop the Java program on any computer system and the execution

    of that program is possible on any other computer system loaded with JVM.

    For example, we can write and compile the Java program on Windows 98

    and execute the compiled program on JVM of the Macintosh operating

    system. The same concept is explained in Figure 1 given below.

    Java Virtual Machine ConceptsWhen a Java program is compiled it is converted to byte code which is then executed

    by the Java interpreter by translating the byte code into machine instructions. Java

    interpreter is part of Java runtime environment. Byte code is an intermediate code

    independent of any machine and any operating system. Program in Java run time

    environment, which is used to interpret byte code, is called Java Virtual Machine

    (JVM). The Java compiler reads Java language source files, translates the source into

    Java byte codes, and places the byte codes into class files. Any machine for which

    Java interpreter is available can execute this byte code. Thats why Java is called

    Machine independent and Architecture neutral. Figure 2 shows that Java compiler

    is accepting a Java program and producing its byte code. This byte code can be

    executed on any operating system (Window-98, Macintosh, Linux etc.) running on

    any machine with suitable Java interpreter of that machine.

  • 8/2/2019 MCS-024(11-12) (1)

    8/66

    8

    The JVM plays the main role to making Java portable. It provides a layer of

    abstraction between the compiled Java program and the hardware platform and

    operating system. The JVM is central to Javas portability because compiled Java

    programs run on the JVM, independent of whatever hardware is used.

  • 8/2/2019 MCS-024(11-12) (1)

    9/66

    9

    b) List and explain different logical operators available in java. (2 Marks)

    Solution:

    Arithmetic operators:You must be friendly with arithmetic expressions in mathematics like A B. In this expression A

    and B are operands and the subtraction sign is the operator. The same terminology is also used

    here in the programming language. The following table lists the basic arithmetic operators provided

    by the Java programming language along with the description and uses. Here in the Table A and B are

    the operands. Operators are divided into two categories Binary and Unary. Addition, subtraction,

    multiplication etc. are binary operators and applied only on two operands. Increment and decrement

    are unary operators and applied on single operand.

  • 8/2/2019 MCS-024(11-12) (1)

    10/66

    10

    To do exponentiation we shall import Java.lang class where math is subclass. Inside math class we

    have one function pow similar to C++ which can be used for exponentiation. All the above operators

    can be used only on numeric values except for +, which is also used to concatenate strings.

    Assignment Operators:The basic assignment operator = is used to assign value to the variables. For example A = B; in

    which we assign value of B to A. Similarly, let us see how to assign values to different data types. int

    Integer = 100; float Float = 10.5; char Chararcter = 'S'; boolean aboolean = true; With basic

    assignment operator, the Java programming language defines short cut assignment operators that

    allow you to perform arithmetic, shift, or bitwise operation with one operator.

    Now let us see, if you want to add a number to a variable and assign the result back into the same

    variable, so you will write something like i = i + 2; but using shortcut operator += You can shorten

    this statement, like i += 2. But remember, i = i + 2; and i += 2; both statements are the same for the

    compiler. As given in Table10, Java programming language provides different short cut assignment

    operators:

    Multiple AssignmentsMultiple assignments are possible in the following format:

    Identifier= Identifier B= Identifier C=.=expression

    In this case all the identifiers are assigned the value of expression. Lets see one example:

    A=B=786+x+y+z; this is the same if you write: A=786+x+y+z; and B=786+x+y+z;

    Relational OperatorsRelational operators also called, comparison operators, are used to determine the relationship between

    two values in an expression. As given in Table 11, the return value depends on the operation.

  • 8/2/2019 MCS-024(11-12) (1)

    11/66

    11

    Boolean OperatorsBoolean operators allow you to combine the results of multiple expressions to return a single value

    that evaluates to either true or false. Table 12 describes the use of each boolean operator.

  • 8/2/2019 MCS-024(11-12) (1)

    12/66

    12

    Bitwise operatorsAs you know in computers data is represented in binary (1s and 0s) form. The binary representation

    of the number 43 is 0101011. The first bit from the right to left in the binary representation is the least

    significant bit, i.e. here value is 1. Each Bitwise operator allows you to manipulate integer variables at

    bit level. Table 13 given below describes the use of bitwise operator with help of suitable example for

    each. Similarly, the use of class and object operators is given in Table 14.

  • 8/2/2019 MCS-024(11-12) (1)

    13/66

    13

  • 8/2/2019 MCS-024(11-12) (1)

    14/66

    14

    Other OperatorsThere are some other operators that cannot fit in the above categories but are very important for

    programmers. These operators are explained in Table 15 given below.

  • 8/2/2019 MCS-024(11-12) (1)

    15/66

    15

  • 8/2/2019 MCS-024(11-12) (1)

    16/66

    16

    c) Explain the need of Unicode. (2 Marks)

    Solution:

    Unicode is a 16-bit code having a large range in comparison to previous ASCII code, which is only 7

    bits or 8 bits in size. Unicode can represent all the characters of all human languages. Since Java is

    developed for designing Internet applications, and worldwide people can write programs in Java,

    transformation of one language to another is simple and efficient. Use of Unicode also supports

    platform independence in Java.

    d) What is a constructor? Explain advantages of parameterized constructors with a program in Java.

    (4

    Marks)

    Solution: Constructor : When we create an object of a class, a special kind of method called a

    constructor is always invoked. If we dont define any constructors for our

    class, the compiler will supply a default constructor in the class, which does nothing.

    The default constructor is also described as the no-arg constructor because it requiresno arguments to be specified when it is called. The primary purpose of a constructor is to

    provide us with the means of initializing the instance variables uniquely for the

    object that is being created.

    If we are creating a Person object with the name John Doe, then we want to be able to initialize the

    member holding the persons name to John Doe. This is precisely what a constructor can do. Any

    initialization blocks that we have defined in a class are always executed before a constructor. A

    constructor has two special characteristics that differentiate it from other class methods:

    A constructor never returns a value, and we must not specify a return typenot even of type void.

    A constructor always has the same name as the class.

    To see a practical example we could add a constructor to the Sphere class definition:

    class Sphere {

    static final double PI = 3.14; // Class variable that has a fixed value

    static int count = 0; // Class variable to count objects

    // Instance variables

    double radius; // Radius of a sphere

    double xCenter; // 3D coordinates

    double yCenter; // of the center

    double zCenter; // of a sphere

    //--------------------------------- Class constructor Def.-----------------------------------------------------------

    Sphere(double theRadius, double x, double y, double z) {radius = theRadius; // Set the radius

    // Set the coordinates of the center

    xCenter = x;

    yCenter = y;

    zCenter = z;

    ++count; // Update object count

    }

    //-----------------------------------Constructor Def Ends------------------------------------

    // Static method to report the number of objects created

    static int getCount() {

    return count; // Return current object count

    }// Instance method to calculate volume

  • 8/2/2019 MCS-024(11-12) (1)

    17/66

    17

    double volume() {

    return 4.0/3.0*PI*radius*radius*radius;

    }

    }

    The definition of the constructor is shaded above. We are accumulating quite a lot of code to define

    the Sphere class, but as its just an assembly of the pieces we have been adding, we should find it all

    quite straightforward. As we can see, the constructor has the same name as the class and has no return

    type specified. A constructor can have any number of parameters, including none. The default

    constructor has no parameters, as is indicated by its alternative descriptionthe no-arg constructor. In

    this case the Sphere class constructor has four parameters, and each of the instance variables is

    initialized with the value of the appropriate parameter. Heres a situation where we might have used

    the name radius for the parameter, in which case we would need to use the keyword this to refer to the

    instance variable of the same name. The last action of the constructor is to increment the class

    variable count by 1, so that count accumulates the total number of objects created.

    The Default ConstructorAs I said, if we dont define any constructors for a class, the compiler will supply a default

    constructor that has no parameters and does nothing. Before we defined a constructor for the Sphereclass, the compiler would have supplied one, defined like this:

    Sphere()

    {

    }

    It has no parameters and no statements in its body so it does nothingexcept enable you to create an

    object of type Sphere, of course. The object created by the default constructor will have fields with

    their default values set. If you have defined any non-static initialization blocks within a class, they

    will be executed each time any constructor executes, immediately before the execution of the code in

    the body of the constructor. Whenever you create an object, a constructor will be called. When you

    have not defined any constructors for a class, the default constructor will be called each time youcreate an object of that class type.

    Note that if you define a constructor of any kind for a class, the compiler will not supply a default

    constructor. If you still need a default constructorand you will find many occasions when you do -

    you must define it explicitly in addition to the other constructors in the class.

    Parameterized Constructor:It is possible to pass arguments to constructors. Typically, these arguments help initialize an object

    when it is created. To create a parameterized constructor, simply add parameters to it the way you

    would to any other function. When you define the constructors body, use the parameters to initialize

    the object. For example, here is a simple class that includes a parameterized constructor:

    class Rectangle

    {

    int length;

    int width;

    Rectangle(int x,int y) //Parameterized Constructor

    {

    length=x;

    width=y;

    }

    Int rectArea()

    {

    return(length*width);

    }

  • 8/2/2019 MCS-024(11-12) (1)

    18/66

    18

    }

    Class RectangleArea

    {

    public static void main(string args[])

    {

    Rectangle rect1=new Rectangle(15,10); //Calling Parameterized Constructor

    Int area1=rect1.rectArea();

    System.out.println(Area1 = + area1);

    }

    }

    Output:Area1 = 150

    Parameterized constructors are very useful because they allow us to avoid having to make anadditional function call simply to initialize one or more variables in an object. Each function call we

    avoid makes our program more efficient. Also, notice that the short rectArea() function is defined in

    line, within the Rectangle class.

    Question 3: a) What is an exception. Explain how an exception subclass is created in Java.

    (5 Marks)

    Solution:

    Java uses exceptions as a way of signaling serious problems when you execute a program. The

    standard classes use them extensively. Since they arise in your Java programs when things go wrong,and if something can go wrong in your code, sooner or later it will, they are a very basic consideration

    when you are designing and writing your programs.

    An exception usually signals an error and is so called because errors in your Java programs are bound

    to be the exception rather than the ruleby definition! An exception doesnt always indicate an error

    thoughit can also signal some particularly unusual event in your program that deserves special

    attention.

    If you try to deal with the myriad and often highly unusual error conditions that might arise in the

    midst of the code that deals with the normal operation of the program, your program structure will

    soon become very complicated and difficult to understand. One major benefit of having an error

    signaled by an exception is that it separates the code that deals with errors from the code that isexecuted when things are moving along smoothly. Another positive aspect of exceptions is that they

    provide a way of enforcing a response to particular errors. With many kinds of exceptions, you must

    include code in your program to deal with them; otherwise, your code will not compile.

    One important idea to grasp is that not all errors in your programs need to be signaled by exceptions.

    Exceptions should be reserved for the unusual or catastrophic situations that can arise. A user entering

    incorrect input to your program for instance is a normal event and should be handled without recourse

    to exceptions. The reason for this is that dealing with exceptions involves quite a lot of processing

    overhead, so if your program is handling exceptions a lot of the time it will be a lot slower than it

    needs to be.

    An exception in Java is an object thats created when an abnormal situation arises in your program.

    This exception object has fields that store information about the nature of the problem. The exception

  • 8/2/2019 MCS-024(11-12) (1)

    19/66

    19

    is said to be thrownthat is, the object identifying the exceptional circumstance is tossed as an

    argument to a specific piece of program code that has been written specifically to deal with that kind

    of problem. The code receiving the exception object as a parameter is said to catch it.

    The situations that cause exceptions are quite diverse, but they fall into four broad categories:

    Types of ExceptionsAn exception is always an object of some subclass of the standard class Throwable. This is true for

    exceptions that you define and throw yourself, as well as the standard exceptions that arise due to

    errors in your code. Its also true for exceptions that are thrown by methods in one or another of the

    standard packages.

    Two direct subclasses of the class Throwablethe class Error and the class Exceptioncover all the

    standard exceptions. Both these classes themselves have subclasses that identify specific exception

    conditions. Figure 7-1 shows the hierarchy to which these classes belong.

    Error ExceptionsThe exceptions that are defined by the Error class and its subclasses are characterized by the fact that

    they

    all represent conditions that you arent expected to do anything about, so you arent expected to catch

    them. Error has three direct subclassesThreadDeath, LinkageError, and VirtualMachineError:

    The first of these sounds the most serious, but in fact it isnt. AThreadDeath exception is thrown

    whenever an executing thread is deliberately stopped, and for the thread to be destroyed properly,

    you should not catch this exception. In some circumstances you might want to catch it

    for clean-up operations, for examplein which case you must be sure to rethrow the exception

    to allow the thread to die peacefully. When a ThreadDeath exception is thrown and not caught,its the thread that ends, not the program. I will deal with threads in detail in Chapter 16.

  • 8/2/2019 MCS-024(11-12) (1)

    20/66

    20

    The LinkageError exception class has subclasses that record serious errors with the classes

    in your program. Incompatibilities between classes or attempting to create an object of a nonexistent

    class type are the sorts of things that cause these exceptions to be thrown.

    The VirtualMachineError class has four subclasses that specify exceptions that will be

    thrown when a catastrophic failure of the Java Virtual Machine occurs. You arent prohibited

    from trying to deal with these exceptions, but in general, theres little point in attempting tocatch them.

    The exceptions that correspond to objects of classes derived from LinkageError and

    VirtualMachineError are all the result of catastrophic events or conditions. You can do little or

    nothing to recover from them during the execution of the program. In these sorts of situations, all you

    can usually do is read the error message that is generated by the exception being thrown and then,

    particularly

    in the case of a LinkageError exception, try to figure out what might be wrong with your code

    to cause the problem.

    RuntimeException ExceptionsFor almost all the exceptions that are represented by subclasses of the Exception class, you must

    include code in your programs to deal with them if your code may cause them to be thrown. If a

    methodin your program has the potential to generate an exception of a type that has Exception as a

    superclass,

    you must either handle the exception within the method or register that your method may throw such

    an exception. If you dont, your program will not compile. Youll see in a moment how to handle

    exceptions

    and how to specify that a method can throw an exception.

    One group of subclasses of Exception that is exempted from this is comprised of those derived from

    RuntimeException. The reason that RuntimeException exceptions are treated differently, and that the

    compiler allows you to ignore them, is that they generally arise because of serious errors in your code.

    In

    most cases you can do little to recover the situation. However, in some contexts for some of these

    exceptions,this is not always the case, and you may well want to include code to recognize them. Quite a lot

    of subclasses of RuntimeException are used to signal problems in various packages in the Java class

    library. Lets look at the exception classes that have RuntimeException as a base that are defined in

    the

    java.lang package.

    The subclasses of RuntimeException defined in the standard package java.lang are:

  • 8/2/2019 MCS-024(11-12) (1)

    21/66

    21

    In the normal course of events you shouldnt meet up with the last three of these. The

    ArithmeticException turns up quite easily in your programs, as does the

    IndexOutOfBoundsException. A mistake in a for loop limit will produce the latter. In fact there are

    two subclasses of IndexOutOfBoundsException that specify the type of exception thrown more

    preciselyArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.

    A NullPointerException can also turn up relatively easily, as can ArrayStoreException,

    ClassCastException, and IllegalArgumentException, surprisingly enough. The last three here arise

    when you are using a base class variable to call methods for derived class objects. Explicit attempts to

    perform an incorrect cast, or store a reference of an incorrect type, or pass an argument of the wrong

    type to a method will all be picked up by the compiler. These exceptions can, therefore, arise only

    from using a variable of a base type to hold references to a derived class object.

    The IllegalArgumentException class is a base class for two further exception classes,

    IllegalThreadStateException and NumberFormatException. The former arises when you attempt an

    operation that is illegal in the current thread state. The NumberFormatException exception is thrown

    by the valueOf() or decode() methods in the classes representing integersthat is, the classes Byte,

    Short, Integer, and Long. The parseXXX() methods in these classes can also throw this exception. The

    exception is thrown if the String object you pass as an argument to the conversion method is not a

    valid representation of an integerif it contains invalid characters, for example. In this case a special

  • 8/2/2019 MCS-024(11-12) (1)

    22/66

    22

    return value cannot be used, so throwing an exception is a very convenient way to signal that the

    argument

    is invalid.

    Defining an Exception ClassYour exception classes must always have Throwable as a superclass; otherwise, they will not define

    an exception. Although you can derive them from any of the standard exception classes, your best

    policy is to derive them from the Exception class. This will allow the compiler to keep track of where

    such exceptions are thrown in your program and check that they are either caught or declared as

    thrown in a method. If you use RuntimeException or one of its subclasses, the compiler checking for

    catch blocks of your exception class will be suppressed.

    An example of how to define an exception class:

    public class DreadfulProblemException extends Exception

    {

    // Constructorspublic DreadfulProblemException(){ } // Default constructor

    public DreadfulProblemException(String s)

    {

    super(s); // Call the base class constructor

    }

    }

    This is the minimum you should supply in your exception class definition. By convention, your

    exception class should include a default constructor and a constructor that accepts a String object as

    an argument. The message stored in the superclass Exception (in fact, in Throwable, which is the

    superclass of Exception) will automatically be initialized with the name of your class, whichever

    constructor for your class objects is used. The String passed to the second constructor will beappended to the name of the class to form the message stored in the exception object.

    Of course, you can add other constructors. In general, youll want to do so, particularly when youre

    rethrowing your own exception after a standard exception has been thrown. In addition, youll

    typically want to add instance variables to the class that store additional information about the

    problem, plus methods that will enable the code in a catch block to get at the data. Since your

    exception class is ultimately derived from Throwable, the stack trace information will be

    automatically available for your exceptions.

    Throwing Your Own ExceptionAs you saw earlier, you throw an exception with a statement that consists of the throw keyword,

    followed by an exception object. This means you can throw your own exception with the following

    statements:

    DreadfulProblemException e = new DreadfulProblemException();

    throw e;

    The method will cease execution at this pointunless the code snippet above is in a try or a catch

    block with an associated finally clause, the contents of which will be executed before the method

    ends. The exception will be thrown in the calling program at the point where this method was called.

    The message in the exception object will consist only of the qualified name of the exception class. If

    you wanted to add a specific message to the exception, you could define it as:

    DreadfulProblemException e = new DreadfulProblemException(Uh-Oh, trouble.);

  • 8/2/2019 MCS-024(11-12) (1)

    23/66

    23

    Youre using a different constructor here. In this case the message stored in the superclass will be a

    string that consists of the class name with the string passed to the constructor appended to it. The

    getMessage() method inherited from Throwable will, therefore, return a String object containing the

    following string:

    DreadfulProblemException: Uh-Oh, trouble.

    You can also create an exception object and throw it in a single statement. For example:

    throw new DreadfulProblemException(Terrible difficulties);

    In all the examples, the stack trace record inherited from the superclass Throwable will be set up

    automatically.

    Defining Your Own Exception Class

    We can define the class that will correspond to an ArithmeticException in the divide() method as:

    public class ZeroDivideException extends Exception{

    private int index = -1; // Index of array element causing error

    // Default Constructor

    public ZeroDivideException(){ }

    // Standard constructor

    public ZeroDivideException(String s)

    {

    super(s); // Call the base constructor

    }

    public ZeroDivideException(int index)

    {

    super(/ by zero); // Call the base constructor

    this.index = index; // Set the index value

    }

    // Get the array index value for the error

    public int getIndex()

    {

    return index; // Return the index value

    }

    }

  • 8/2/2019 MCS-024(11-12) (1)

    24/66

    24

    b) What is abstract class? Write a program in Java to explain abstract class and multilevel inheritance.

    (5 Marks)

    Solution:

    An abstract class is a class in which one or more methods are declared, but not defined. The bodies of

    these methods are omitted, because, as in the case of the method sound() in the Animal class,

    implementing the methods does not make sense. Since they have no definition and cannot be

    executed, they are called abstract methods. The declaration for an abstract method ends with a

    semicolon and you specify the method with the keyword abstract to identify it as such. To declare that

    a class is abstract you just use the keyword abstract in front of the class keyword in the first line of the

    class definition.

    public abstract class Animal {

    public abstract void sound(); // Abstract method

    public Animal(String aType) {

    type = new String(aType);

    }public String toString() {

    return This is a + type;

    }

    private String type;

    }

    class Spaniel extends Dog {

    public Spaniel(String aName) {

    super(aName, Spaniel);

    }

    }

    The previous program will work just as well with these changes. It doesnt matter whether you prefixthe class name with public abstract or abstract public, they are equivalent, but you should be

    consistent in your usage. The sequence public abstract is typically preferred. The same goes for the

    declaration of an abstract method, but both public and abstract must precede the return type

    specification, which is void in this case.

    An abstract method cannot be private since a private method cannot be inherited and therefore cannot

    be redefined in a subclass. You cannot instantiate an object of an abstract class, but you can declare a

    variable of an abstract class type. With the new abstract version of the class Animal, you can still

    write:

    Animal thePet = null; // Declare a variable of type Animal

    You can then use this variable to store objects of the subclasses, Dog, Spaniel, Duck, and Cat. When

    you derive a class from an abstract base class, you dont have to define all the abstract methods in the

    subclass. In this case the subclass will also be abstract and you wont be able to instantiate any objects

    of the subclass either. If a class is abstract, you must use the abstract keyword when you define

    A program in Java to explain abstract class and multilevel inheritance

    abstract class Player // class is abstract

    {

    private String name;

    public Player(String nm)

    {

    name=nm;

  • 8/2/2019 MCS-024(11-12) (1)

    25/66

    25

    }

    public String getName() // regular method

    {

    return (name);

    }

    public abstract void Play();

    // abstract method: no implementation

    }

    class Cricket_Player extends Player

    {

    Cricket_Player( String var)

    {

    }

    public void Play()

    {

    System.out.println("Play Cricket:"+getName());

    }

    }class Hockey_Player extends Player

    {

    Hockey_Player( String var)

    {

    }

    public void Play()

    {

    System.out.println("Play Hockey:"+getName());

    }

    }

    class Football_Player extends Player

    {Football_Player( String var)

    {

    }

    public void Play()

    {

    System.out.println("Play Football:"+getName());

    }

    }

    public class PolyDemo

    {

    public static void main(String[] args)

    {Player ref; // set up var for an Playerl

    Cricket_Player aCplayer = new Cricket_Player("Sachin"); // makes specific objects

    Hockey_Player aHplayer = new Hockey_Player("Dhanaraj");

    Football_Player aFplayer = new Football_Player("Bhutia");

    // now reference each as an Animal

    ref = aCplayer;

    ref.Play();

    ref = aHplayer;

    ref.Play();

    ref = aFplayer;

    ref.Play();

    }

    }

  • 8/2/2019 MCS-024(11-12) (1)

    26/66

    26

    Output:Play Cricket:Sachin

    Play Hockey:Dhanaraj

    Play Football:Bhutia

    Question 4: a) What is polymorphism? Is Interfaces in Java, a kind of polymorphism?

    Justify your answer with the help of a Java program. (5 Marks)

    Solution:

    Polymorphismis the capability of a methodto do different things based on the object through which it

    is invoked or object it is acting upon. For example methodfind _area will work definitely for Circle

    object and Triangle object In Java, the type of actual object always determines method calls; object

    reference type doesnt play any role in it. You have already used two types of polymorphism

    (overloading and overriding) in the previous unit and in the current unit of this block. Now we will

    look at the third: dynamic method binding. Java uses Dynamic Method Dispatch mechanism to decide

    at run time which overridden function will be invoked. Dynamic Method Dispatch mechanism isimportant because it is used to implement runtime polymorphism in Java. Java uses the principle: a

    super class object can refer to a subclass object to resolve calls to overridden methods at run time.

    If a superclass has method that is overridden by its subclasses, then the different versions of the

    overridden methods are invoked or executed with the help of a superclass reference variable. Assume

    that three subclasses (Cricket_Player Hockey_Player and Football_Player) that derive from Player

    abstract class are defined with each subclass having its own Play() method.

    abstract class Player // class is abstract

    {

    private String name;

    public Player(String nm){

    name=nm;

    }

    public String getName() // regular method

    {

    return (name);

    }

    public abstract void Play();

    // abstract method: no implementation

    }

    class Cricket_Player extends Player

    {

    Cricket_Player( String var)

    {

    }

    public void Play()

    {

    System.out.println("Play Cricket:"+getName());

    }

    }

    class Hockey_Player extends Player

    {

    Hockey_Player( String var){

  • 8/2/2019 MCS-024(11-12) (1)

    27/66

    27

    }

    public void Play()

    {

    System.out.println("Play Hockey:"+getName());

    }

    }

    class Football_Player extends Player

    {

    Football_Player( String var)

    {

    }

    public void Play()

    {

    System.out.println("Play Football:"+getName());

    }

    }

    public class PolyDemo

    {public static void main(String[] args)

    {

    Player ref; // set up var for an Playerl

    Cricket_Player aCplayer = new Cricket_Player("Sachin"); // makes specific objects

    Hockey_Player aHplayer = new Hockey_Player("Dhanaraj");

    Football_Player aFplayer = new Football_Player("Bhutia");

    // now reference each as an Animal

    ref = aCplayer;

    ref.Play();

    ref = aHplayer;

    ref.Play();

    ref = aFplayer;ref.Play();

    }

    }

    Output:Play Cricket:Sachin

    Play Hockey:Dhanaraj

    Play Football:Bhutia

    Notice that although each method is invoked through ref, which is a reference to player class (but no

    player objects exist), the program is able to resolve the correct

    Interfaces in Java look similar to classes but they dont have instance variables and provides methods

    that too without implementation. It means that every method in the interface is strictly a declaration.

    All methods and fields of an interface must be public.

    Interfaces are used to provide methods to be implemented by class(es). A class implements an

    interface using implements clause. If a class is implementing an interface it has to define all the

    methods given in that interface. More than one interface can be implemented in a single class.

    Basically an interface is used to define a protocol of behavior that can be implemented by any class

    anywhere in the class hierarchy. As Java does not support multiple inheritance, interfaces are seen as

    the alternative of multiple inheritance, because of the feature that multiple interfaces can be

    implemented by a class. Interfaces are useful because they:

  • 8/2/2019 MCS-024(11-12) (1)

    28/66

    28

    Provide similarities among unrelated classes without artificially forcing a classrelationship.

    Declare methods that one or more classes are expected to implement. Allow objects from many different classes which can have the same type. This allows us

    to write methods that can work on objects from many different classes, which can even be

    in different inheritance hierarchies.

    Interfaces and Polymorphism

    You cant create objects of an interface type, but you can create a variable of an interface type. For

    example:

    Conversions converter = null; // Variable of the Conversions interface type

    If you cant create objects of type Conversions, what good is it? Well, you use it to store a reference

    to an object of any class type that implements Conversions. This means that you can use this variable

    to call the methods declared in the Conversions interface polymorphically. The Conversions interface

    is not a good example to show how this works. Lets consider a real-world parallel that I can use to

    better demonstrate this idea, that of home audio/visual equipment and a remote control. Im grateful toJohn Ganter who suggested this idea to me after reading a previous edition of this book.

    You almost certainly have a TV, a hi-fi, a VCR, and maybe a DVD player around your home, and

    each of them will have its own remote control. All the remote controls will probably have some

    common subset of buttonspower on/off, volume up, volume down, mute, and so on. Once you have

    more than four or so remotes cluttering the place up, you might consider one of those fancy universal

    remote control devices to replace themsort of a single definition of a remote control, to suit all

    equipment.

    A universal remote has a lot of similarities to an interface. By itself a universal remote does nothing.

    It defines a set of buttons for standard operations, but the operation of each button must be

    programmed specifically to suit each kind of device that you want to control. You can represent theTV, VCR, DVD, and so on by classes, each of which will make use of the same remote control

    interfacethe set of buttons if you likebut each in a different way. Even though it uses the same

    button on the remote, Power On for the TV, for example, is quite different from Power On for the

    VCR. Lets see how that might look in a concrete example.

    public interface RemoteControl {

    boolean powerOnOff(); // Returns new state, on = true

    int volumeUp(int increment); // Returns new volume level

    int volumeDown(int decrement); // Returns new volume level

    void mute(); // Mutes sound output

    int setChannel(int channel); // Set the channel number and return it

    int channelUp(); // Returns new channel numberint channelDown(); // Returns new channel number

    }

    The methods declared here in the RemoteControl interface should be self-explanatory. I have included

    just a few of the many possible remote operations here to conserve space in the book. You could add

    more if you want. You could have separate power on and power off methods, for example, tone

    controls, and so on. There is no definition for any of these methods here. Methods declared in an

    interface are always abstractby definition. Nor is there an access attribute for any of them. Methods

    declared in an interface are always public by default. Now any class that requires the use of the

    functionality provided by a RemoteControl just has to declare that it implements the interface and

    include the definitions for each of the methods in the interface. For example, heres the TV:

    import static java.lang.Math.max;

  • 8/2/2019 MCS-024(11-12) (1)

    29/66

    29

    import static java.lang.Math.min;

    public class TV implements RemoteControl {

    public TV(String make, int screensize) {

    this.make = make;

    this.screensize = screensize;

    // In practice you would probably have more

    // arguments to set the max and min channel

    // and volume here plus other characteristics for a particular TV.

    }

    public boolean powerOnOff() {

    power = !power;

    System.out.println(make + + screensize + inch TV power

    + (power ? on.:off.));

    return power;

    }

    public int volumeUp(int increment) {

    if(!power) { // If the power is off

    return 0; // Nothing works}

    // Set volume must not be greater than the maximum

    volume += increment;

    volume = min(volume, MAX_VOLUME);

    System.out.println(make + + screensize + inch TV volume level:

    + volume);

    return volume;

    }

    public int volumeDown(int decrement) {

    if(!power) { // If the power is off

    return 0; // Nothing works

    }// Set volume must not be less than the minimum

    volume -= decrement;

    volume = max(volume, MIN_VOLUME);

    System.out.println(make + + screensize + inch TV volume level:

    + volume);

    return volume;

    }

    public void mute() {

    if(!power) { // If the power is off

    return; // Nothing works

    }

    volume = MIN_VOLUME;System.out.println(make + + screensize + inch TV volume level:

    + volume);

    }

    public int setChannel(int newChannel) {

    if(!power) { // If the power is off

    return 0; // Nothing works

    }

    // Channel must be from MIN_CHANNEL to MAX_CHANNEL

    if(newChannel>=MIN_CHANNEL && newChannel

  • 8/2/2019 MCS-024(11-12) (1)

    30/66

    30

    return channel;

    }

    public int channelUp() {

    if(!power) { // If the power is off

    return 0; // Nothing works

    }

    // Wrap channel up to MIN_CHANNEL when MAX_CHANNEL is reached

    channel = channelMIN_CHANNEL ? --channel : MAX_CHANNEL;System.out.println(make + + screensize + inch TV tuned to channel:

    + channel);

    return channel;

    }

    private String make = null;

    private int screensize = 0;

    private boolean power = false;

    private int MIN_VOLUME = 0;

    private int MAX_VOLUME = 100;

    private int volume = MIN_VOLUME;

    private int MIN_CHANNEL = 0;

    private int MAX_CHANNEL = 999;private int channel = 0;

    }

    This class implements all the methods declared in the RemoteControl interface, and each method

    outputs

    a message to the command line so youll know when it is called. Of course, if you omitted any of

    the interface method definitions in the class, the class would be abstract and you would have to

    declare

    it as such.

    A VCR class might also implement RemoteControl:

    import static java.lang.Math.max;import static java.lang.Math.min;

    public class VCR implements RemoteControl {

    public VCR(String make) {

    this.make = make;

    }

    public boolean powerOnOff() {

    power = !power;

    System.out.println(make + VCR power + (power ? on.:off.));

    return power;

    }

    public int volumeUp(int increment) {

    if(!power) { // If the power is off

    return 0; // Nothing works

  • 8/2/2019 MCS-024(11-12) (1)

    31/66

    31

    }

    // Set volume must not be greater than the maximum

    volume += increment;

    volume = min(volume, MAX_VOLUME);

    System.out.println(make + VCR volume level: + volume);

    return volume;

    }

    public int volumeDown(int decrement) {

    if(!power) { // If the power is off

    return 0; // Nothing works

    }

    // Set volume must not be less than the minimum

    volume -= decrement;

    volume = max(volume, MIN_VOLUME);

    System.out.println(make + VCR volume level: + volume);

    return volume;

    }

    public void mute() {if(!power) { // If the power is off

    return; // Nothing works

    }

    volume = MIN_VOLUME;

    System.out.println(make + VCR volume level: + volume);

    }

    public int setChannel(int newChannel) {

    if(!power) { // If the power is off

    return 0; // Nothing works

    }

    // Channel must be from MIN_CHANNEL to MAX_CHANNEL

    if(newChannel>=MIN_CHANNEL && newChannel

  • 8/2/2019 MCS-024(11-12) (1)

    32/66

    32

    private int MIN_VOLUME = 0;

    private int MAX_VOLUME = 100;

    private int volume = MIN_VOLUME;

    private int MIN_CHANNEL = 0;

    private int MAX_CHANNEL = 99;

    private int channel = 0;

    }

    Polymorphism Using an Interface Type

    You want to demonstrate polymorphic behavior with these classes. By introducing a bit of

    randomness

    into the example, you can avoid having any prior knowledge of the objects involved. Heres the

    class to operate both TV and VCR objects via a variable of type RemoteControl:

    import static java.lang.Math.random;

    public class TryRemoteControl {

    public static void main(String args[]) {

    RemoteControl remote = null;// You will create five objects to operate using our remote

    for(int i = 0 ; i

  • 8/2/2019 MCS-024(11-12) (1)

    33/66

    33

    b) What are the classes in Java available for file handling? Write a program in Java to create a file and

    copy the content of an already existing file into it. (5 Marks)

    Solution:

    Java input and output is based on the use of streams, or sequences of bytes that travel from a source toa destination over a communication path. If a program is writing to a stream, you can consider it asstreams source. If it is reading from a stream, it is the streams destination. The communication pathis dependent on the type of I/O being performed. It can consist of memory-to-memory transfers, a filesystem, a network, and other forms of I/O.

    Streams are powerful because they abstract away the details of the communication path from inputand output operations. This allows all I/O to be performed using a common set of methods. Thesemethods can be extended to provide higher-level custom I/O capabilities.

    Three streams given below are created automatically: System.out - standard output stream

    System.in - standard input stream System.err - standard error

    An InputStream represents a stream of data from which data can be read. Again, this stream will beeither directly connected to a device or else to another stream.

    An OutputStream represents a stream to which data can be written. Typically, this stream will eitherbe directly connected to a device, such as a file or a network connection, or to another output stream.

    Java.io packageThis package provides support for basic I/O operations. When you are dealing with the Java.iopackage some questions given below need to be addressed.

    What is the file format: text or binary? Do you want random access capability? Are you dealing with objects or non-objects? What are your sources and sinks for data? Do you need to use filtering?

    For example:

  • 8/2/2019 MCS-024(11-12) (1)

    34/66

    34

    If you are using binary data, such as integers or doubles, then use the InputStream andOutputStream classes.

    If you are using text data, then the Reader and Writer classes are right.

    File handling in java is available through streams and stream classes

    The Java model for I/O is entirely based on streams. There are two types of streams: byte streams andcharacter streams.

    Byt e streams carry integers with values that range from 0 to 255. A diversified data canbe expressed in byte format, including numerical data, executable programs, and bytecodes the class file that runs a Java program.

    Character Str eams are specialized type of byte streams that can handle only textual data.Most of the functionality available for byte streams is also provided for character streams. Themethods for character streams generally accept parameters of data type char, whilebytestreams workwith bytedata types. The names of the methods in both sets of classes are almost identi cal except for

    the suffix, that is, character-stream classes end with the suffix Reader or Writer and byte-streamclasses end with the suffix InputStream and OutputStream. For example, to read files using characterstreams use the Java.io.Fi leReader class, and for reading it using byte streams useJava.io.FileInputStream.

    Unless you are writing programs to work with binary data, such as image and sound files, use readersand writers (character streams) to read and write information for the following reasons:

    They can handle any character in the Unicode character set (while the byte streams arelimited to ISO-Latin-1 8-bit bytes).

    They are easier to internationalize because they are not dependent upon a specificcharacter encoding.

    They use buffering techniques internally and are therefore potentially much moreefficient than byte streams.

    Byte Stream ClassesJava defines two major classes of byte streams: InputStream and OutputStream. To provide a varietyof I/O capabilities subclasses are derived from these InputStream and OutputStream classes.

    InputStream classThe InputStream class defines methods for reading bytes or arrays of bytes, marking locations in thestream, skipping bytes of input, finding out the number of bytes available for reading, and resettingthe current position within the stream. An input stream is automatically opened when created. Theclose() method can explicitly close a stream.

    Methods of I nputStream class The basic method for getting data from any InputStream object is the read() method.

    public abstract int read() throws IOException: reads a single byte from the input stream andreturns it.

    public int read(byte[] bytes) throws IOException: fills an array with bytes read from the streamand returns the number of bytes read.

  • 8/2/2019 MCS-024(11-12) (1)

    35/66

    35

    public int read(byte[] bytes, int offset, int length) throws IOException: fills an array from streamstarting at position offset, up to length bytes. It returns either the number of bytes read or -1 forend of file.

    public int available() throws IOException: the readmethod always blocks when there is no dataavailable. To avoid blocking, program might need to ask ahead of time exactly how many bytescan safely read without blocking. The available method returns this number.

    public long skip(long n): the skip() method skips over n bytes (passed as argument ofskip()method) in a stream.

    public synchronized void mark (int readLimit): this method marks the current position in thestream so it can backed up later.

    OutputStream classThe OutputStream defines methods for writing bytes or arrays of bytes to the stream. An output

    stream is automatically opened when created. An Output stream can be explicitly closed with theclose() method.

    Methods of OutputStream class public abstract void wri te(int b) throws IOException: writes a single byte of data to an output

    stream. public void wri te(byte[] bytes) throws IOException: wri tes the entire contents of the bytes array to

    the output stream. public void wri te(byte[] bytes, int offset, int length) throws IOException: wri tes length number of

    bytes starting at position offset from the bytes array.

    The Java.io package contains several subclasses of InputStream and OutputStream that implementspecific input or output functions. Some of these classes are:

    FileInputStream and FileOutputStream: Read data from or wri te data to a file on the native filesystem.

    PipedInputStream and PipedOutputStream : Implement the input and output components of apipe. Pipes are used to channel the output from one program (or thread) into the input of another.A PipedInputStream must be connected to a PipedOutputStream and a PipedOutputStream mustbe connected to a PipedInputStream.

    ByteArrayInputStream and ByteArrayOutputStream : Read data from or write data to a byte arrayin memory.

    ByteArrayOutputStream provides some additional methods not declared for OutputStream. The

    reset() method resets the output buffer to allow writing to restart at the beginning of the buffer. The size() method returns the number of bytes that have been written to the buffer. The write to ()method is new.

    SequenceInputStream: Concatenate multiple input streams into one input stream. StringBufferInputStream: Allow programs to read from a StringBuffer as if i t were an input

    stream.

    A Program to Copy an already existing File to new File

    import java.io.*;

    public class jCOPY {

  • 8/2/2019 MCS-024(11-12) (1)

    36/66

    36

    public static void main(String args[]){

    try {

    jCOPY j = new jCOPY();

    j.CopyFile(new File(args[0]),new File(args[1]));

    }

    catch (Exception e) {

    e.printStackTrace();

    }

    }

    public void CopyFile(File in, File out) throws Exception {

    FileInputStream fis = new FileInputStream(in);

    FileOutputStream fos = new FileOutputStream(out);

    byte[] buf = new byte[1024];

    int i = 0;

    while((i=fis.read(buf))!=-1) {

    fos.write(buf, 0, i);

    }

    fis.close();

    fos.close();

    }

    }

  • 8/2/2019 MCS-024(11-12) (1)

    37/66

    37

    Question 5: a) Write a java program to find whether a given string is a substring or not, of a string

    provided as input to the program. (5 Marks)

    Solution:

    import java.io.File;

    import java.io.BufferedReader;

    import java.io.FileReader;

    import java.util.StringTokenizer;

    public class WordCounter {

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

    if(args.length != 1) {

    System.out.println("Invalid number of arguments!");

    return;

    }

    String sourcefile = args[0];

    String searchFor = "good bye";

    int searchLength=searchFor.length();

    String thisLine;

    try {

    BufferedReader bout = new BufferedReader (new FileReader (sourcefile));

    String ffline = null;

    int lcnt = 0;

    int searchCount = 0;

    while ((ffline = bout.readLine()) != null) {

    lcnt++;for(int searchIndex=0;searchIndex

  • 8/2/2019 MCS-024(11-12) (1)

    38/66

    38

    b) What is multithreading? Explain how threads are created in Java programs. (5 Marks)

    Solution:

    Multithreaded programs support more than one concurrent thread of execution. This means they areable to simultaneously execute multiple sequences of instructions. Each instruction sequence has itsown unique flow of control that is independent of all others. These independently executed instructionsequences are known as threads.

    Your PC has only a single CPU; you might ask how it can execute more than one thread at the sametime? In single processor systems, only a single thread of execution occurs at a given instant. Butmultiple threads in a program increase the utilization of CPU.

    The CPU quickly switches back and forth between several threads to create an illusion that the threadsare executing at the same time. You know that single-processor systems support logical concurrencyonly. Physical concurrency is not supported by it. Logical concurrency is the characteristic exhibited

    when multiple threads execute with separate, independent flow of control. On the other hand on a

    multiprocessor system, several threads can execute at the same time, and physical concurrency isachieved.

    The advantage of multithreaded programs is that they support logical concurrency. Manyprogramming languages support multiprogramming, as it is the logically concurrent execution ofmultiple programs. For example, a program can request the operating system to execute programs A,B and C by having it spawn a separate process for each program. These programs can run in aconcurrent manner, depending upon the multiprogramming features supported by the underlyingoperating system.

    Multithreading differs from multiprogramming. Multithreading provides concurrency within thecontent of a single process. But multiprogramming also provides concurrency between processes.

    Threads are not complete processes in themselves. They are a separate flow of control that occurswithin a process.

  • 8/2/2019 MCS-024(11-12) (1)

    39/66

    39

    Advantages of Mult ithr eading Concurrency can be used within a process to implement multiple instances of simultaneous

    services. Multi threading requires less processing overhead than multiprogramming because concurrent

    threads are able to share common resources more efficiently.A multithreaded web server is one of the examples of multithreaded programming. Multithreadedweb servers are able to efficiently handle multiple browser requests. They handle one request per

    processing thread.

    Multi threading enables programmers to wri te very efficient programs that make maxi mum use ofthe CPU. Unlike most other programming languages, Java provides built-in support formultithreaded programming. The Java run-time system depends on threads for many things. Javauses threads to enable the enti re environment to be synchronous.

    The multithreading system in Java is built upon the Thr ead Class, its methods and its companioninterface, Runnable. To create a new thread, your program will either extend Thread Classorimplement the Runnable interface. The Thread Class defines several methods that help in managingthreads. For example, if you have to create your own thread then you have to do one of the followingthings:

    Creating Thr eads in Java

  • 8/2/2019 MCS-024(11-12) (1)

    40/66

    40

    1)class MyThread extends Thread{

    MyThread(arguments) // constructor{

    } //initialization

    public void run(){

    // perform operations}

    }

    Write the following code to create a thread and start i t running:MyThread p = new MyThread(arguments);p.start();

    2)class MyThread implements Runnable{

    MyThread(arguments){

    //initialization}

    public void run(){

    // perform operation}

    }

    The Thread Class ConstructorsThe following are the Thread class constructors: Thread() Thread(Runnable target) Thread (Runnable target, String name) Thread(String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup group, Runnable target, String name, long stackSize) Thread(ThreadGroup group, String name)

    Thread Class MethodSome commonly used methods of Thread class are given below: static Thread currentThread() Returns a reference to the currently executing thread object. String getName() Returns the name of the thread in which it is called int getPriority() Returns the Threads priority void interrupt() Used for Interrupting the thread. static boolean interrupted() Used to tests whether the current thread has been interrupted or not. boolean isAlive() Used for testing whether a tread is alive or not. boolean isDaemon() Used for testing whether a thread is a daemon thread or not. void setName(String NewName ) Changes the name of the thread to NewName

  • 8/2/2019 MCS-024(11-12) (1)

    41/66

    41

    void setPriority(int newPriority) Changes the priority of thread. static void sleep(long millisec) Causes the currently executing thread to sleep (temporarily cease

    execution) for the specif ied number of mil liseconds. void start() Used to begin execution of a thread .The Java Virtual Machine calls the run method

    of the thread in which this method is called. String toString() Returns a string representation of thread.String includes the threads name,

    priority, and thread group. static void yi eld() Used to pause temporarily to currently executing thread object and allow other

    threads to execute. static int activeCount() Returns the number of active threads in the current thread's thread group. void destroy() Destroys the thread without any cleanup.

    Creating ThreadsJava provides native support for multithreading. This support is centered on the Java.lang.Threadclass, the Java.lang.Runnable interface and methods of the Java.lang.object class. In Java, support formultithreaded programming is also provided through synchronized methods and statements. The

    thread class provides the capability to create thread objects, each with its own separate flow ofcontrol. The thread class encapsulates the data and methods associated with separate threads ofexecution and enables multithreading to be integrated within Javas object oriented framework. Theminimal multithreading support required of the Thread Class is specified by the java.lang.Runnableinterface. This interface defines a single but important method run.

    public void run( )

    This method provides the entry point for a separate thread of execution. As we have discussed alreadyJava provides two approaches for creating threads. In the first approach, you create a subclass of theThread class and override the run( ) method to provide an entry point for the Threads execution.When you create an instance of subclass of Thread class, you invoke start( ) method to cause the

    thread to execute as an independent sequence of instructions. The start( ) method is inherited from theThread class. It initializes the thread using the operating systems multi threading capabilities, andinvokes the run( ) method.

    A program for creating threads by inheriting the Thread class.

    //programclass MyThreadDemo extends Thread{public String MyMessage [ ]={ "Java","is","very","good","Programming","Language"} ;MyThreadDemo(String s)

    {

    super(s);}

    public void run( ){

    String name = getName( );for ( int i=0; i < MyMessage.length;i++){

    Wait( );System.out.println (name +":"+ MyMessage [i]);

    }}

    void Wait( )

  • 8/2/2019 MCS-024(11-12) (1)

    42/66

    42

    {try{

    sleep(1000);}

    catch (InterruptedException e){

    System.out.println (" Thread is Interrupted");}

    }}

    class ThreadDemo{

    public static void main ( String args [ ]){

    MyThreadDemo Td1= new MyThreadDemo("thread 1:");MyThreadDemo Td2= new MyThreadDemo("thread 2:");Td1.start ( );Td2.start ( );boolean isAlive1 = true;boolean isAlive2 = true;do{

    if (isAlive1 && ! Td1.isAlive( )){

    isAl ive1= false;System.out.println ("Thread 1 is dead");

    }

    if (isAlive2 && !Td2.isAlive( )){

    isAli ve2= false;System.out.println ("Thread 2 is dead");

    }}

    while(isAl ive1 || isAl ive2);}

    }

    Output:thread 1::Javathread 2::Javathread 1::isthread 2::isthread 1::verythread 2::verythread 1::goodthread 2::goodthread 1::Programmingthread 2::Programmingthread 1::Languagethread 2::Language

  • 8/2/2019 MCS-024(11-12) (1)

    43/66

    43

    Thread 1 is deadThread 2 is dead

    This output shows how two threads execute in sequence, displaying information on the console. Theprogram creates two threads of execution, Td 1 and Td2. The threads display the"Java","is","very","good","Programming","Language" message word by word, while waiting a shortamount of time between each word. Because both threads share the console window, the programsoutput identifies which thread wrote to the console during the programs execution.

  • 8/2/2019 MCS-024(11-12) (1)

    44/66

    44

    Question 6: a) What is an Applet? Create an Applet program having two text boxes and one button.

    Read your name in one text box and when button is pressed then your name is transferred into text

    box two. Use appropriate layout in this program. (5Marks)

    Solution:

    Applet is a Java program that runs in theAppletviewer ( a test utility for Applets that is included with

    the J2SDK) or a World Wide Web browser such as Microsoft Internet Explorer or Netscape

    Communicator.

    The Applet class is packed in the Java. Appletpackage which has several interfaces. Theseinterfaces enable the creation of Applets, interaction of Applets with the browser, and playing audio

    clips in Applets. In Java 2, class Javax.swing. JApplet is used to define an Applet that uses the Swing

    GUI components.

    As you know, in Java class hierarchy Object is the base class of Java.lang package. The Applet is

    placed into the hierarchy as follows:

    Below is the list given for Dos and Donts of Java Applets:

    Dos Draw pictures on a web page Create a new window and draw the picture in it.

    Play sounds. Receive input from the user through the keyboard or the mouse. Make a network connection to the server from where the Applet is downloaded, and send to and

    receive arbitrary data from that server.

    Donts Write data on any of the hosts disks. Read any data from the hosts disks without the users permission. In some environments, notably

    Netscape, an Applet cannot read data from the user's disks even with permission.

    Delete files Read from or write to arbitrary blocks of memory, even on a non-memory protected operating

    system like the MacOS

    Make a network connection to a host on the Internet other than the one from which it wasdownloaded.

  • 8/2/2019 MCS-024(11-12) (1)

    45/66

    45

    Call the native API directly (though Java API calls may eventually lead back to native API calls). Introduce a virus or Trojan horse into the host system.

    The Basic Applet Life Cycle, the points listed below should be thought of:1. The browser reads the HTML page and finds any tags.2. The browser parses the tag to find the CODE and possibly CODEBASE attribute.3. The browser downloads the. Class file for the Applet from the URL (Uniform Resource

    Locator) found in the last step.

    4. The browser converts the raw bytes downloaded into a Java class, that is a Java.lang.Classobject.

    5. The browser instantiates the Applet class to form an Applet object. This requires the Applet tohave a no-args constructor.

    6. The browser calls the Applets init () method.7. The browser calls the Applets start () method.8. While the Applet is running, the browser passes all the events intended for the Applet, like

    mouse clicks, key presses, etc. to the Applets handle Event () method.

    9. The default method paint() in Applets just draw messages or graphics (such as lines, ovals

    etc.) on the screen. Update events are used to tell the Applet that it needs to repaint itself.10.The browser calls the Applets stop () method.

    11. The browser calls the Applets destroy () method.

    In brief, you can say that, all Applets use their five following methods:

    public void init ();

    public void start();

    public void paint();

    public void stop();

    public void destroy();

    File : Q6a.java

    // An Applet program having two text boxes and one button. Read your name in one text box

    // and when button is pressed then your name is transferred into text box two

    import java.awt.*;

    import java.applet.*;

    import java.awt.event.*;

    public class Q6a extends Applet implements ActionListener{

    TextField text1,output;

    Label label1,label2;Button button;

    public void init(){

    setLayout(null);

    label1 = new Label("Enter Name: ");

    label1.setBounds(20,20,100,20);

    add(label1);

    text1 = new TextField(5);

    text1.setBounds(150,20,100,20);

    add(text1);

    label2 = new Label("You Entered: ");

  • 8/2/2019 MCS-024(11-12) (1)

    46/66

    46

    label2.setBounds(20,80,130,20);

    add(label2);

    output = new TextField(5);

    output.setBounds(150,80,100,20);

    add(output);

    button = new Button("Submit");

    button.setBounds(150,110,100,20);

    add(button);

    button.addActionListener(this);

    }

    public void actionPerformed(ActionEvent ae){

    String src=text1.getText();

    output.setText(src);}

    }

    Compile :

    File: applet.htm

    Output

  • 8/2/2019 MCS-024(11-12) (1)

    47/66

    47

    b) What is JDBC? Explain steps involved in connecting a databases using JDBC. (5 Marks)

    Solution:

    Java Database Connectivity (JDBC) is a class library which provides a standard way for establishingand maintaining a Java programs connection to a database.

    Java provides JDBC to connect to databases and work with it. Using standard library routines, youcan open a connection to the database. Basically JDBC allows the integration of SQL calls into ageneral programming environment by providing library routines, which interface with the database. Inparticular, Javas JDBC has a rich collection of routines which makes such an interface extremelysimple and intuitive.

    Establishing A ConnectionThe first thing to do, of course, is to install Java, JDBC and the DBMS on the working machines.Since you want to interface with a database, you would need a driver for this specific database.

    Load the vendor specif ic driverThis is very important because you have to ensure portability and code reuse. The API should bedesigned as independent of the version or the vendor of a database as possible. Since differentDBMSs have different behaviour, you need to tell the driver manager which DBMS you wish to use,so that it can invoke the correct driver. For example, an Oracle driver is loaded using the followingcode snippet:

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

    Make the connectionOnce the driver is loaded and ready for a connection to be made, you may create an instance of aConnection object using:

    Connection con = DriverManager.getConnection(url , username, password);

    Let us see what are these parameters passed to get Connection method of DriverManager class. Thefirst string is the URL for the database including the protocol, the vendor, the driver, and the serverthe port number. The username and password are the name of the user of database and password isuser password.

    The connection conreturned in the last step is an open connection, which will be used to pass SQLstatements to the database.

    Creating JDBC StatementsA JDBC Statement object is used to send the SQL statements to the DBMS. It is entirely differentfrom the SQL statement. A JDBC Statement object is an open connection, and not any single SQLStatement. You can think of a JDBC Statement object as a channel sitting on a connection, andpassing one or more of the SQL statements to the DBMS.

    An active connection is needed to create a Statement object. The following code is a snippet, usingour Connection object con

    Statement statmnt = con.createStatement();

    At this point, you wi ll notice that a Statement object exists, but it does not have any SQL statement topass on to the DBMS.

  • 8/2/2019 MCS-024(11-12) (1)

    48/66

    48

    Creating JDBC PreparedStatementPreparedStatement object is more convenient and efficient for sending SQL statements to the DBMS.The main feature, which distinguishes PreparedStatement object from objects of Statement class, isthat it gives an SQL statement right when it is created. This SQL statement is then sent to the DBMSright away, where it is compiled. Thus, in effect, a PreparedStatement is associated as a channel with

    a connection and a compiled SQL statement.

    Another advantage offered by PreparedStatement object is that if you need to use the same or similarquery with different parameters multiple times, the statement can be compiled and optimized by theDBMS just once. While with a normal Statement, each use of the same SQL statement requires acompilation all over again.

    PreparedStatements are also created with a Connection method. The following code shows how tocreate a parameterized SQL statement with three input parameters:

    PreparedStatement prepareUpdatePrice = con.prepareStatement( "UPDATE Employee SETemp_address =? WHERE emp_code = 1001 AND emp_name =?");

    You can see two? symbol in the above PreparedStatementprepareUpdatePrice. This means that youhave to provide values for two variables emp_address and emp_name in PreparedStatement beforeyou execute it. Calling one of the setXXX methods defined in the class PreparedStatement canprovide values. Most often used methods are setInt, setFloat, setDouble, setString, etc. You can setthese values before each execution of the prepared statement.

    You can write something like:prepareUpdatePrice.setInt(1, 3);prepareUpdatePrice.setString(2, "Renuka");prepareUpdatePrice.setString(3, "101, Sector-8,Vasundhara, M.P");

    Executing CREATE/INSERT/UPDATE Statements of SQLExecuting SQL statements in JDBC varies depending on the intention of the SQL statement. DDL(Data Definition Language) statements such as table creation and table alteration statements, as wellas statements to update the table