121
http://www.ignousolvedassignments.com For More Ignou Solved Assignments Please Visit - www.ignousolvedassignments.com Connect on Facebook : http://www.facebook.com/pages/IgnouSolvedAssignmentscom/346544145433550 Subscribe and Get Solved Assignments Direct to your Inbox : http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com Request Any Solved Assignment at : http://ignousolvedassignments.com/request-and-share-solved-assignments/ Course Code Course Title Assignment Number Assignment Marks Maximum Marks Last Date of Submission : MCS-024 : Object Oriented Technologies and Java Programming : MCA (2)/024/Assign/11 : 100 : 25% : 15th October, 2012 (For July 2012 Session) 15th April, 2013 (For January 2013 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. 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.

IGNOU MCS-024 Solved Assignment 2012-13

Embed Size (px)

DESCRIPTION

solved paper

Citation preview

Page 1: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

For More Ignou Solved Assignments Please Visit -

www.ignousolvedassignments.com

Connect on Facebook :

http://www.facebook.com/pages/IgnouSolvedAssignmentscom/346544145433550

Subscribe and Get Solved Assignments Direct to your Inbox :

http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com

Request Any Solved Assignment at :

http://ignousolvedassignments.com/request-and-share-solved-assignments/

Course Code

Course Title Assignment Number Assignment Marks Maximum Marks Last Date of Submission

: MCS-024 : Object Oriented Technologies and Java Programming : MCA (2)/024/Assign/11 : 100 : 25% : 15th October, 2012 (For July 2012 Session)

15th April, 2013 (For January 2013 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. 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.

Page 2: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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.

Page 3: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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.

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. Let's 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 treated as 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 other's data or functions. It is sufficient to know the type of message

accepted and the type of response returned by the 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. Let's see in the Figure 4, how objects interact by sending

messages to one another.

Page 4: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 5: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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

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 doesn't create an object just as the existence of a built-in

type integer doesn't 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 and hiding how that task is performed. A step further, in the Object Oriented approach, classes use the concept of data 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

Page 6: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 7: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

hardware or software is hidden from the programmer. Similarly in Object Oriented approach, classes act as abstract 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 of objects 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,

each derived class has added its own features according to the requirement. Therefore, new classes use the concept of reusability and extend their functionality.

Polymorphism Polymorphism 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 OOPS OOP 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 problem domain

to those objects in the program, the work can be easily partitioned based on

Page 8: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 code

and 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 to

build secure programs that cannot be accessed by code in other parts of the

program. • Allows designing simpler interfaces: Message passing techniques between

objects allows making simpler interface descriptions with external systems.

b) What is polymorphism? Explain the advantages of polymorphism with an example.

Solution :

Polymorphism is the capability of a method to do different things based on the object through which it is invoked or object it is acting upon. For example method find _area will work definitely for Circle object and Triangle object In Java, the type of actual object always determines method calls; object

reference type doesn't 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 is

important 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() {

Page 9: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 10: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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(); } } 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 don't 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.

Page 11: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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:

Page 12: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 13: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

• Provide similarities among unrelated classes without artificially forcing a class relationship.

• 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 can't 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 can't 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. Let's consider a real-world parallel that I can use to better demonstrate this idea, that of home audio/visual equipment and a remote control. I'm grateful to John 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 buttons—power 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 them—sort 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 the

TV, VCR, DVD, and so on by classes, each of which will make use of the same remote control

interface—the set of buttons if you like—but 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. Let's 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 number int 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 abstract—by 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, here's the TV:

Page 14: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

import static java.lang.Math.max;

Page 15: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 16: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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<=MAX_CHANNEL) channel = newChannel; System.out.println(make + " "+ screensize + " inch TV tuned to channel: "

Page 17: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

+ channel);

Page 18: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 19: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 = channel<MAX_CHANNEL ? ++channel : MIN_CHANNEL; System.out.println(make + " "+ screensize + " inch TV tuned to channel: " + channel); return channel; } public int channelDown() { if(!power) { // If the power is off return 0; // Nothing works } // Wrap channel down to MAX_CHANNEL when MIN_CHANNEL is reached channel = channel>MIN_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 you'll 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

Page 20: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

return 0; // Nothing works

Page 21: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 22: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

} // 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<=MAX_CHANNEL) { channel = newChannel; } System.out.println(make + " VCR tuned to channel: "+ channel); return channel; } public int channelUp() { if(!power) { // If the power is off return 0; // Nothing works } // Wrap channel round to MIN_CHANNEL when MAX_CHANNEL is reached channel = channel<MAX_CHANNEL ? ++channel : MIN_CHANNEL; System.out.println(make + " VCR tuned to channel: "+ channel); return channel; } public int channelDown() { if(!power) { // If the power is off return 0; // Nothing works } // Wrap channel round to MAX_CHANNEL when MIN_CHANNEL is reached channel = channel>MIN_CHANNEL ? --channel : MAX_CHANNEL; System.out.println(make + " VCR tuned to channel: "+ channel); return channel; } private String make = null;

Page 23: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

private boolean power = false;

Page 24: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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. Here's 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<5 ; i++) { // Now create either a TV or a VCR at random if(random()<0.5) // Random choice of TV make and screen size remote = new TV(random()<0.5 ? "Sony" : "Hitachi", random()<0.5 ? 32 : 28); else // Random choice of VCR remote = new VCR(random()<0.5 ? "Panasonic": "JVC"); // Now operate it, whatever it is remote.powerOnOff(); // Switch it on remote.channelUp(); // Set the next channel up remote.volumeUp(10); // Turn up the sound }}}

Page 25: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Question 2:

Solution :

a) What is platform independence? Explain why java is secure and

platform independent.

Platform Independent 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 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 of hardware architecture dependent constructs. For example, Integers are always four bytes long and floating-point variables follow the IEEE 754.You don't 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 Concepts When 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. That's 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

Page 26: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 27: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

any machine with suitable Java interpreter of that machine.

Page 28: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 29: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 Java's portability because compiled Java programs run on the JVM, independent of whatever hardware is used.

b) Write a program in java to generate Fibonnaci Series. Solution

Input - 8 Output - 1 1 2 3 5 8 13 21 */

