mcs-024 solved assignment 2015-16

Upload: anonymous-qnf6ydfx

Post on 28-Feb-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    1/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.1 (a) What is Object Oriented Programming? Explain features of Object Oriented

    Programming .

    Ans: 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.

    Figure 2: Real world objects

    The basic difference in Object Oriented programming(OOP) is that the program isorganized around the data being operated upon rather than the operations performed.The basic idea behind OOP is tocombine both, data and its functions that operate onthe data into a single unit calledobject . Now in our next section, we will learn about

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    2/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    the basic concepts used extensively in the Object Oriented approach.Object Oriented methods are favored because many experts agree that ObjectOriented techniques are more disciplined than conventional structured techniques.(Martin and Odell 1992)The main components of Object Oriented technology are objects and classes , dataabstraction and encapsulation , inheritance and polymorphism . It is very

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

    ( )

    FEATURES OF OOP:

    1. Object

    2. Class3. Data Hiding and Encapsulation4. Dynamic Binding5. Message Passing6. Inheritance7. Polymorphism

    Brief Explanation of Points:

    OBJECT: Object is a collection of number of entities. Objects take up space in the memory. Oinstances of classes. When a program is executed , the objects interact by sending messages to o

    Each object contain data and code to manipulate the data. Objects can interact without having knoeach others data or code.

    Lets start withObject. The first thing that we should do in the Object Orientedapproach is to start thinking in terms of Objects. The problem to be solved is dividedinto objects. Start analyzing the problem in terms of objects and the nature ofcommunication between them. Program object should be chosen such that they match

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    3/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    closely with real-world objects. Lets start creating objects using real-life things, forexample, thedog. You can create an object representing a dog, It would have datalikeHow hungry is it ? How happy is it ? Where is it ? Now think what are thedifferent functions you can perform on a dog, likeeat, bark, run anddig. Similarly,the following can be treated as objects in different programming problems:Fig. 3: Dog objectand its behavior

    ! 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-basedapplication.

    CLASS: Class is a collection of objects of similar type. Objects are variables of the type class. Once been defined, we can create any number of objects belonging to that class. Eg: grapes bannans andthe member of class fruit.Objects of the similar type can be grouped together to form a class. Can you tell towhich classdog belongs? Yes, of course, it belongs to theanimal class. Now, let usconcentrate on the creation of objects. This can be easily answered if we look at theway of creating any variable in common programming languages. Almost allcomputer languages havebuilt-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 problem solution. In the simcan define many objects of the same class.You can take a class as a type created by a programmer.A class serves as aplan or template . The programmer has to specify the entire set ofdata and functions for various operations on the data for an object as a user-definedtype in the form of a class. In other words,the programmer defines the objectformat and behavior by defining a class . The compiler of that language does notknow about this user-defined data type. The programmer has to define the data andfunctionality associated with it by designing a class.Finally, defining the class doesnt create an object just as the existence of a built-in

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    4/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    type integer doesnt create any variable. Once the class has been defined, you cancreate any number of objects belonging to that class.A class is thus acollection of objects of similar type . For example, in a collection ofpotatoes 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.

    Example:Fruit orange;In the above statement object mango is created which belong to the class fruit.NOTE: Classes are user define data types.

    DATA ENCAPSULATION: Combining data and functions into a single unit calledclass and the process is known asEncapsulation .Datencapsulation is important feature of a class.

    The wrapping up of data and functions into a single unit is known asencapsulation .This is one of the strong features of the object oriented approach. The data is notdirectly 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. Thesefunctions provide the interface to access data. If one wants to modify the data of anobject, s/he should know exactly what functions are available to interact with it. Thisinsulation of the data from direct access by the program is known asdata hiding .DATA ABSTRACTION: Class contains both data and functions. Data is not accessible from the outsiand only those function which are present in the class can access the data. The insulation of the dataaccess by the program is called data hiding or information hiding. Hiding the complexity of proraAbstraction and only essential features are represented.In short we can say that internal working is hiAbstraction refers to the act of representing essential features without including thebackground details to distinguish objects/ functions from other objects/functions. Incase of structured programming,functional abstraction was provided by telling,which task is performed by function and hiding 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 concernedabout the exact details of implementation. As in case of built-in data types likeinteger, floating point, etc. The programmer only knows about the various operationswhich can be performed on these data types, but how these operations are carried outby the hardware or software is hidden from the programmer. Similarly in ObjectOriented approach, classes act asabstract data types . Classes are defined as a set ofattributes and functions to operate on these attributes. They encapsulate all theessential properties of the objects that are to be created.

    DYNAMIC BINDING: Refers to linking of function call with function defination is called binding anis take place at run time called dynamic binding.

    MESSAGE PASSING: The process by which one object can interact with other object is called passing.For example, in the banking system, customer object may send a messagenamed ascheck balance to the account object to get the response, i.e. bank balance.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    5/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    An Object Oriented system can be considered asnetwork of cooperating objectswhich interact by sending messages to each other. Lets see in theFigure 4 , howobjects interact by sending messages to one another.

    INHERITANCE: it is the process by which object of one class aquire the properties or features of oanother class. The concept of inheritance provide the idea of reusability means we can add additionaan existing class without Modifying it. This is possible by driving a new class from the existing onclass will have the combined features of both the c

    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 theclass two-wheelers, which is again a type of (or kind of) the class motor vehicles. Asshown in theFigure 5 the principle behind it is that the derived class shares commoncharacteristics with the class from which it is derived.New classes can be built from the existing classes. It means that we can addadditional features to an existing class without modifying it. The new class is referredas derived class or sub class and the original class is known asbase class or superclass . Therefore, the concept of inheritance provides the idea ofreusability. 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 inFigure 5 , three classes have been derived from one base class. Feature Aand Feature B of the base class are inherited in all the three derived classes. Also,each derived class has added its own features according to the requirement.Therefore, new classes use the concept of reusability and extend their functionality.Example:Robine is a part of the class flying bird which is again a part of the class bird.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    6/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    POLYMORPHISM: A greek term means ability to take more than one form. An operation maydifferent behaviours in different instances. The behaviour depends upon the types of data used in thePolymorphism meansthe ability to take more than one form of the sameproperty. For example, consider an addition operation. It shows a different behaviorin different types of data. For two numbers, it will generate a sum. The numbers mayintegers or float. Thus the addition for integers is different from the addition tofloats.An example is shown inFigure 6, where single function name, i.e.draw can be usedto drawdifferent shapes . The name is the same in all the classes but the functionalitydiffers. This is known as function overriding, which is a type of polymorphism. Wewill discuss it in detail in our next unit.In our example, we also used a functionarea which was inherited by all the threederived classes, i.e.triangle , circle andrectangle . But in the cases of the circle andthe triangle, we override the function area because the data types and number ofparameters varies.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    7/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.1 (b) What is platform independence? Explain why java is platform independent.

    Ans: Java was developed by SUN Microsystems in 1991 underthe guidance of James Gosling. Its an Object Oriented, general-purpose programminglanguage. After its birth it became popular because of many reasonslike security,robustness and multithreadedness but mainly because of its characteristic ofArchitecture Neutral and platform independent . The logic and magic behind itsplatform independence is BYTECODE. Java offers two flavors of programming,Java application and Java applet. Application can be executed independently whileapplet cannot be executed independently. When we compile a Java program we getJava bytecode (.class file) that can be executed on any other computer system,equipped with Java interpreter. To execute applets you can use applet viewer orexplorer to run Java embedded HTML code.You learnt the meaning of different Java keywords which have special meaning forcompiler and cannot be used as a user defined identifier. Java supports eight primitivedata types which can be classified into four categories. Each data type has its memorysize and range of values it can store. Before using the Java variables in your programyou should declare them and assign them some value. You learnt how to declare avariable dynamically with the help of an example. You have learnt different types ofoperators in the last section of this unit which are similar to C++ so you must befamiliar with some of them. You must be tired after reading a long unit so now youcan go and have a cup of coffee. In the next unit we will discuss about the classes andobjects in Java.

    ( P L (

    .Java 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 typicallymeans some combination of hardware and system software but here you canunderstand it as your operating system.Java is compiled to an intermediate form calledJava byte-code or simply byte code.A Java program never really executes immediately after compilation on the hostmachine. Rather, this special program called the Java interpreter or Java VirtualMachine reads the byte code, translates it into the corresponding host machine

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    8/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    instructions and then executes the machine instruction. A Java program can run onany computer system for which a JVM (Java Virtual Machine ) and some libraryroutines have been installed. The second important part which makes Java portable isthe elimination of hardware architecture dependent constructs. For example, Integersare always four bytes long and floating-point variables follow the IEEE 754.You dontneed to worry that the interpretation of your integer is going to change if you movefrom one hardware to another hardware like Pentium to a PowerPC. You can developthe Java program on any computer system and the execution of that program ispossible on any other computer system loaded with JVM. For example, you can writeand compile the Java program on Windows 98 and execute the compiled program onJVM of the Macintosh operating system. The same concept is explained in Figure 1given below.

    S ,

    J M .

    . S M S ORA: O R A .

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    9/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.1 (b)Write a program to explain how array of objects may be created in java.

    Ans: A , . F ,

    . H , S

    S . T , , . F .

    S ;

    A .

    S A = S 7 ;

    T S . I ' . T S

    S . I S , . F , N P E A 0 ' S

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    10/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    A 0 . = 100;

    T S S .

    A 0 = S ();

    I , S . I S , . H ,

    S .

    ( =0; < A . ; ++) A = S ();

    T S

    .

    A 0 . =100;

    E S . T S . T

    S S .

    ( S : A ) . = . I (); // S

    R

    M , , , . T . T

    . F .

    (S ) S A = S 7 ;

    A 0 = S ();A 0 . = 99;

    S . . ( A 0 . ); // 99( A 0 );

    S . . ( A 0 . ); // 100 99

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    11/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    //

    (S ) . = 100;

    C .

    P . N P E

    , . M , .

    Pograam Is :

    (S )

    // S

    F = F

    0 = F ("S ",13

    1 = F ("R P "

    2 = F ("T T C D

    3 = F ("E ",114

    F L = , S = ;// T

    = 0, = 0; // T

    ( =0; < . ; ++)

    = .

    ( == 0)

    S = L =

    = =

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    12/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    ( < )

    = ;

    S =

    ( > )

    = ;

    L =

    S . . ("L "

    L . ()

    " "+ +"

    S . . ("S "

    S . ()

    " "+ +"

    Q .2 ( )

    Ans: Java programming language is a statically typed language. It means that every variableexpression has a type that is known at compile time. Java language is also a strongly typed languatypes limit the values that a variable can hold or that an expression can produce, limit the operationon those values, and determine the meaning of the operations. Strong static typing helps detect errortime. Variables in dynamically typed languages like Ruby or Python can receive different data typtime. In Java, once a variable is declared to be of a certain data type, it cannot hold values of other d

    There are two fundamental data types in Java: primitive types andreference types . Primitive types are: boolean char byte short

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    13/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    int long float double

    To Represent use of Boolean Variablepackage com.zetcode;

    import java.util.Random;

    public class BooleanType {

    public static void main(String[] args) {

    String name = "";Random r = new Random();boolean male = r.nextBoolean();

    if (male == true) {

    name = "Robert";}

    if (male == false) {

    name = "Victoria";}

    System.out.format("We will use name %s%n", name);

    System.out.println(9 > 8);}

    }

    Qst.2 (b) Explain followings in context of java, with the help of examples.Ans:( ) OBJECT: Object is a collection of number of entities. Objects take up spacmemory. Objects are instances of classes. When a program is executed , the objects interact bmessages to one another. Each object contain data and code to manipulate the data. Objects can intehaving know details of each others data or code.

    Lets start withObject. The first thing that we should do in the Object Orientedapproach is to start thinking in terms of Objects. The problem to be solved is dividedinto objects. Start analyzing the problem in terms of objects and the nature of

    communication between them. Program object should be chosen such that they matchclosely with real-world objects. Lets start creating objects using real-life things, forexample, thedog. You can create an object representing a dog, It would have datalikeHow hungry is it ? How happy is it ? Where is it ? Now think what are thedifferent functions you can perform on a dog, likeeat, bark, run anddig. Similarly,the following can be treated as objects in different programming problems:Fig. 3: Dog object

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    14/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    and its behavior! 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-basedapplication.

    CLASS: Class is a collection of objects of similar type. Objects are variables of the type class. Once been defined, we can create any number of objects belonging to that class. Eg: grapes bannans andthe member of class fruit.Objects of the similar type can be grouped together to form a class. Can you tell towhich classdog belongs? Yes, of course, it belongs to theanimal class. Now, let usconcentrate on the creation of objects. This can be easily answered if we look at theway of creating any variable in common programming languages. Almost allcomputer languages havebuilt-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 problem solution. In the simcan define many objects of the same class.You can take a class as a type created by a programmer.A class serves as aplan or template . The programmer has to specify the entire set ofdata and functions for various operations on the data for an object as a user-definedtype in the form of a class. In other words,the programmer defines the objectformat and behavior by defining a class . The compiler of that language does notknow about this user-defined data type. The programmer has to define the data andfunctionality associated with it by designing a class.Finally, defining the class doesnt create an object just as the existence of a built-intype integer doesnt create any variable. Once the class has been defined, you cancreate any number of objects belonging to that class.A class is thus acollection of objects of similar type . For example, in a collection ofpotatoes 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.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    15/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Example:Fruit orange;In the above statement object mango is created which belong to the class fruit.NOTE: Classes are user define data types.

    ( ) Data abstraction and encapsulationThe wrapping up of data and functions into a single unit is known asencapsulation .This is one of the strong features of the object oriented approach. The data is notdirectly accessible to the outside world and only the functions, which are wrapped inthe class, can access it. Functions are accessible to the outside world. Thesefunctions provide the interface to access data. If one wants to modify the data of anobject, s/he should know exactly what functions are available to interact with it. Thisinsulation of the data from direct access by the program is known asdata hiding .Abstraction refers to the act of representing essential features without including thebackground details to distinguish objects/ functions from other objects/functions. Incase of structured programming,functional abstraction was provided by telling,which task is performed by function and hiding 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 concernedabout the exact details of implementation. As in case of built-in data types likeinteger, floating point, etc. The programmer only knows about the various operationswhich can be performed on these data types, but how these operations are carried outby the hardware or software is hidden from the programmer. Similarly in ObjectOriented approach, classes act asabstract data types . Classes are defined as a set ofattributes and functions to operate on these attributes. They encapsulate all theessential properties of the objects that are to be created.

    (iii) Application program and applet program : All Java programs can be classified asApplications andApplets . The striking differences are that applications contain main() method where as applets domore is, applications can be executed at DOS prompt and applets in a browser. We can say, an aInternet application . Come on, read further.

    Definition Importance

    Applet is a Java program executed by a browser. The position of applets in software world is they client-side position in Web communication. On the server-side, you guess, another Java progrServlets . Applets on client-side and servlets on server-side makes Java a truly "Internet-based language ". Toexecute applets, the browsers come with JRE (Java Runtime Environment). The browsers with JaEnvironment (or to say, JVM) loaded are known asJava enabled browsers .

    Note: Browser do not have a Java compiler as a compiled applet file (.class file) is given to browser t

    Applications Vs. Applets

    You have seen two main differences between applications and applets. Let us summarize them.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    16/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    ()P N

    E R JRE R C

    N C

    R

    R C

    S D R

    Advantages of Applets

    1. E ( ).

    2. ( ) 3. I GUI , , , . (

    ).

    Restrictions of Applets

    1. A .2. I , 3. A (

    ) , . .

    4. E C .

    What Applet can't do Security Limitations

    Applets are treated asuntrusted because they are developed by somebody and placed on some unknoserver. When downloaded, they may harm the system resources or steal passwords and valuable available on the system. As applets areuntrusted , the browsers come with many security restrictions. Spolicies are browser dependent. Browser does not allow the applet to access any of the system resouis permitted to use browser resources, infact, applet execution goes within the browser only).

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    17/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    A .

    A . A . A A A ( ) C

    The JRE throwsSecurityException if the applet violates the browser restrictions.

    Applet Architecture

    Applets permitGUI and handling events. Infact, an applet will be in waiting mode forever expectinevent (input) to occur from the user. Applets areevent driven andwindow-based . The event is forwardedthe AWT GUI environment (graphics environment) to the applet. The applet takes the event, do sand return the control back to AWT. Applet does not keep the execution control with it for a long

    programmer would like to listen the music continuously or use some banner to display, he museparated thread and assign the job to it.

    Note: Do not try to take input from keyboard with applets as applets arewindow-based and instead you ccreate some GUI text field and take input.

    Qst3. (a) What is static variable and static method? Explain why main method in java is always static.

    If you declare any variable as static, it is known static variable.

    T ( . . , .

    T .

    It makes your programmemory efficient (i.e it saves memory).

    1. S2. ;3. S ;4. S ="ITS";5.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    18/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Suppose there are 500 students in my college, now all instance data members will get memory eachobject is created.All student have its unique rollno and name so instance data member is good.Hrefers to the common property of all objects.If we make it static,this field will get memory only once

    .

    1. //P 2. 3. S 84. ;5. S ;6. S ="ITS";7. 8. S 8( ,S )9. = ;10. = ;11. 12. () S . . ( +" "+ +" "+ );13. 14. (S )15. S 8 1 = S 8(111,"K ");16. S 8 2 = S 8(222,"A ");17. 18. 1. ();19. 2. ();20.

    21.

    T N Output:111 Karan ITS

    222 Aryan ITS

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    19/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    In this example, we have created an instance variable named count which is incremented in the Since instance variable gets the memory at the time of object creation, each object will have the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have ththe count variable.

    1. C2. =0;// 3. 4. C ()5. ++;

    6. S . . ( );7. 8. 9. (S )10. 11. C 1= C ();

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    20/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    12. C 2= C ();13. C 3= C ();14. 15. 16.

    T N Output:1

    11

    A , , , .

    1. C 22. =0;// 3. 4. C 2()5. ++;6. S . . ( );7. 8. 9. (S )10. 11. C 2 1= C 2();12. C 2 2= C 2();13. C 2 3= C 2();14. 15. 16.

    T N Output:1

    23

    If you apply static keyword with any method, it is known as static method.

    A . A .

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    21/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    .

    1. //P ( ).2. 3. S 94. ;5. S ;6. S = "ITS";7. 8. ()9. = "BBDIT";10. 11. 12. S 9( , S )13. = ;

    14. = ;15. 16. 17. () S . . ( +" "+ +" "+ );18. 19. (S )20. S 9. ();21. 22. S 9 1 = S 9 (111,"K ");23. S 9 2 = S 9 (222,"A ");24. S 9 3 = S 9 (333,"S ");25. 26. 1. ();27. 2. ();28. 3. ();29. 30.

    T N Output:111 Karan BBDIT

    222 Aryan BBDIT333 Sonoo BBDIT

    1. //P 2. 3. C

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    22/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    4. ( )5. * * ;6. 7. 8. (S )9. =C . (5);

    10. S . . ( );11. 12.

    T N Output:125

    T . T :

    1. T .

    2. .

    1. A2. =40;// 3. 4. (S )5. S . . ( );6. 7.

    T N Output:Compile Time ErrorMain method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet orany other container managed Java program where life cycle methods are provided to control the execution. In coreJava program, execution starts from main method when you type java main-class-name, JVM search for public staticvoid main(String args[]) method in that class and if it doesn't find that method it throws errorNoSuchMethodError:main and terminates.

    Signature of main method in Java

    Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will notrun. Here is the exact signature of main method

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    23/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    public static void main(String args[])

    This signature is classic signature and there from start of Java but with introduction of variable argument or varargsin Java5 you can also declare main method in Java using varargs syntax as shown in below example:

    public static void main(String... args)

    Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, staticand void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java mainmethod.

    Qst.3 (b) What is inheritance? Explain the advantage of inheritance with an example program. What aredifferent types of inheritance supported by java?

    : .

    The idea behind inheritance in java is that you can create new classes that are built upon existing clayou inherit from an existing class, you can reuse methods and fields of parent class, and you camethods and fields also.

    Inheritance represents theIS-A relationship , also known as parent-child relationship.

    F M O ( ). F C R .

    1. S S2. 3. // 4.

    Theextends keyword indicates that you are making a new class that derives from an existing class.

    In the terminology of Java, a class that is inherited is called a super class. The new class is called a s

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    24/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Advantages:-

    One of the key benefits of inheritance is to minimize the amount of duplicate code in an application bysharing common code amongst several subclasses. Where equivalent code exists in two relatedclasses, the hierarchy can usually be refactored to move the common code up to a mutualsuperclass. This also tends to result in a better organization of code and smaller, simpler compilationunits.

    Inheritance can also make application code more flexible to change because classes that inherit froma common superclass can be used interchangeably. If the return type of a method is superclass

    Reusability -- facility to use public methods of base class without rewriting the sameExtensibility -- extending the base class logic as per business logic of the derived classData hiding -- base class can decide to keep some data private so that it cannot be altered by thederived class

    Overriding--With inheritance, we will be able to override the methods of the base class so thatmeaningful implementation of the base class method can be designed in the derived class.

    Disadvantages:-

    1.One of the main disadvantages of inheritance in Java (the same in other object-oriented languages)is the increased time/effort it takes the program to jump through all the levels of overloaded classes.If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to runthrough a function defined in each of those classes

    2.Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightlycoupled.This means one cannot be used independent of each other.

    3. Also with time, during maintenance adding new features both base as well as derived classes arerequired to be changed. If a method signature is changed then we will be affected in both cases(inheritance & composition)

    4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case ofusing that method.Here things can get a bit complicated in case of inheritance because our programswill still compile, but the methods of the subclass will no longer be overriding superclass methods.These methods will become independent methods in their own right.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    25/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Rbetween two classes isProgrammer IS-A Employee .It means that Programmer is a type of Employee.

    1. E2. =40000;3.

    4. P E5. =10000;6. (S )7. P = P ();8. S . . ("P :"+ . );9. S . . ("B P :"+ . );10. 11.

    T N Programmer salary is:40000.0Bonus of programmer is:10000

    In the above example, Programmer object can access the field of own class as well as of Employcode reusability.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    26/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchic

    In java programming, multiple and hybrid inheritance is supported through interface only. We will

    interfaces later.

    .

    When a class extends multiple classes i.e. known as multiple inheritance. For Example:

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    27/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    1)

    Single inheritance is damn easy to understand. When a class extends another one class only then wsingle inheritance. The below flow diagram shows that class B extends only one class which is A. parent class of B and B would be achild class of A.

    Single Inheritance example program in Java

    Class A{

    public void methodA()

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    28/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    {System.out.println("Base class method");

    }}

    Class B extends A{

    public void methodB(){System.out.println("Child class method");

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

    B obj = new B();obj.methodA(); //calling super class methodobj.methodB(); //calling local method

    }}

    2)

    Multiple Inheritance refers to the concept of one class extending (Or inherits) more than one base inheritance we learnt earlier had the concept of one base class or parent. The problem withinheritance is that the derived class will have to manage the dependency on two base classes.

    Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance ofproblems in the hierarchy. This results in unwanted complexity when further extending the class.

    Note 2: Most of the new OO languages likeSmall Talk, Java, C# do not support Multiple inheritanceMultiple Inheritance is supported in C++.

    3)

    Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derivthereby making this derived class the base class for the new class. As you can see in below flow dsubclass or child class of B and B is a child class of A. For more details and example refer Multileveinheritance in Java.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    29/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Multilevel Inheritance example program in Java

    Class X{

    public void methodX(){

    System.out.println("Class X method");}

    }Class Y extends X{public void methodY(){System.out.println("class Y method");}}Class Z extends Y{

    public void methodZ()

    {System.out.println("class Z method");

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

    Z obj = new Z();obj.methodX(); //calling grand parent class methodobj.methodY(); //calling parent class methodobj.methodZ(); //calling local method

    }}

    4)

    In such kind of inheritance one class is inherited by many sub classes . In below example class B,C aninherits the same class A. A isparent class (or base class) of B,C & D. Read More at HierarchicInheritance in java with example program.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    30/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    5)

    In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance. Atypical flow diagram would look like below. A hybrid inheritance can be achieved in the java in a smultiple inheritance can be!! Using interfaces. yes you heard it right. By usinginterfaces you can have multias well ashybrid inheritance in Java.

    Read the full article here hybrid inheritance in java with example program.

    Qst.3 (c) Explain the steps involved in creating a distributed application using Remote Method Invocation(RMI).

    Ans: The Java Remote Method Invocation (RMI) mechanism and the Common Object RequeArchitecture (CORBA) are the two most important and widely used distributed object systems. Eachits own features and shortcomings. Both are being used in the industry for various applications rangcommerce to health care. Selecting which of these two distribution mechanisms to use for a projectask. This article presents an overview of RMI and CORBA, and more importantly it shows how tuseful application for downloading files from remote hosts. It then:

    P

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    31/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    P RMI CORBA G RMI CORBA S RMI CORBA P RMI CORBA

    /

    The client/server model is a form of distributed computing in which one program (the client) comwith another program (the server) for the purpose of exchanging information. In this model, both thserver usually speak the same language -- a protocol that both the client and server understand -- able to communicate.

    While the client/server model can be implemented in various ways, it is typically done using low-leUsing sockets to develop client/server systems means that we must design a protocol, which commands agreed upon by the client and server through which they will be able to communicexample, consider the HTTP protocol that provides a method calledGET , which must be implemented byweb servers and used by web clients (browsers) in order to retrieve documents.

    A distributed object-based system is a collection of objects that isolates the requesters of services (cthe providers of services (servers) by a well-defined encapsulating interface. In other words, clientsfrom the implementation of services as data representations and executable code. This is one odifferences that distinguishes the distributed object-based model from the pure client/server model.

    In the distributed object-based model, a client sends a message to an object, which in turns intmessage to decide what service to perform. This service, or method, selection could be performed bobject or a broker. The Java Remote Method Invocation (RMI) and the Common Object RequArchitecture (CORBA) are examples of this model.

    RMI is a distributed object system that enables you to easily develop distributed Java applications. distributed applications in RMI is simpler than developing with sockets since there is no need protocol, which is an error-prone task. In RMI, the developer has the illusion of calling a local melocal class file, when in fact the arguments are shipped to the remote target and interpreted, and thesent back to the callers.

    Developing a distributed application using RMI involves the following steps:

    1. D 2. I

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    32/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    3. D 4. D 5. G S S , RMI , ,

    We will now examine these steps through the development of a file transfer application.

    This application allows a client to transfer (or download) any type of file (plain text or binary) fromachine. The first step is to define a remote interface that specifies the signatures of the methods to by the server and invoked by clients.

    Define a remote interface

    The remote interface for the file download application is shown in Code Sample 1. TheFileInterface provides one methoddownloadFile that takes aString argument (the name of the file) returns the data of the file as an array of bytes.

    Code Sample 1 : FileInterface.java

    import java.rmi.Remote;import java.rmi.RemoteException;

    public interface FileInterface extends Remote {public byte[] downloadFile(String fileName) throwsRemoteException;

    }

    Note the following characteristics about theFileInterface :

    I public , .

    I Remote , E java.rmi.RemoteException .

    Implement the remote interface

    The next step is to implement the interfaceFileInterface . A sample implementation is shown in Sample 2. Note that in addition to implementing theFileInterface , the FileImpl class is extending tUnicastRemoteObject . This indicates that theFileImpl class is used to create a single, non-replicated, robject that uses RMI's default TCP-based transport for communication.

    Code Sample 2 : FileImpl.java

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    33/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    import java.io.*;import java.rmi.*;import java.rmi.server.UnicastRemoteObject;

    public class FileImpl extends UnicastRemoteObjectimplements FileInterface {

    private String name;

    public FileImpl(String s) throws RemoteException{super();name = s;

    }

    public byte[] downloadFile(String fileName){try {

    File file = new File(fileName);byte buffer[] = new byte[(int)file.length()];BufferedInputStream input = new

    BufferedInputStream(new FileInputStream(fileName));

    input.read(buffer,0,buffer.length);input.close();return(buffer);

    } catch(Exception e){System.out.println("FileImpl: "+e.getMessage());e.printStackTrace();return(null);

    }}

    }

    Develop the server The third step is to develop a server. There are three things that the server needs to do:

    1. C RMISecurityManager 2. C (FileImpl )3. R RMI . A C S

    Code Sample 3 : FileServer.java

    import java.io.*;

    import java.rmi.*;

    public class FileServer {public static void main(String argv[]) {

    if(System.getSecurityManager() == null) {System.setSecurityManager(new RMISecurityManager());

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    34/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    }try {

    FileInterface fi = new FileImpl("FileServer");Naming.rebind("//127.0.0.1/FileServer", fi);

    } catch(Exception e) {System.out.println("FileServer: "+e.getMessage());e.printStackTrace();

    }}

    }

    The statementNaming.rebind("//127.0.0.1/FileServer", fi) assumes that the RMI registry is runon the default port number, which is 1099. However, if you run the RMI registry on a different pormust be specified in that statement. For example, if the RMI registry is running on port 4500, then thbecomes:

    Naming.rebind("//127.0.0.1:4500/FileServer", fi)

    Also, it is important to note here that we assume the rmi registry and the server will be running omachine. If they are not, then simply change the address in therebind method.

    Develop a client

    The next step is to develop a client. The client remotely invokes any methods specified in the remotFileInterface ). To do so however, the client must first obtain a reference to the remote object fromregistry. Once a reference is obtained, thedownloadFile method is invoked. A client implementation is sin Code Sample 4. In this implementation, the client accepts two arguments at the command line: thethe name of the file to be downloaded and the second one is the address of the machine from which be downloaded, which is the machine that is running the file server.

    Code Sample 4 : FileClient.java

    import java.io.*;import java.rmi.*;

    public class FileClient{public static void main(String argv[]) {

    if(argv.length != 2) {System.out.println("Usage: java FileClient fileName machineName");System.exit(0);

    }try {

    String name = "//" + argv[1] + "/FileServer";FileInterface fi = (FileInterface) Naming.lookup(name);byte[] filedata = fi.downloadFile(argv[0]);File file = new File(argv[0]);

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    35/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    BufferedOutputStream output = newBufferedOutputStream(new FileOutputStream(file.getName()));

    output.write(filedata,0,filedata.length);output.flush();output.close();

    } catch(Exception e) {System.err.println("FileServer exception: "+ e.getMessage());e.printStackTrace();

    }}

    }

    Qst.4 (a) What is polymorphism? Is Interfaces in Java, a kind of polymorphism? Justify your answehelp of an example.A :Polymorphism is the capability of amethod to do different things based on the objectthrough 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 typeof actual object always determines method calls; object reference type doesnt playany role in it. You have already used two types of polymorphism (overloading andoverriding) in the previous unit and in the current unit of this block. Now we will lookat the third:dynamic method binding . Java uses Dynamic Method Dispatchmechanism to decide at run time which overridden function will be invoked. DynamicMethod Dispatch mechanism is important because it is used to implement runtimepolymorphism in Java. Java uses the principle: a super class object can refer to asubclass object to resolve calls to overridden methods at run time.If a superclass has method that is overridden by its subclasses, then the differentversions of the overridden methods are invoked or executed with the help of asuperclass 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 ownPlay() 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{

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    36/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    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 PlayerlCricket_Player aCplayer = new Cricket_Player("Sachin"); // makes specific objectsHockey_Player aHplayer = new Hockey_Player("Dhanaraj");Football_Player aFplayer = new Football_Player("Bhutia"); // now reference each as an Animalref = aCplayer;ref.Play();ref = aHplayer;ref.Play();ref = aFplayer;ref.Play();}}Output:Play Cricket:SachinPlay Hockey:DhanarajPlay Football:BhutiaNotice that although each method is invoked through ref, which is a reference to

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    37/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    player class (but no player objects exist), the program is able to resolve the correct method related to the subclruntime. This is known as dynamic (or late)method binding.

    As illustrated in the previous chapter, one of the most important benefits of class extension is that yadvantage of polymorphism. In an inheritance hierarchy, if classCoffeeCup extends classCup , you can treatCoffeeCup object as if it were aCup object. Sometimes, however, it is difficult to get the polymorphiwant from the singly-inherited hierarchies you can build with class extension. To help you polymorphism than you can easily get with single- inheritance, Java supports a restricted form inheritance through a construct called the "interface." This chapter will discuss the motivatiomechanics of the Java interface.

    To reap the benefits of polymorphism through class extension, you must build a family of classes . In Javterminology, both classes and interfaces are "types." When you declare an interface, as when yoclass, you establish a new type. In the remainder of this book, "type" will be used to refer to eitheinterfaces. Here, a "family of classes" is simply a family of types in which all the types are classeinterfaces). Thus, a family of classes is a group of related classes with a single base class from whiclasses in the family descend. Since every class in Java descends fromObject , all Java classes are memberthe Object family; however, you can still look at individual areas of an inheritance hierarchy as "families of classes." For example, classCup and all its subclasses, as shown in Figure 4-1, form theCup family[bv: I believe I covered this already in a previous chapter.]

    Figure 4-1. TheCup family

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    38/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Given a family of classes, polymorphism allows you to treat a subclass object as if it were a supercFor example, imagine you wanted to create a single method that could wash any kind of cup in cafe. You could declare a public method namedwash() in the base class of theCup family:

    // In Source Packet in file interface/ex1/Cup.javaclass Cup {

    public void wash() {System.out.println("Washing a Cup.");// ...

    }//...

    }

    // In Source Packet in file interface/ex1/CoffeeCup.javaclass CoffeeCup extends Cup {

    public void wash() {System.out.println("Washing a CoffeeCup.");// ...

    }//...

    }

    // In Source Packet in file interface/ex1/CoffeeMug.javaclass CoffeeMug extends CoffeeCup {

    public void wash() {System.out.println("Washing a CoffeeMug.");// ...

    }//...

    }

    // In Source Packet in file interface/ex1/EspressoCup.javaclass EspressoCup extends CoffeeCup {

    public void wash() {System.out.println("Washing an EspressoCup.");// ...

    }//...

    }

    Given this family of types, you could define a method that takes aCup reference as follows:

    // In Source Packet in file interface/ex1/VirtualCafe.javaclass VirtualCafe {

    public static void prepareACup(Cup cup) {//...

    cup.wash();//...

    }//...

    }

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    39/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Using polymorphism, you could pass to the method a reference to any object that is-aCup :

    // In Source Packet in file interface/ex1/Example1.javaclass Example1 {

    public static void main(String[] args) {

    Cup c = new Cup();CoffeeCup cc = new CoffeeCup();CoffeeMug cm = new CoffeeMug();EspressoCup ec = new EspressoCup();VirtualCafe.prepareACup(c);VirtualCafe.prepareACup(cc);VirtualCafe.prepareACup(cm);VirtualCafe.prepareACup(ec);

    }}

    Here you have all the benefits of polymorphism. TheprepareACup() method can invokewash() on mandifferent objects, but it doesn't need to useinstanceof . As a consequence, the code is easier to read

    change. If later, you wanted to add classTeaCup to your program and washTeaCup objects witprepareACup() , you only need to makeTeaCup a subclass ofCup . You don't need to change prepareACup() method itself.

    Qst.4 (b) Explain the need of package in Java. Write a java program to show how package is created.

    Ans Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packagimplementations of Java use a hierarchical file system to manage source and class files. It is easy class files into packages. All we need to do is put related class files in the same directory, give thename that relates to the purpose of the classes, and add a line to the top of each class file that dpackage name, which is the same as the directory name where they reside.

    In java there are already many predefined packages that we use while programming.

    For example: java.lang , java.io , java.util etcHowever one of the most useful feature of java is that we can define our own packages

    Advantages of using a package

    Before discussing how to use them Let see why we should use packages.

    Reusability: Reusability of code is one of the most important requirements in the softwar

    Reusability saves time, effort and also ensures consistency. A class once developed can be reunumber of programs wishing to incorporate the class in that particular program. Easy to locate the files. In real life situation there may arise scenarios where we need to define files of the same name

    lead to name-space collisions. Packages are a way of avoiding name-space collisions.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    40/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Types of package:1) User defined package: The package we create is called user-defined 2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in

    Defining a Package:This statement should be used in the beginning of the program to include that program in thapackage.package ;

    Example :

    package tools;public class Hammer {

    public void id (){

    System.out.println ("Hammer");}

    }

    :armstrong.javapublic class armstrong{

    int x=407;int r,temp,a=0;public void test(){temp=x;while(x>0){

    r=x%10;a=a+(r*r*r);x=x/10;

    }if(temp==a){

    System.out.println("This is Armstrong no..");}

    else{

    System.out.println("This is not Armstrong no..");}}}

    After the creation of the program then compile this program with following syntax:

    javac armstrong.java

    If compile this part with successfully then write down this program.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    41/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Listing 2 : Sample showing Example calling package

    cal.javaimport cei.*;public class cal{

    public static void main(String args[]){armstrong ob=new armstrong();ob.test(); //this part is calling package method

    }}

    Then compile the code cal.java

    javac cal.java

    After that we interpreting this program cal.java

    java cal

    Then this call.java will be interpreted and run this program and show the output

    Output:

    This is Armstrong no.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    42/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.4 (c) What is rule of accessibility? Explain different level of accessibility in java.

    1. 2. R 3. 4. 5. 6. A

    There are two types of modifiers in java:access modifiers andnon-access modifiers .

    The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or

    There are 4 types of java access modifiers:

    1. 2. 3. 4.

    There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transienwe will learn access modifiers.

    1) T .

    I , A S . A , .

    1. A2. =40;

    3. () S . . ("H ");4. 5. 6. S7. (S )8. A = A();

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    43/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    9. S . . ( . );//C T E10. . ();//C T E11. 12.

    I , :

    1. A2. A() // 3. () S . . ("H ");4. 5. S6. (S )7. A = A();//C T E8. 9.

    .

    2)

    I ' , . T

    I , . A A , .

    1. // A.2. ;3. A4. () S . . ("H ");5.

    1. // B.2. ;3. .*;4. B5. (S )6. A = A();//C T E

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    44/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    7. . ();//C T E8. 9.

    In the above example, the scope of class A and its method msg() is default so it cannot be accessed fthe package.

    3)

    The protected access modifier is accessible within package and outside the package but through inhonly.

    The protected access modifier can be applied on the data member, method and constructor. It can't bthe class.

    In this example, we have created the two packages pack and mypack. The A class of pack package can be accessed from outside the package. But msg method of this package is declared as protected,accessed from outside the class only through inheritance.

    1. // A.2. ;3. A4. () S . . ("H ");5.

    1. // B.2. ;3. .*;4. 5. B A6. (S )7. B = B();8. . ();9. 10.

    Output:Hello

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    45/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    4)

    T . I .

    1. // A.2. 3. ;4. A5. () S . . ("H ");6.

    1. // B.2. 3. ;4. .*;

    5. 6. B7. (S )8. A = A();9. . ();10. 11.

    Output:Hello

    Let's understand the access modifiers by a simple table.

    N N N

    N N

    N

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    46/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    If you are overriding any method, overridden method (i.e. declared in subclass) must not be more re

    1. A2. () S . . ("H ");3. 4. 5. S A6. () S . . ("H "); //C.T.E7. (S )8. S = S ();9. . ();10. 11.

    T . T .

    Qst.5 (a) What is abstract class? Explain need of abstract class with the help of an example. when we extending an existing class, we have a

    choice whether to redefine the methods of the superclass. Basically a superclass hascommon features that are shared by subclasses. In some cases you will find thatsuperclass cannot have any instance (object) and such of classes are calledabstractclasses . Abstract classes usually containabstract methods. Abstract method is amethod signature (declaration) without implementation. Basically these abstractmethods provide a common interface to different derived classes. Abstract classes aregenerally used to provide common interface derived classes. You know a superclassis more general than its subclass(es). The superclass contains elements and propertiescommon to all of the subclasses. Often, the superclass will be set up as anabstract

    class, which does not allow objects of its prototype to be created. In this case onlyobjects of the subclass are created. To do this the reserved wordabstract is included(prefixed) in the class definition.For example, the class given below is an abstract class.public abstract class Player // class is abstract{private String name;public Player(String vname){name=vname;}public String getName() // regular method{return (name);}public abstract void Play(); // abstract method: no implementation}Subclassesmust provide the method implementation for their particular meaning. If

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    47/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    the method statements is one provided by the superclass, it would require overridingin each subclass. In case you forget to override, the applied method statements may beinappropriate. Now can you think what to do if you have to force that derived classes must redefinethe methods of superclass?The answer is very simple Make those methods abstract.In case attempts are made to create objects of abstract classes, the compiler doesntallow and generates an error message. If you are inheriting in a new class from anabstract class and you want to create objects of this new class, you must providedefinitions to all the abstract methods in the superclass. If all the abstract methods ofsuper class are not defined in this new class this class also will become abstract.Is it possible to have an abstract class without abstract method? Yes, you can have.Can you think about the use of such abstract classes? These types of classes aredefined in case it doesnt make any sense to have any abstract methods, in the classand yet you want to prevent an instance of that class.Inheritance represent, isa relationship between a subclass and a superclass. In otherwords, you can say that every object of a subclass is also a superclass object withsome additional properties. Therefore, the possibility of using a subclass object inplace of a superclass object is always there. This concept is very helpful inimplementing polymorphism.

    Qst.5 (b) What is an exception? Explain haw an exception is handled in Java. Explain hierarchy of differentexception classes in java. Also explain why is it not necessary to handle runtime exception?

    An exceptional condition is considered as a problem, which stops program executionfrom continuation from the point of occurrence of it. Exception stops you fromcontinuing because of lack of information to deal with the exception condition. Inother words it is not known what to do in specific conditions.If the system does not provide it you would have to write your own routine to test forpossible errors. You need to write a special code to catch exceptions before theycause an error.If you attempt in a Java program to carry out an illegal operation, it does notnecessarily halt processing at that point. In most cases, theJVM sees for thepossibility ofcatching the problem and recovering from it.If the problems are such which can be caught and recovery can be provided, then wesay the problems arenot fatal , and for this the termexception is used rather thanerror .

    Exception arises at runtime due to some abnormal condition in program for examplewhen a method. For division encounters an abnormal condition that it can't handleitself, i.e. divide by zero, then this method maythrow an exception.Exceptionis anabnormalconditionIf a program written in Java does not follow the rule of Java language or violates the

    Java execution environment, constraints exception may occur. There may be amanually generated exception to pass on some error reports to some calling certainmethods.If an exception is caught, there are several things that can be done:i. Fix the problem and try again.ii. Do something else instead to avoid the problem.iii. Exit the application with System.exit()

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    48/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    iv. Rethrow the exception to some other method or portion of code.v. Throw a new exception to replace it.vi. Return a default value (a non-void method: traditional way of handlingexceptions).vii. Eat the exception and return from the method (in a void method). In otherwords dont give importance to the exception .viii. Eat the exception and continue in the same method (Rare and dangerous. Bevery careful if you do this).You should give due care to exceptions in program. Programmers new toprogramming almost always try to ignore exceptions. Do not simply avoid dealingwith the exceptions. Generally you should only do this if you can logically guaranteethat the exception will never be thrown or if the statements inside exception checkingblock do not need to be executed correctly in order for the following programstatements to run).

    HANDLING OF EXCEPTIONExceptions in Java are handled by the use of these five keywords: try, catch, throw,throws, and finally . You have to put those statements of program on which you wantto monitor for exceptions, intry block. If any exceptions occur that will be catchedusing catch. Java runtime system automatically throws system-generated exceptions.

    Using try catchNow let us see how to write programs in Java, which take care of exceptionshandling.See the program given below: //programpublic class Excep_Test The throw keyword is used to throw exceptions manually.

    {public static void main(String[] args){int data[] = {2,3,4,5};System.out.println("Value at : " + data[4]);}}Output: java.lang.ArrayIndexOutOfBoundsExceptionat Excep_Test.main(Excep_Test.java:6)Exception in thread "main"

    To catch an exception in Java, you write a try block with one or more catch clauses.Each catch clause specifies one exception type that it is prepared to handle. Thetryblock places a fence around the code that is under the watchful eye of the associated

    catchers. If the bit of code delimited by thetry blockthrows an exception, theassociatedcatch clauses will be examined by the Java virtual machine. If the virtualmachine finds acatch clause that is prepared to handle the thrown exception, theprogram continues execution starting with the first statement of thatcatch clause, andthe catch block is used for executing code to handle exception and gracefultermination of the program.public class Excep_Test

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    49/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    {public static void main(String[] args){try{int data[] = {2,3,4,5};System.out.println("Value at : " + data[4]);}catch( ArrayIndexOutOfBoundsException e){System.out.println("Sorry you are trying to print beyond the size of data[]");}}}Output:Sorry you are trying to print beyond the size of data[]

    Catching Multiple ExceptionsSometimes there may be a chance to have multiple exceptions in a program. You can

    use multiple catch clauses to catch the different kinds of exceptions that code canthrow. If more than one exception is raised by a block of code, then to handle theseexceptions more than one catch clauses are used. When an exception is thrown,different catch blocks associated with try block inspect in order and the first onewhose type (the exception type passed as argument in catch clause) matches with theexception type is executed This code snippet will give you an idea how to catchmultiple exceptions. //code snippet

    try{ // some code}

    catch (NumberFormatException e){ //Code to handle NumberFormatException}catch (IOException e){ // Code to handle IOException}catch (Exception e){ // Code to handle exceptions than NumberFormatException and IOException}finally // optional{ //Code in this block always executed even if no exceptions}Now let us see the program given below : //programpublic class MultiCatch

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    50/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    {public static void main(String[] args){int repeat ;try{repeat = Integer.parseInt(args[0]);}catch (ArrayIndexOutOfBoundsException e){ // pick a default value for repeatrepeat = 1;}catch (NumberFormatException e){ // print an error messageSystem.err.println("Usage: repeat as count" );System.err.println("where repeat is the number of times to say Hello Java" );System.err.println("and given as an integer like 2 or 5" );

    return;}for (int i = 0; i < repeat; i++){System.out.println("Hello");}}}Output:

    Hello

    Using Finally Clause:

    A finally clause is included in a program in the last after all the possible code to beexecuted. Basically finally block should be the last block of execution in the program. //programpublic class Finally_Test{public static void main(String[] args){try{System.out.println("Hello " + args[0]);}catch (ArrayIndexOutOfBoundsException e){System.out.println("Hello, You are here after ArrayIndexOutOfBoundsException");}finally{System.out.println("Finally you have to reach here");

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    51/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    }}}Output:Hello, You are here after ArrayIndexOutOfBoundsExceptionFinally you have to reach here

    TYPES OF EXCEPTIONSExceptions in Java are of two kinds,checked andunchecked . Checked exceptionsare so called because both the Java compiler and theJVM check to make sure thatthe rules of Java are obeyed. Problems causes to checked exceptions are:Environmental error that cannot necessarily be detected by testing; e.g, disk full,broken socket, database unavailable, etc. Checked exceptions must be handled atcompile time. Only checked exceptions need appear in throws clauses. Problems suchas Class not found, out of memory, no such method, illegal access to private field,etc, comes under virtual machine error.

    Unchecked exceptionsBasically, an unchecked exception is a type of exception for that you option thathandle it, or ignore it. If you elect to ignore the possibility of an uncheckedexception, then, as a result of that your program will terminate. If you elect to handlean unchecked exception that occur then the result will depend on the code that youhave written to handle the exception. Exceptions instantiated fromRuntimeException and its subclasses are considered asunchecked exceptions.Checked exceptions

    Checked exceptions are those that cannot be ignored when you write the code in yourmethods. According to Flanagan, the exception classes in this category representroutine abnormal conditions that should be anticipated and caught to prevent programtermination.All exceptions instantiated from theException class, or from subclasses, ofException other thanRuntimeException and its subclasses, must either be:(i) Handled with atry block followed by acatch block, or(ii) Declared in athrows clause of any method that can throw themThe conceptual difference between checked and unchecked exceptions is thatchecked exceptions signalabnormal conditions that you have to deal with. Whenyou place an exception in a throws clause, itforces to invoke your method to dealwith the exception, either by catching it or by declaring it in theirown throws clause.If you don't deal with the exception in one of these two ways, your class will notCompile

    Throwable class HierarchyAll exceptions that occur in Java programs are a subclass of builtin classThrowable . Throwable class is top of the exception class hierarchy. Two classesException andError are subclass of Throwable class. Exception class is used tohandle exceptional conditions. Error class defines those exceptions which are notexpected by the programmer to handle.Exception class and its Subclasses in Throwable class Hierarchyclass java.lang.Object|+ class java.lang.Throwable

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    52/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    |+ class java.lang.Exception|+ class java.awt.AWTException|+class java.lang.ClassNotFoundException|+ class java.lang.CloneNotSupportedException|+ class java.io.IOException|+ class java.lang.IllegalAccessException|+ class java.lang.InstantiationException|+ class java.lang.InterruptedException|+ class java.lang.NoSuchMethodException|

    + class java.lang.NoSuchMethodException|+ class java.lang.RuntimeException|+ class java.lang.ArithmeticException|+ class java.lang.ArrayStoreException|+ class java.lang.ClassCastException|+ class java.util.EmptyStackException

    + class java.lang.IllegalArgumentException

    |+ class java.lang.ErrorFigure 1: Throwable Class Partial Hierarchy

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    53/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.5 (c) Write a java program to create two threads with different priority. Ans:

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    54/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    55/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    Qst.6 (a) What is I/O stream in java? Write a program in java to create a file and copy the content of analready existing file into it.

    / Input Stream and Output Stream hierarchyThere are two different types of Streams found in Java.io package as shown inFigure 1a OutputStream and InputStream. Figure 1b shows the further classificationof Inputstream.

    The following classes are derived from InputStream Class.InputStream: Basic input stream.StringBufferInputStream: An input stream whose source is a string.ByteArrayInputStream: An input stream whose source is a byte array.FileInputStream: An input stream used for basic file input.FilterInputStream: An abstract input stream used to add new behaviour to existinginput stream classes.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    56/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    PipedInputStream: An input stream used for inter-thread communication.Exploring Java I/OSequenceInputStream: An input stream that combines two other input streams.BufferedInputStream: A basic buffered input stream.PushbackInputStream: An input stream that allows a byte to be pushed back ontothe stream after the byte is read.LineNumberInputStream: An input stream that supports line numbers.ataInputStream: An input stream for reading primitive data types.RandomAccessFile: A class that encapsulates a random access disk file.Output streams are the logical counterparts to input streams and handle writing data tooutput sources.In Figure2 the hierarchy of output Stream is given. The followingclasses are derived from outputstream.

  • 7/25/2019 MCS-024 Solved Assignment 2015-16

    57/85

    MCS-024

    For More Solutions Contact To Mr. Bilal Ali : Brain Cafe Computer Classes, Near U.P.Tech. Chowk Lucknow. Contact Number:+91 9984736691,+91 9450148850

    E_Mail_Id- [email protected] , FB Page- facebook.com/bilalali0786

    OutputStream: The basic output stream.ByteArrayOutputStream: An output stream whose destination is a byte array.FileOutputStream: Output stream used for basic file output.PipedOutputStream: An output stream used for inter-thread communication.BufferedOutputStream: A basic buffered output stream.PrintStream: An output stream for displaying text.DataOutputStream: An output stream for writing primitive data types.FilterOutputStream: An abstract output stream used to add new behaviour to existingoutput stream classes.Layering byte Stream FilterSome-times you will need to combine the two input streams. in Java. It is known asfiltered streams ( i.e., feeding an existing stream to the constructor of anotherstream) . You should continue layering stream constructor until you have access to thefunctionality you want.FileInputStream and FileOutputStream give you input and outp