Unit 5 - Mahalakshmi Engineering College

advertisement

QUESTION BANK

DEPARTMENT:

EEE

SEMESTER: V

SUBJECT CODE / Name: CS2311 – OBJECT ORIENTED PROGRAMMING

UNIT – V

PART - A (2 Marks)

1. What is the difference between super class and sub class? (AUC MAY 2013)

The superclass is the class from which the current class inherits.

The subclass is the class which inherits from the current class. class ArrayList extends AbstractList {}

Here AbstractList is the superclass of ArrayList and ArrayList is the subclass of AbstractList.

2. Java does not support multiple inheritance. Why? (AUC MAY 2013)

Classes in java cannot have more than one superclass.

For example

Class A extends B extends C

{

---

---

} is not permitted in java.

3. What is the difference between an Interface and an Abstract class? (AUC DEC

2012)

An Interface is basically a kind of class. Like classes, interfaces contain methods and variables with difference. That is interface do not specify any code to implement these methods.

Abstract class is the one that is not used to create objects. That is, it is designed only to act as a base class.

4. What is a inner class? (AUC DEC 2012)

Inner class is a class whose body is defined inside of another class. That is class contains

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

another class.

5. Define interface. State its use.(AUC MAY 2012)

An Interface is basically a kind of class. Like classes, interfaces contain methods and variables with difference. That is interface do not specify any code to implement these methods.

It contains static variables and abstract methods which will be overridden in the sub class.

6. What is thread?(AUC MAY 2012)

A thread is a single sequential flow of control within a program.

A single thread also has a beginning, an end, a sequence, and at any given time during the runtime of the thread there is a single point of execution. However, a thread itself is not a program. It cannot run on its own, but runs within a program.

7. How is the keyword

‘ supe r’ used in Java? (AUC DEC 2011)

‘super’ is a reference variable that is used to refer immediate parent class object.

(i) super is used to refer immediate parent class instance variable.

(ii) super() is used to invoke immediate parent class constructor.

(iii) super is used to invoke immediate parent class method.

8. What are wrapper classes in Java? (AUC DEC 2011)

Corresponding to all the primitive data types java defines a set of classes referred as wrapper classes, which serves as class versions of the fundamental data types and named similar to the data types.

9. Give a sample statement for parseInt() and give comments for the statement.

(AUC DEC 2010)

This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two. public class Test{ public static void main(String args[]){ int x =Integer.parseInt("9"); double c = Double.parseDouble("5"); int b = Integer.parseInt("444",16);

}

}

System.out.println(x);

System.out.println(c);

System.out.println(b);

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

10. What are the two ways of creating java threads? (AUC DEC 2010)

1.By inheriting Thread class.

2.By implementing interface Runnable.

11. Define Method Overriding.

When you have 2 methods with same name and same arguments list, one present in the base class and another present in the sub class. When you access the method in the base class using the object of the derived class, the method in the derived class will be called instead of the method in the base class. The derived class method has overridden the base class method.

12. What is package? What are the packages of Java?

Package is a collection of related classes and interfaces. It is also defined as

“putting classes together”. They are of two types.

 Java API Packages

 User Defined Packages

13. What is use of Final keyword in java?

The Final keyword is similar to the keyword “Const” in C/C++. It is used several different circumstances as a modifier meaning you can not reassign the same in some sense.

14. Write about API Packages.

Java API provides a large number of classes grouped into different packages according to functionality.

 Language Package(java.lang)

 Utilities Package(java.util)

 I/O Package(java.io)

 Networking Package(java.net)

 Applet Package(java.applet)

 AWT Package(java.awt)

15. What are thread states?

NEW

A thread that has not yet started is in this state.

RUNNABLE

A thread executing in the Java virtual machine is in this state.

BLOCKED

A thread that is blocked waiting for a monitor lock is in this state.

WAITING

A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED WAITING

A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

TERMINATED

A thread that has exited is in this state.

16. Define Synchronization.

One thread try to read a record from a file while another is still writing to the same file.

Depending on the situation, we may get strange results. To overcome this problem using a technique known as synchronization.

17. Write about thread priorities.

 The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively.

 To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.

18. Draw the hierarchy for Reader and Writer classes.

19. Write about the stream hierarchy.

20. Define multithreading.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

Java provides built-in support for multithreaded programming . A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multithreading requires less overhead than multitasking processing.

PART – B (16 Marks)