class Fibonacci{

public static void main(String a rgs[]){ int num = Integer.parseInt(args[0]); //taking no. as command line

argument.

System.out.println("*****Fibonacci Series*****"); int f1, f2=0, f3=1; for (int i=1;i<=num;i++){

System.out.print(" "+f3+" ");

f1 = f2; f2 = f3; f3 = f1 + f2;

} }

}

Page 30: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 31: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

c) Explain the advantage of 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) Explain the significance of PATH and CLASS PATH. Solution : Java is an OOP language. In java programming language for compiling the program we use the compiler that converts the source code into the byte code after that, that byte code is interpreted by JVM that converts the bytecode into the machine independent code. In java how the Java compiler and the JVM use the class search path to locate classes when they are referenced by other Java code. Searching class path is important for all Java developers.Many development tools have their own ways of manipulating the class path, which vary from product to product.For doing this we will use only simple command-line tools to carry out the compile operations. No difference, between the way that the Java compiler searches for classes, and the way that the JVM does it at run time. The compiler has the ability to compile classes from source code, where the JVM does not. We will use the compiler, but similar issues apply at run time.

Searching of multiple class directories

javac(compiler)search the files in only one directory at a time.

But, class search path will contain numerous directories and JAR archives. The -classpath

option to javac and java allows multiple entries to be specified, but the syntax is different

for Unix and Windows systems.

For Unix like this

javac -classpath dir1:dir2:dir3 ...

For Windows like this

javac -classpath dir1;dir2;dir3 ...

The difference is that Windows uses the colon (:) character as part of a filename, so it can't be used

as a filename separator. Naturally the directory separator character is different as well: forward

slash (/) for Unix and backslash (\) for Windows.

( I ). For running a simple program we need to set the java path on command prompt(for

temporary )& in Environment variable using PATH variable & CLASSPATH variable : PATH variable

In JDK the PATH variable contains directories where binary files (e.g. EXE files in Windows)

will be looked for.We set the PATH variables like this i.e path C:\Java\jdk1.6.0_03\bin

(i)on command prompt

C:\>set path=%path;C:\Java\jdk1.6.0_03\bin%

Page 32: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

When you open a command prompt and type "javac", you're supposed to have the "bin" directory

of your sdk into the PATH, otherwise you'll get an infamous "Command not found" error message.

20

Page 33: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

CLASSPATH

In JDK the CLASSPATH contains directories (or JAR files), from where your java

compiler/runtime will look for .class files (and some others). For example, "java Hello.class" will

not work unless you set the directory (or JAR file) Hello.class is in, into your CLASSPATH.

i.e.classpath C:\Java\jdk1.6.0_03\lib

For setting CLASSPATH using command prompt

Java class path can be set using either the -classpath option when calling an SDK tool (the

preferred method) or by setting the CLASSPATH environment variable. The -classpath option is

preferred because you can set it individually for each application without affecting other

applications and without other applications modifying its value. (ii)on command prompt

C:\>set classpath=%classpath;C:\Java\jdk1.6.0_03\lib%

JARs on the classpath

Java compiler and run-time can search for classes not only in separate files, but also in `JAR'

archives. A JAR file can maintain its own directory structure, and Java follows exactly the same

rules as for searching in ordinary directories. Specifically, `directory name = package name'.

Because a JAR is itself a directory, to include a JAR file in the class search path, the path must

reference the JAR itself, not the directory that contains the JAR. This is a very common error. Suppose I have a JAR jarclasses.jar in directory /jarclasses. The Java compiler look for classes in

this jar, we need to specify:

javac -classpath /jarclasses/jarclasses.jar ... and

not merely the directory jarclasses.

For the CLASSPATH use CLASSPATH Environment Variable

In java programming language we use the following packages such as java.io.*; java.

util.*;These packages are just a set of classes, you will want to store them in one place, separate

from the directory where you are developing your program. Sometimes these libraries have a set of

files stored in a single jar file ( with a .jar extension). From where the Java compiler and run

programs must be able to find any of these. This is done for command line use of Java and for

some editors and IDEs by setting an environment variable called CLASSPATH. For Windows,

the CLASSPATH environment variable should look like this :

c:\MyJavaLib;c:\MyJavaLib\myutils.jar;c:\MyJavaLib\blackboxclasses.jar;.

At the end " . " includes the current directory in the search for classes.

Suppose we have a directory MyJavaLib on the C-drive that contains some utility classes or the directories that correspond to some packages. This is the part before the first semi-

colon.

Second part indicates that we have some classes stored in a file myutils.jar

Third part indicates that we have a jar file blackboxclasses.jar.

Page 34: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

21

Page 35: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Finally, after the last semi-colon we have the period( . ), indicating that the current directory is on the CLASSPATH. If some things are stored in directories that are subdirectories, the complete

path, starting with "c:\" should be in the CLASSPATH.

(2) For setting CLASSPATH & PATH variable in environment variable by using the

following steps:

(i) right click on my computer icon on desktop

(ii) click on properties (iii)

click on advanced

(iv) click on Environment variables

Page 36: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Page 37: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.c

om

(v) system varables click on new

Page 38: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.c

om

23

Page 39: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

(vi) in ( variable name) write ----- path

in ( variable value) paste the path till bin directory i.e.------- c:\java\jdk1.6.0_03\bin click on ok

Page 40: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

24

Page 41: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

(vii) in system varables again click on new

Page 42: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

25

Page 43: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

(viii) in ( variable name) write ----- classpath

in ( variable value) paste the path till lib directory i.e.------- c:\java\jdk1.6.0_03\lib click on ok

(ix) after finished click on ok

Page 44: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

26

Page 45: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedas

signments.com

(x) finished click on ok

Page 46: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedas

signments.com

27

Page 47: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

How to set System Classpath :

Java class path is set for including the various files during program execution & compilation.After

setting class search path on the javac command line, we set `system' class path. This class path

will be used by both the Java compiler and the JVM . In both Unix and Windows systems, this is

done by setting an environment variable. For example, in Linux with the bash shell:

CLASSPATH=/jarclasses/jarclasses.jar;export CLASSPATH

for Windows:

set CLASSPATH=c:\jarclasses\jarclasses.jar

We use this procedure for setting short-term changes to the system CLASSPATH, but if you want

these changes to be persistent you will need to arrange this yourself.For different - 2 system this

path is different . On a Linux system, we put the commands in the file .bashrc in my home

directory. On Windows 2000/NT there is a `Control Panel' page for this.

Setting the system CLASSPATH is a useful procedure if you have JARs full of classes that you

use all the time.

Page 48: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

28

Page 49: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Question 3: a) What is an exception? Create an exception subclass named MyException to

handle user generate exceptions in Java.

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 rule—by definition! An exception doesn't always indicate an error though—it 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 is executed 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 that's 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 is said to be thrown—that 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 Exceptions An 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. It's also true for exceptions that are thrown by methods in one or another of the standard packages. Two direct subclasses of the class Throwable—the class Error and the class Exception—cover all the

Page 50: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

29

Page 51: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 Exceptions The exceptions that are defined by the Error class and its subclasses are characterized by the fact that they all represent conditions that you aren't expected to do anything about, so you aren't expected to catch them. Error has three direct subclasses—ThreadDeath, LinkageError, and VirtualMachineError:

❑ The first of these sounds the most serious, but in fact it isn't. 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 example—in 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, it's the thread that ends, not the program. I will deal with threads in detail in Chapter 16.

❑ 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 aren't prohibited from trying to deal with these exceptions, but in general, there's little point in attempting to

catch 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 Exceptions For 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 method in 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 don't, your program will not compile. You'll see in a moment how to handle exceptions and how to specify that a method can throw an exception.

Page 52: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

30

Page 53: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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. Let's 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:

Page 54: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

31

Page 55: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

In the normal course of events you shouldn't 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 precisely—ArrayIndexOutOfBoundsException 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 integers—that 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 integer—if it contains invalid characters, for example. In this case a special

Page 56: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

32

Page 57: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

return value cannot be used, so throwing an exception is a very convenient way to signal that the argument is invalid. Defining an Exception Class Your 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 {

// Constructors public 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 be

appended to the name of the class to form the message stored in the exception object. Of course, you can add other constructors. In general, you'll want to do so, particularly when you're

rethrowing your own exception after a standard exception has been thrown. In addition, you'll

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 Exception As 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 point—unless 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.");

Page 58: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

33

Page 59: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

You're 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 }

}

Page 60: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

34

Page 61: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

b) What is abstract class? What are advantages of using abstract class? Write a program in

Java to explain abstract class and multilevel inheritance..

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 doesn't matter whether you prefix the

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 don't have to define all the abstract methods in the

subclass. In this case the subclass will also be abstract and you won't 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;

35

Page 62: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

} 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(); } }

Page 63: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

36

Page 64: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Output: Play Cricket:Sachin Play Hockey:Dhanaraj Play Football:Bhutia

Question 4: Differentiate the following and support with example:

Final and static member Inheritance and Aggregation

Abstract class and Interface String and String Buffer

(I) Final and static member

Solution

1.Static variables (also called class variables) only exist in the class they are defined in. They are

not instantiated when an instance of the class is created. In other words, the values of these

variables are not a part of the state of any object. When the class is loaded, static variables are

initialized to their default values if no explicit initialization expression is specified Final

variable:values of final variables cannot be changed.

2.Static methods are also known as class methods. A static method in a class can directly access

other static members in the class. It cannot access instance (i.e., non-static) members of the class,

as there is no notion of an object associated with a static method. However, note that a static

method in a class can always use a reference of the class's type to access its members, regardless

of whether these members are static or not.

3. Final methods:cannot be overriden.

Final Member

static final variables are not the same with final(non-static) variables! Final(non-static) variables

can differ from object to object!!! But that's only if the initialization is made within the

constructor! (If it is not initialized from the constructor then it is only a waste of memory as it

creates final variables for every object that is created that cannot be altered.)

For example:

class A {

final int f ; static final int sf = 5; A (int num ) {

this .f = num ; } void show () {

System .out .printf ("About Object: %s \n Final: %d \n Sta tic Final: %d \n\n" , this .toString (), this .f, sf );

}

Page 65: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

public static void main (String [] args ) {

A ob1 = new A (14 ); ob1 .show ();

37

Page 66: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

A ob2 = new A (21 ); ob2 .show ();

} }

Static member

a static variable, also referred to as a class variable, is a variable which exists across instances of a

class.

I found an example of this here:

public class StaticVariable {

static int noOfInstances ; Stat icVariable () {

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

StaticVariable sv1 = new StaticVariable (); System .out .println ("No. of instances for sv1 : " + sv1 .noOfInstances ); StaticVariable sv2 = new StaticVariable ();

System .out .println ("No. of instances for sv1 : "

System .out .println ("No. of instances for st2 : " StaticVariable sv3 = new StaticVariable (); System .out .println ("No. of instances for sv1 : "

System .out .println ("No. of instances for sv2 : "

System .out .println ("No. of instances for sv3 : "

+ sv1 .noOfInstances ); +

sv2 .noOfInstances ); + sv1 .noOfInstances ); +

sv2 .noOfInstances ); +

sv3 .noOfInstances );

} }

Output of the program is given below:

As we can see in this example each object has its own copy of class variable.

C:\java >java StaticVariable No . of instances for sv1 : 1 No . of

instances for sv1 : 2 No . of

instances for st2 : 2 No . of

instances for sv1 : 3 No . of

instances for sv2 : 3 No . of

instances for sv3 : 3 (ii) Inheritance and Aggregation

There are two schools of thought on how to best extend, enhance, and reuse code in an object-

oriented system:

1. Inheritance: extend the functionality of a class by creating a subclass. Override superclass

members in the subclasses to provide new functionality. Make methods abstract/virtual to

force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but

is agnostic about its implementation.

Page 67: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

38

Page 68: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

2. Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other

code.

It's not a matter of which is the best, but of when to use what.

In the 'normal' cases a simple question is enough to find out if we need inheritance or aggregation.

If The new class is more or less as the original class. Use inheritance. The new class is now a subclass of the original class.

If the new class must have the original class. Use aggregation. The new class has now the original class as a member.

However, there is a big gray area. So we need several other tricks.

If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we

have a big nasty smell that indicates that we had to use aggregation.

If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.

To cut it short. We should use aggregation if part of the interface is not used or has to be changed

to avoid an illogical situation. We only need to use inheritance, if we need almost all of the

functionality without major changes. And when in doubt, use Aggregation.

An other possibility for, the case that we have an class that needs part of the functionality of the

original class, is to split the original class in a root class and a sub class. And let the new class

inherit from the root class. But you should take care with this, not to create an illogical separation.

Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark', 'Play'.

class Dog Eat; Walk;