1. Create class box and box3d. box3d is an extended class of box. The above two classes has to fulfill the following requirement. Set value of length, breadth, height. Find out area and volume. (AUC MAY 2013) class Box { double length; double breadth;

Box()

{

}

Box(double l, double b

{ length = l; breadth = b;

} void getArea()

{

System.out.println("Area is : " + length * breadth);

}

} public class Box3d extends Box {

} double height;

Box3d()

{

}

Box3d(double l, double b, double h)

{ super(l, b); height = h;

} void getVolume()

{

System.out.println("Volume is : " + length * breadth * height);

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

public static void main(String args[]) {

Box3d mb1 = new Box3d(10, 10, 10); mb1.getArea(); mb1.getVolume();

System.out.println("Length of Box3d is " + mb1.length);

System.out.println("breadth of Box3d is " + mb1.breadth);

System.out.println("height of Box3d is " + mb1.height);

}

}

Output

Area is 100.0

Volume is : 1000.0 length of MatchBox 1 is 10.0 breadth of MatchBox 1 is 10.0 height of MatchBox 1 is 10.0

2. What is exception handling in Java? Why is it used? With example, explain how to handle the exception with overloaded methods. (AUC MAY 2013)

Explain with example program exception handling in java.(AUC MAY 2012)

Exceptions are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language.

Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events.

Exception Hierarchy:

There are three types of Exceptions:

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

1)Checked Exceptions - These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptions extend the java.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses.

For example if you call the readLine() method on a BufferedReader object then the

IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throwsjava.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well-written application and will also prompt to correct the file name. Here is the list of checked exceptions.

NoSuchFieldException

InstantiationException

IllegalAccessException

ClassNotFoundException

NoSuchMethodException

CloneNotSupportedException

InterruptedException

2)Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception

class . These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API.

These type of exceptions are also calledRuntime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.

Lets take the same file name example as described earlier. In that example the file name is passed to the constructor for FileReader. However, the constructor will throwNullPointerException if a logic error causes a null to be passed to the constructor. Well in this case the exception could be caught by the application but it would rather try to eliminate the bug due to which the exception has occurred. You must have encountered the most common exception in your program i.e. the

ArithmeticException . I am sure you must be familiar with the reason of its occurrence that is when something tries to divide by zero. Similarly when an instance data member or method of a reference variable is to be accessed that hasn't yet referenced an object throws NullPointerException .

Here is the list of unchecked exceptions.

IndexOutOfBoundsException

ArrayIndexOutOfBoundsException

ClassCastException ArithmeticException

NullPointerException

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

IllegalStateException

SecurityException

3) Error - The errors in java are external to the application. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement.

Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown. This error will cause the program to terminate but if an application wants then the error might be caught. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions.

Throwing Exceptions

If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in the method signature, and then include a throw-statement in the method. Here is an example:

When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed. In the example above the "return numberToDivide / numberToDivideBy;" statement is not executed if a

BadNumberException is thrown. The program resumes execution when the exception is caught somewhere by a "catch" block. Catching exceptions is explained later.

You can throw any type of exception from your code, as long as your method signature declares it. You can also make up your own exceptions. Exceptions are regular Java classes that extends java.lang.Exception, or any of the other built-in exception classes. If a method declares that it throws an exception A, then it is also legal to throw subclasses of A.

Catching Exceptions

If a method calls another method that throws checked exceptions, the calling method is forced to either pass the exception on, or catch it. Catching the exception is done using a try-catch block. Here is an example:

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

The BadNumberException parameter e inside the catch-clause points to the exception thrown from the divide method, if an exception is thrown.

If no exeception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed.

If an exception is thrown inside the try-block, for instance from the divide method, the program flow of the calling method, callDivide, is interrupted just like the program flow inside divide.

The program flow resumes at a catch-block in the call stack that can catch the thrown exception. In the example above the "System.out.println(result);" statement will not get executed if an exception is thrown fromt the divide method. Instead program execution will resume inside the "catch

(BadNumberException e) { }" block.

If an exception is thrown inside the catch-block and that exception is not caught, the catch- block is interrupted just like the try-block would have been.

When the catch block is finished the program continues with any statements following the catch block. In the example above the "System.out.println("Division attempt done");" statement will always get executed.

Example: Catching IOException's

If an exception is thrown during a sequence of statements inside a try-catch block, the sequence of statements is interrupted and the flow of control will skip directly to the catch-block.

This code can be interrupted by exceptions in several places:

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

If the reader.read() method call throws an IOException, the following

System.out.println((char) i ); is not executed. Neither is the last reader.close() or the

System.out.println("--- File End ---"); statements. Instead the program skips directly to the catch(IOException e){ ... } catch clause. If the new FileReader("someFile"); constructor call throws an exception, none of the code inside the try-block is executed.

Finally

You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:

No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed,

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

regardless of the program flow inside the try or catch block.

3. (i) Write a Java program to implement multiple inheritance using interface. (8)

(AUC DEC 2012) interface car

{ int speed=90; public void distance();

} interface bus

{ int distance=100; public void speed();

} class vehicle implements car,bus

{ public void distance()

{ int distance=speed*100;

}

System.out.println(“distance travelled is”+distance);

{ public void speed()

} int speed=distance/100;

}

{ class maindemo

{ public static void main(String args[])

}

}

System.out.println(“w.r.t Vehicle”);

Vechicle v1=new Vehicle(); v1.distance(); v1.speed();

(ii) What is multithreading? Explain with an example. (8) (AUC DEC 2012)