Bark;

Play; end;

We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try to extend it from a

Dog.

class Cat is Dog Purr;

end;

Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a barking cat

violates the principles of the universe. So we need to override the Bark method so that it does

nothing.

class Cat is Dog Purr; Bark = null;

end;

Ok, this works, but it smells bad. So lets try an aggregation:

class Cat has Dog; Eat = Dog.Eat;

Page 69: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

39

Page 70: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Walk = Dog.Walk; Play = Dog.Play; Purr;

end;

Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an internal dog that

wants out. So lets try solution number three:

class Pet Eat; Walk;

Play; end; class Dog is Pet

Bark; end; class Cat is Pet

Purr; end;

This is much cleaner. No internal dogs. And cats and dogs are at the same level. We can even

introduce other pets to extend the model. Unless it is a fish, or something that does not walk. In

that case we again need to refactor. But that is something for an other time.

(iii) Abstract class and Interface

down vote accepted

Interface

An interface is a contract: the guy writing the interface say "hey, I accept things looking that way",

and the guy using the interface says "OK, the class I write looks that way".

An interface is an empty shell, there are only the signatures (name / params / return type) of the

methods. The methods do not contain anything. The interface can't do anything. It's just a pattern.

E.G (pseudo code):

// I say all motor vehicles should look like that : int erface MotorVehicle {

void run(); int getFuel();

} // my team mate complies and write vehicle looking that way class Car implements MotoVehicle {

int fuel; void run() {

print("Wrroooooooom"); } int getFuel()

Page 71: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

40

Page 72: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

{ return this.fuel;

} }

Implementing an interface consume very little CPU, because it's not a class, just a bunch of names,

and therefor there is no expensive lookup to do. It's great when it matters such as in embedded

devices.

Abstract classes

Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a

lookup to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more : you can define a

behavior for them. It's more about a guy saying "these classes should look like that, and they got

that in common, so fill in the blanks !".

e.g:

// I say all motor vehicles should look like that : abstract class MotorVehicle {

int fuel; // they ALL have fuel, so wh y let others implement that ? // let's make it for everybody int getFuel() {

return this.fuel; } // that can be very different, force them to provide their // implementation abstract void run();

} // my team mate co mplies and write vehicle looking that way class Car extends MotorVehicule {

void run() {

print("Wrroooooooom"); }

}

Implementation

While abstract classes and interface are supposed to be different concepts, the implementation

make that statement sometimes untrue. Sometime, there are not even what you think it is.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method

declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is

actually using metaclasses, and therefor classes. And interfaces are more related to duck typing in

Page 73: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

41

Page 74: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

this langage and it's a mix between conventions and special methods call descriptors (the

__method__ methods). (iv) String and String Buffer

A String is immutable, i.e. when it's created, it can never change. A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little

Strings along the way.

The maximum length for both is Integer.MAX_VALUE, because they are stored internally as

arrays, and Java arrays only have an int for their length pseudo-field.

The performance improvement between Strings and StringBuffers for multiple concatenation is

quite significant. If you run the following test code, you will see the difference. On my ancient

laptop with Java 6, I get these results:

Concat with String took: 1781ms Concat with StringBuffer took: 0ms public class Concat {

public static String concatWithString () {

String t = "Cat" ; for (int i =0; i <10000 ; i ++) {

t = t + "Dog" ; } return t ;

} public static String concatWithStringBuffer () {

StringBuffer sb = new StringBuffer ("Cat" ); for (int i =0; i <10000 ; i ++) {

sb .append ("Dog" ); } return sb .toString ();

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

long start = System .currentTimeMill is (); concatWithString (); System .out .println ("Concat with String took: " +

(System .currentTimeMillis () - start ) + "ms" ); start = System .currentTimeMillis (); concatWithStringBuffer (); System .out .println ("Concat with S tringBuffer took: " +

(System .currentTimeMillis () - start ) + "ms" ); }

}

Page 75: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

42

Page 76: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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

append content at the end of an already existing file.

Solution:

Java input and output is based on the use of streams, or sequences of bytes that travel from a source to a destination over a communication path. If a program is writing to a stream, you can consider it as stream' s source. If it is reading from a stream, it is the stream' s destination. The

communication path is dependent on the type of I/O being performed. It can consist of memory-to-memory transfers, a file system, a network, and other forms of I/O. Streams are powerful because they abstract away the details of the communication path from

input and output operations. This allows all I/O to be performed using a common set of

methods. These methods can be extended to provide higher-level custom I/O capabilities. Three streams given below are

automatically: • System.out - standard output stream • System.in - standard input stream

• System.err - standard error

created

An I nputStr eam represents a stream of data from which data can be read. Again, this stream will be either directly connected to a device or else to another stream. An OutputStr eam represents a stream to which data can be written. Typically, this stream will either be directly connected to a device, such as a file or a network connection, or to another output stream. Java.io package This package provides support for basic I/O operations. When you are dealing with the Java.io package 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?

Page 77: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

43

Page 78: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

For example:

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

and OutputStream 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 and character streams.

• Byt e str eams carry integers with values that range from 0 to 255. A diversified

data can be expressed in byte format, including numerical data, executable

programs, and byte codes - the class file that runs a Java program. • Char acter 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. The

methods for character streams generally accept parameters of data type char, while byte streams work with byte data types. The names of the methods in both sets of classes are

almost identical except for the suffix, that is, character-stream classes end with the suffix Reader or Writer and byte-stream classes end with the suffix InputStream and OutputStream.

For example, to read files using character streams use the Java.io.FileReader class, and for reading it using byte streams use Java.io.FileInputStream. Unless you are writing programs to work with binary data, such as image and sound files, use readers and 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

are limited to ISO-Latin-1 8-bit bytes). • They are easier to internationalize because they are not dependent upon a specific

character encoding. • They use buffering techniques internally and are therefore potentially much more

efficient than byte streams.

Byte Str eam Classes Java defines two maj or classes of byte streams: InputStream and OutputStream. To provide a variety of I/O capabilities subclasses are derived from these InputStream and OutputStream classes. InputStream class The InputStream class defines methods for reading bytes or arrays of bytes, marking locations in the stream, skipping bytes of input, finding out the number of bytes available for reading, and resetting the current position within the stream. An input stream is automatically opened when created. The close() method can explicitly close a stream. M ethods of I nputStr eam class • The basic method for getting data from any InputStream obj ect is the read() method. • public abstract int read() throws IOException: reads a single byte from the input stream

Page 79: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

44

Page 80: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

and returns it.

• public int read(byte[] bytes) throws IOException: fills an array with bytes read from the

stream and returns the number of bytes read.

• public int read(byte[] bytes, int offset, int length) throws IOException: fills an array

from stream starting at position offset, up to length bytes. It returns either the number of

bytes read or -1 for end of file.

• public int available() throws IOException: the readmethod always blocks when there is

no data available. To avoid blocking, program mi ght need to ask ahead of time exactly

how many bytes can 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 of skip()method) in a stream.

• public synchronized void mark (int readLimit): this method marks the current

position in the stream so it can backed up later.

OutputStream class The 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 the close() method. M ethods of OutputStr eam class • public abstract void write(int b) throws IOException: writes a single byte of data to an output

stream. • public void write(byte[] bytes) throws IOException: writes the entire contents of the bytes

array to the output stream. • public void write(byte[] bytes, int offset, int length) throws IOException: writes length number of

bytes starting at position offset from the bytes array.

The Java.io package contains several subclasses of InputStream and OutputStream that implement specific input or output functions. Some of these classes are: • FileInputStream and FileOutputStream: Read data from or write data to a file on the

native file system. • PipedInputStream and PipedOutputStream : Implement the input and output components

of a pipe. 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 must be connected to a PipedInputStream.

• ByteArrayInputStream and ByteArrayOutputStream : Read data from or write data to a byte array

in 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.

Page 81: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

45

Page 82: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

• StringBufferInputStream: Allow programs to read from a StringBuffer as if it were an

input stream.

A Program to Copy an already existing File to new File import java.io.*;

public class jCOPY {

public static void main(String args[]){

tr y { 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();

}

}

Page 83: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

46

Page 84: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

b) Explain the difference between checked and unchecked exceptions with example.

Solution:

As stated by their name, unchecked exceptions are not checked at compile-time which means that

the compiler doesn't require methods to catch or to specify (with a throws) them. Classes

belonging to this category are detailed in the section 11.2 Compile-Time Checking of Exceptions

of the JLS:

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the

class Error and its subclasses. All other exception classes are checked exception classes. The

Java API defines a number of exception classes, both checked and unchecked. Additional

exception classes, both checked and unchecked, may be declared by programmers. See §11.5 for a

description of the exception class hierarchy and some of the exception classes defined by the Java

API and Java virtual machine.

The following picture illustrates the Exception hierarchy:

The class Error and its subclasses are exceptions from which ordinary programs are not ordinarily

expected to recover and, as explained in 11.5 The Exception Hierarchy:

The class Error is a separate subclass of Throwable, distinct from Exception in the class

hierarchy, to allow programs to use the idiom:

} catch (Exception e ) {

to catch all exceptions from which recovery may be possible without catching errors from which

recovery is typically not possible.

To summarize, RuntimeException are a subset of unchecked exceptions for exceptions from

which recovery is possible (but unchecked exception is not a synonym of RuntimeException

Page 85: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

47

Page 86: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Question 6: a) What is multithreading? Explain the two ways of creating threads in Java

programs. Also explain difference between notify() and notify All( ) methods.

Solution: Multithreaded programs support more than one concurrent thread of execution. This means they are able to simultaneously execute multiple sequences of instructions. Each instruction sequence has its own unique flow of control that is independent of all others. These independently executed instruction sequences are known as threads. Your PC has only a single CPU; you mi ght ask how it can execute more than one thread at the same

time? In single processor systems, only a single thread of execution occurs at a given instant. But multiple

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 threads are

executing at the same time. You know that single-processor systems support logical concurrency only. 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 is achieved. The advantage of multithreaded programs is that they support logical concurrency. Many programming

languages support multiprogramming, as it is the logically concurrent execution of multiple 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 a concurrent manner, depending upon the multiprogramming features supported by the underlying operating system. Multithreading differs from multiprogramming. Multithreading provides concurrency within the content 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 occurs within a process.

Page 87: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

48

Page 88: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Advantages of M ultithr eading • Concurrency can be used within a process to implement multiple instances of simultaneous

services.

• Multithreading 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. Multithreaded web servers are able to efficiently handle multiple browser requests. They handle one request per processing thread.

• Multithreading enables programmers to write very efficient programs that make maxi mum use of the CPU. Unlike most other programming languages, Java provides built-in support for

multithreaded programming. The Java run-time system depends on threads for many things. Java uses threads to enable the entire environment to be synchronous.

Creating Threads in Java The multithreading system in Java is built upon the Thr ead Class, its methods and its companion interface, Runnable. To create a new thread, your program will either extend Thread Class or

implement the Runnable interface. The Thread Class defines several methods that help in managing threads. For example, if you have to create your own thread then you have to do one of the following things:

Page 89: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

49

Page 90: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

1) class MyThread extends Thread {

MyThread(arguments) // constructor {

} //initialization public void run() {

// perform operations }

}

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

2)

class MyThread implements Runnable {

MyThread(arguments) {

//initialization } public void run() {

// perform operation }

}

The Thr ead Class Constr uctor s The 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) Thr ead Class M ethod Some commonly used methods of Thread class are given below: • static Thread curr entThr ead() Returns a reference to the currently executing thread object. • String getName() Returns the name of the thread in which it is called • int getPr ior ity() Returns the Thread' s priority • void inter r upt() Used for Interrupting the thread. • static boolean inter r upted() 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

Page 91: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

50

Page 92: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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

execution) for the specified number of milliseconds. • void star t() 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 toStr ing() Returns a string representation of thread.String includes the thread' s 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 destr oy() Destroys the thread without any cleanup. Cr eating Thr eads Java provides native support for multithreading. This support is centered on the Java.lang.Thread class,

the Java.lang.Runnable interface and methods of the Java.lang.obj ect class. In Java, support for multithreaded programming is also provided through synchronized methods and statements. The thread class provides the capability to create thread obj ects, each with its own separate flow of control.

The thread class encapsulates the data and methods associated with separate threads of execution and enables multithreading to be integrated within Java' s obj ect oriented framework. The minimal multithreading support required of the Thread Class is specified by the j ava.lang.Runnable

interface. 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 already Java provides two approaches for creating threads. In the first approach, you create a subclass of the