What is a thread? How do you create threads? (6) (AUC DEC 2011)

Write about Java threads. (8) (AUC DEC 2010)

Java provides built-in support for multithreaded programming . A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multitasking threads require less

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

overhead than multitasking processes.

A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the

CPU, because idle time can be kept to a minimum.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Above mentioned stages are explained here:

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

Runnable : After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

terminates.

Creating a Thread:

Java defines two ways in which this can be accomplished:

By implementing the Runnable interface.

By extending the Thread class, itself.

1)Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( )

You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.

After you create a class that implements Runnable, you will instantiate an object of type

Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName .

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here: void start( );

Example:

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

2)Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.

The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

4. (i) Write a Java program to add two integers and raise exception when any other character except number (0-9) is given as input. (8) (AUC DEC 2012) import java.util.Scanner; public class TestException { static int input; static Scanner scan = new Scanner(System.in); public static void main(String[] args) {

System.out.println("Enter an integer number: ");

}

} try { input = Integer.parseInt(scan.next());

System.out.println("You've entered number: " + input);

} catch (NumberFormatException e) {

System.out.println("You've entered non-integer number");

System.out.println("This caused " + e);

}

(ii) Write short notes on various I/O streams in Java. (8) (AUC DEC 2012)

Explain with examples from Java. - Streams and IO (AUC DEC 2010)

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.

No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an

input stream

to read data from a source, one item at a time:

A program uses an

output stream

to write data to a destination, one item at time:

Byte Streams

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream .

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file

I/O byte streams, FileInputStream and FileOutputStream . Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Character Streams

The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.

Buffered Streams

Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

To reduce this kind of overhead, the Java platform implements buffered I/O streams.

Buffered input streams read data from a memory area known as a buffer ; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we've used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class. Here's how you might modify the constructor invocations in the

CopyCharacters example to use buffered I/O: inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and

BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.

5. Explain in detail about inheritance with example program in java language.(AUC

MAY 2012)

(i) Describe the three different types of inheritance with an example Java program for each. (AUC DEC 2011)

The concept of inheritance is used to make the things from general to more specific e.g.

When we hear the word vehicle then we got an image in our mind that it moves from one place to another place it is used for traveling or carrying goods but the word vehicle does not specify whether it is two or three or four wheeler because it is a general word.

But the word car makes a more specific image in mind than vehicle, that the car has four wheels. It concludes from the example that car is a specific word and vehicle is the general word.

If we think technically to this example then vehicle is the super class (or base class or parent class) and car is the subclass or child class because every car has the features of it's parent (in this case vehicle) class

The following kinds of inheritance are there in java.

Simple Inheritance

Multilevel Inheritance

Pictorial Representation of Simple and Multilevel Inheritance

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

Simple Inheritance

When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance. class A

{ int x; int y; int get(int p, int q)

{ x=p; y=q; return(0);

} void Show()

{

System.out.println(x);

}

} class B extends A

{ public static void main(String args[])

{

A a = new A(); a.get(5,6); a.Show();

} void display()

{ System.out.println("B");

}

}

Multilevel Inheritance

It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

Java does not support multiple Inheritance

Multiple Inheritances

The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritances. Java does not support multiple inheritances but the multiple inheritances can be achieved by using the interface.

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

(ii) Describe the concept of interface with the syntax. (6) (AUC DEC 2011)

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interface in a class.

Multiple inheritance using interfaces to calculate the area of a rectangle and triangle

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

6. (i) Write a Java program to demonstrate how to read and write data to a file. (10) (AUC DEC 2011) import java.io.*; import java.util.*; public class Test

{ public static void main(String[] args)

{ try

{

String fileName="c:\\out.txt"; if ((fileName == null) || (fileName == "")) throw new IllegalArgumentException();

String line;

ArrayList file = new ArrayList();

FileReader fr = new FileReader(fileName);

BufferedReader in = new BufferedReader(fr); if (!in.ready()) throw new IOException(); while ((line = in.readLine()) != null) { file.add(line);

} in.close();

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

} catch (IOException e)

}

}

{

System.out.println(e);

}

7. Write a java class called ‘student’ with name, Marks of 3 subjects and total

Marks. Write another class named ‘calculate’ that gets the Marks of the student and calculates the total Marks and display the result(pass or fail). (AUC DEC

2010)

}

} class student

{

String name; int m1, m2, m3; int total; public void getdetails(String n, int a, int b, int c)

{ name=n; m1=a; m2=b; m3=c; class calculate extends student

{ public void computetotal()

{ total = m1+m2+m3; system.out.println(“total = “+total);

} public void computegrade()

{ if(m1>=50&&m2>=50&&m3>=50) system.out.println(“result is pass”); else system.out.println(“result is fail”);

} public static void main(String args[])

{

}

} calculate c=new calculate(); c.getdetails(“anu”,52, 87,98); c.computetotal(); c.computegrade();

CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT V / V Sem EEE

Download