Thread class and override the run( ) method to provide an entry point for the Thread' s 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 the Thread

class. It initializes the thread using the operating system' s multithreading capabilities, and invokes the run( ) method.

A program for creating threads by inheriting the Thread class. //program

class MyThreadDemo ext ends 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( )

Page 93: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

51

Page 94: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

{ t ry {

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( )) {

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

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

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

} }

while(isAlive1 || isAlive2); }

} Output: thread 1::Java thread 2::Java thread 1::is thread 2::is thread 1::very thread

2::very thread

1::good thread

2::good thread 1::Programming thread 2::Programming thread 1::Language thread 2::Language

Page 95: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

52

Page 96: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Thread 1 is dead Thread 2 is dead This output shows how two threads execute in sequence, displaying information on the console. The program 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 short

amount of time between each word. Because both threads share the console window, the program' s output identifies which thread wrote to the console during the program' s execution. notify(): this method should be called only when the current thread has already

acquired the lock on the object. If the wait set of the object is non-empty then a

thread from the set is arbitrarily chosen, removed and is re-enabled for thread scheduling. Of course, the thread will not be able to proceed unless the current thread releases the object's lock. notifyAll(): it's same as the notify() method. The only difference is that in

this case all the threads from the non-empty wait set of the object are removed and are re-enabled for thread scheduling in stead of only one thread from the wait set being picked arbitrarily, removed, and re-enabled for thread scheduling as is

the case in notify() method.

b) What is need of Layout Manager? Explain different layouts available in Java.

Solution:

A LayoutManager rearranges the components in the container based on their size relative to the size of the container. Consider the window that just popped up. It has got five buttons of varying sizes. Resize the window and watch how the buttons move. In particular try making it just wide enough so that all the buttons fit on one line. Then try making it narrow and tall so that there is only one button on line. See if you can

manage to cover up some of the buttons. Then uncover them. Note that whatever you try to do, the order of the buttons is maintained in a logical way. Button 1 is always before button 2, which is always before button 3 and so on. It is harder to show, but imagine if the components changed sizes, as they mi ght if you viewed this page in different browsers or

on different platforms withdifferent fonts. The layout manager handles all these different cases for you to the greatest extent possible. If you had used absolute positioning and the window were smaller than expected or the components larger than you expected, some components would likely be truncated or

completely hidden. In essence a layout manager defers decisions about positioning until runtime. When you add a component to an applet or a container, the container uses its layout manager to decide where to put the component. Different LayoutManager classes use different rules to place components. java.awt.LayoutManager is an interface. Five classes in the java packages implement it: • FlowLayout • BorderLayout • CardLayout • GridLayout • GridBagLayout

•plus javax.swing.BoxL ayout

Page 97: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

53

Page 98: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

FlowL ayout A FlowLayout arranges widgets from left to right until there's no more space left. Then it begins a row lower and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. This is the default LayoutManager for applets and panels. FlowLayout is the

default layout for java.awt.Panel of which j ava.applet.Applet is a subclasses. Therefore you don't need to do anything special to create a FlowLayout in an applet. However you do need to use the following constructors if you want to use a FlowLayout in a Window.LayoutManagers have constructors like any other class. The constructor for a FlowLayout is public FlowLayout(). Thus to create a new FlowLayout object you write FlowLayout fl; fl = new FlowLayout(); As usual this can be shortened to FlowLayout fl = new FlowLayout(); You tell an applet to use a particular LayoutManager instance by passing the obj ect to the applet's setLayout() method like this: this.setLayout(fl); Most of the time setLayout() is called in the init() method. You normally j ust create the

LayoutManager right inside the call to setLayout() like this this.setLayout(new FlowLayout());

For example the following applet uses a FlowLayout to position a series of buttons that mimic the buttons on a tape deck. import java.applet.* ; import java.awt.* ; public class FlowTest extends Applet { public void init() { this.setLayout(new FlowLayout()); this.add( new Button("Add")); this.add( new Button("Modify")); this.add( new Button("Delete")); this.add( new Button("Ok")); this.add( new Button("CANCEL")); } }

Output:

Border Layout

Page 99: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

54

Page 100: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

A BorderLayout organizes an applet into North, South, East, West and Center sections. North, South, East and West are the rectangular edges of the applet. They're continually resized to fit the sizes of the widgets included in them. Center is whatever is left over in the middle. A BorderLayout places objects in the North, South, East, West and center of an applet. You create a new BorderLayout obj ect much like a FlowLayout obj ect, in the init() method call to setLayout like this: this.setLayout(new BorderLayout()); There's no centering, left alignment, or right alignment in a BorderLayout. However, you can add

horizontal and vertical gaps between the areas. Here is how you would add a two pixel horizontal gap and a three pixel vertical gap to a BorderLayout:

this.setLayout(new BorderLayout(2, 3)); To add components to a BorderLayout include the name of the section you wish to add them to do like done in the program gi ven below. this.add("South", new Button("Start")); import j ava.applet.* ; import j ava.awt.* ; public class BorderLayouttest extends Applet

{ public void init() { this.setLayout(new BorderLayout(2, 3)); this.add("South", new Button("Start")); this.add("North", new Button("Stop")); this.add("East", new Button("Play")); this.add("West", new Button("Pause")); } }

Car d L ayout

Page 101: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

55

Page 102: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

A CardLayout breaks the applet into a deck of cards, each of which has its own Layout Manager. Only one card appears on the screen at a time. The user flips between cards, each of which shows a

different set of components. The common analogy is with HyperCard on the Mac and Tool book on Windows. In Java this might be used for a series of data input screens, where more input is needed than will comfortably fit on a single screen.

Gr id L ayout A GridLayout divides an applet into a specified number of rows and columns, which form a grid of cells, each equally sized and spaced. It is important to note that each is equally sized and spaced as there is another similar named Layout known as GridBagLayout .As Components are added to the layout they are placed in the cells, starting at the upper left hand corner and moving to the right and down the page. Each component is sized to fit into its cell. This tends to squeeze and stretch components unnecessarily. The GridLayout is great for arranging Panels. A GridLayout specifies the number of rows and columns into which components will be placed. The applet is broken up into a table of equal sized cells. GridLayout is useful when you want to place a number of similarly sized obj ects. It is great for putting together lists of checkboxes and radio buttons as you did in the Ingredients applet. GridLayout looks like Figure 3. Gr id Bag L ayout GridBagLayout is the most precise of the five AWT Layout Managers. It is similar to the GridLayout, but components do not need to be of the same size. Each component can occupy one or more cells of the layout. Furthermore, components are not necessarily placed in the cells beginning at the upper

left-hand corner and moving to the right and down. In si mple applets with just a few components you often need only one layout manager. In more complicated applets, however, you will often split your applet into panels, lay out the panels according to

a layout manager, and give each panel its own layout manager that arranges the components inside it. The GridBagLayout constructor is trivial, GridBagLayout() with no arguments.

GridBagLayout gbl = new GridBagLayout();

Page 103: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

56

Page 104: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Question 7: a) What is an Applet? Write an applet that prints "Lear Java it is useful" at the

current cursor position whenever the mouse left button is clicked.

Solution: Applet is a Java program that runs in the Appletviewer ( 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. Applet package which has several interfaces. These

interfaces 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 Do's and Don'ts of Java Applets:

Do's • 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.

Don'ts • Write data on any of the host's disks. • Read any data from the host's disks without the user's 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 was

downloaded.

• 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:

Page 105: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

57

Page 106: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

1. The browser reads the HTML page and finds any <APPLET> tags. 2. The browser parses the <APPLET> 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.Class

object. 5. The browser instantiates the Applet class to form an Applet object. This requires the Applet to

have a no-args constructor. 6. The browser calls the Applet's init () method. 7. The browser calls the Applet's 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 Applet's 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 Applet's stop () method.

11. The browser calls the Applet's 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: ");

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

Page 107: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

58

Page 108: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 <HTML> <BODY> <APPLET ALIGN="CENTER" CODE="Q6a.class" width = "700" height = "400"></APPLET> </BODY> </HTML>

Page 109: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

59

Page 110: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

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 establishing

and maintaining a Java program' s connection to a database. Java provides JDBC to connect to databases and work with it. Using standard library routines, you can open a connection to the database. Basically JDBC allows the integration of SQL calls into a general programming environment by providing library routines, which interface with the database. In

particular, Java' s JDBC has a rich collection of routines which makes such an interface extremely simple and intuitive.

Establishing A Connection The 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.

L oad the vendor specific dr iver This is very i mportant because you have to ensure portability and code reuse. The API should be designed as independent of the version or the vendor of a database as possible. Since different DBMS' s 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 following code snippet: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ")

M ake the connection Once the driver is loaded and ready for a connection to be made, you may create an instance of a Connection object using:

Connection con = DriverManager.getConnection(url, username, password); Let us see what are these parameters passed to get Connection method of DriverManager class. The

first string is the URL for the database including the protocol, the vendor, the driver, and the server the port number. The username and password are the name of the user of database and password is user password. The connection con returned in the last step is an open connection, which will be used to pass SQL

statements to the database.

Cr eating JDBC Statements A JDBC Statement object is used to send the SQL statements to the DBMS. It is entirely different from the SQL statement. A JDBC Statement obj ect is an open connection, and not any single SQL Statement. You can think of a JDBC Statement object as a channel sitting on a connection, and

passing 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, using our Connection obj ect con Statement statmnt = con.createStatement(); At this point, you will notice that a Statement obj ect exists, but it does not have any SQL statement to

pass on to the DBMS.

Page 111: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

47

Page 112: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

Cr eating JDBC Pr epar edStatement PreparedStatement object is more convenient and efficient for sending SQL statements to the DBMS. The main feature, which distinguishes PreparedStatement obj ect from objects of Statement class, is that it gives an SQL statement right when it is created. This SQL statement is then sent to the DBMS right 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 similar query with different parameters multiple times, the statement can be compiled and optimized by the DBMS j ust once. While with a normal Statement, each use of the same SQL statement requires a

compilation all over again. PreparedStatements are also created with a Connection method. The following code shows how to create a parameterized SQL statement with three input parameters: PreparedStatement prepareUpdatePrice = con.prepareStatement( "UPDATE Employee SET emp_address =? WHERE emp_code =" 1001" AND emp_name =?"); You can see two? symbol in the above PreparedStatement prepareUpdatePrice. This means that you have to provide values for two variables emp_address and emp_name in PreparedStatement before you

execute it. Calling one of the setXXX methods defined in the class PreparedStatement can provide values. Most often used methods are setInt, setFloat, setDouble, setString, etc. You can set these 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/I NSERT/UPDATE Statements of SQL Executing 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 well as statements to update the table contents, all are executed using the executeUpdate method. The following snippet has examples of executeUpdate statements.

Statement stmt = con.createStatement(); stmt.executeUpdate("CREATE TABLE Employee " + "(emp_name VARCHAR2(40), emp_address VARCHAR2(40), emp_sal REAL)" ); stmt.executeUpdate("INSERT INTO Employee " + "VALUES ('Archana', '10,Down California', 30000" ); String sqlString = "CREATE TABLE Employee " + "(name VARCHAR2(40), address VARCHAR2(80), license INT)" ;

stmt.executeUpdate(sqlString); Since the SQL statement will not quite fit on one line on the page, you can split it into two or more strings concatenated by a plus sign(+). "INSERT INTO Employee" to separate it in the resulting string from "VALUES". The point to note here is that the same Statement object is reused rather than to create a new one each time. When executeUpdate is used to call DDL statements, the return value is always zero, while data modification statement executions will return a value greater than or equal to zero, which is the number of tuples affected in the relation by execution of modification statement.

Page 113: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

48

Page 114: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

While working with a PreparedStatement, you should execute such a statement by first plugging in the values of the parameters (as you can see above), and then invoking the executeUpdate on it. For example:

int n = prepareUpdateEmployee.executeUpdate() ;

Executing SEL ECT Statements A query is expected to return a set of tuples as the result, and not change the state of the database. Not surprisingly, there is a corresponding method called execute Query, which returns its results as a

ResultSet object. It is a table of data representing a database result set, which is usually generated by

executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is

positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet obj ect, it can be used in a while loop to iterate through the result set. A default ResultSet object is not updatable and has a cursor that moves forward only In the program code given below:

String ename,eaddress;

float esal;

ResultSet rs = stmt.executeQuery("SELECT * FROM Employee"); while ( rs.next() ) {

ename = rs.getString("emp_name"); eaddress = rs.getString("emp_address"); esal = rs.getFloat("emp_salary"); System.out.println(ename + " address is" + eaddress + " draws salary " + esal + "in dollars");

} The tuples resulting from the query are contained in the variable rs which is an instance of ResultSet. A set is of not much use to you unless you can access each row and the attributes in each row. The? Now you should note that each invocation of the next method causes it to move to the next row, if one exi sts and returns true, or returns false if there is no remaining row. You can use the getXXX method of the appropriate type to retrieve the attributes of a row. In the above program code getString and getFloat methods are used to access the column values. One more thing you can observe that the name of the column whose value is desired is provided as a parameter to the method. Similarly, while working with a PreparedStatement, you can execute a query by first plugging in the values of the parameters, and then invoking the executeQuery on it.

1. ename = rs.getString(1); eaddress = rs.getFloat(3); esal = rs.getString(2);

2. ResultSet rs = prepareUpdateEmployee.executeQuery() ;

Accessing ResultSet Now to reach each record of the database, JDBC provides methods like getRow, isFirst, isBeforeFirst, isLast, isAfterLas to access ResultSet.Also there are means to make scroll-able cursors to allow free

access of any row in the ResultSet. By default, cursors scroll forward only and are read only. When

Page 115: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

49

Page 116: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

creating a Statement for a Connection, we can change the type of ResultSet to a more flexi ble scrolling or updatable model: Statement stmt = con.createStatement ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM Sells"); The different options for types are TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and

TYPE_SCROLL_SENSITIVE. We can choose whether the cursor is read-only or updatable using the

options CONCUR_READ_ONLY, and CONCUR_UPDATABLE. With the default cursor, we can scroll forward using rs.next(). With scroll-able cursors we have more options: rs.absolute(3); // moves to the third tuple or row

rs.previous(); // moves back one tuple (tuple 2) rs.relative(2); // moves forward two tuples (tuple 4) rs.relative(-3); // moves back three tuples (tuple 1)

4.2.2 Tr ansactions with Database When you go to some bank for deposit or withdrawal of money, you get your bank account updated, or in other words you can say some transaction takes place. JDBC allows SQL statements to be grouped together into a single transaction. Thus, you can ensure the ACID (Atomicity, Consistency,

Isolation, Durability) properties using JDBC transactional features. The Connection obj ect performs transaction control. When a connection is created, by default it is in

the auto-commit mode. This means that each individual SQL statement is treated as a transaction by itself, and will be committed as soon as its execution is finished. You can turn off auto-commit mode for an active connection with: con.setAutoCommit(false) ; And turn it on again if needed with: con.setAutoCommit(true) ; Once auto-commit is off, no SQL statements will be committed (that is, the database will not be permanently updated) until you have explicitly told it to commit by invoking the commit () method:

con.commit() ; At any point before commit, you may invoke rollback () to rollback the transaction, and restore values to the last commit point (before the attempted updates).

Q8 b) What is Java Bean ? What are its advantages?

A JavaBean on its own is not terribly interesting, it's just a Java class that conforms to some

standards that you listed above. However, conformance with this standard is one of the pillars on

which the Java EE framework is built and it comes up in quite a few places. I suspect that when

you hear about all of the great things that JavaBeans can do, what's being referred to in Enterprise

JavaBeans (EJBs). FYI, there are a few different types of EJB listed below:

1. Entity Beans

Page 117: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

50

Page 118: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

2. Stateful Session Beans

3. Stateless Session Beans

Some details now follow...

Entity Beans

You might want to read/write objects to/from an underlying database. You could use JDBC/SQL

to do this but you could also use a persistance framework. The Java EE spec includes a spec for

persistance whereby you declare your class to be an "entity bean" and have Java automatically

generate database tables and logic to map between entries in your database and objects in your

program. Originally, persistance was something that required the use of an Application Server

(such as Glassfish, JBoss, Geronimo etc.) but AFAIK, you can do use it in desktop apps with no

server component. The actual implementation is provided by a lower level library such as

Eclipselink, Toplink, Hibernate etc. but the Java API abstracts away any differences between

them.

Stateful Session Beans

Imagine that you want to create an instance of a Java class which exists on separate JVM. The

JVMs might be running on the same physical machine but equally, may be on separate machines

communicating over a network. Using a Java EE application server, you can create a class which

can be instantiated by clients of the app server. These clients can instantiate a class which will act

just like a normal object but any methods that are invoked on the object get executed on the server

with the results being passed back to the caller. It's basically an object oriented form of remote

procedure calls. Stateless Session Beans

This is a minor variation on stateful session beans. With stateful beans, if the server has 1000

clients then it will potentially have to create 1000 instances of the bean and remember which

instance belongs to which client. With stateless beans, the server creates a pool of beans and

doesn't bother to remember which client owns which bean. When a client invokes a method, the

server picks a bean from the pool and uses it, returning it to the pool on completion. You use

stateful session beans when you want the server to remember details about each client, you will

use stateless beans when you don't need to remember client specific details. Note that the stateless

beans may well have state, it's just that this state won't be of interest to the client.

Advantages

Most of all, a Java Bean is a reusable software component.

This means that it is not tightly coupled to other components. If your Java class creates an instance

of another class, or returns some specific implementation class, it is no longer a bean. Beans cover

some well-defined piece of functionality and are loosely coupled to other classes.

The advantage of this is that you get all these little pieces that you can then get to work together

pretty easily. Also, these are easy to reuse and unittest.

Even if you are not using some visual environment to couple beans (as the bean spec suggests),

this is still a reason to use beans: to get small pieces of code which are easily usable.

Page 119: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

51

Page 120: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

If you don't use a visual tool, it is not that important that your bean has a 0-argument constructor, or is serializable.

The biggest advantage is that your beans are built according to a specification and can be used

directly with "bean-compatible" libraries and frameworks.

For example, most frameworks for Serialization (XML, JSON, YAML, ...) often can use beans

directly without configuration.

For More Ignou Solved Assignments Please Visit -

www.ignousolvedassignments.com

Connect on Facebook :

http://www.facebook.com/pages/IgnouSolvedAssignmentscom/346544145433550

Subscribe and Get Solved Assignments Direct to your Inbox :

http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com

Request Any Solved Assignment at :

http://ignousolvedassignments.com/request-and-share-solved-assignments/

Page 121: IGNOU MCS-024 Solved Assignment 2012-13

http://www.ignousolvedassignments.com

52