You are on page 1of 23

SNS COLLEGE OF ENGINEERING COIMBATORE

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Java Programming Fifth Semester (2011-2012) Question Bank

UNIT 1 Two Marks Questions 1. What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. 2. What is a object? An object is a software bundle of variables and related methods. An instance of a class depicting the state and behaviour at that particular time in real world. 3. What is a method? Encapsulation of a functionality which can be called to perform specific tasks. 4. What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object 5.What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects. 6.What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language\'s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language 7.Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java. 8.What is JVM?
1

The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine (JVM) 9.What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other are final and static. 10. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 11. What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object 12. What is a static variable and static method? What\'s the difference between two? The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non-static method cannot be called from static method. 13. What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore. 14. What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, a class has to be declared abstract if it has one or more abstract methods. 15. What is meant by final class, methods and variables? This modifier can be applied to class, method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed. 16. What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation. 17.What is method overloading? Overloading is declaring multiple methods with the same name, but with different argument list. 18.What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM. 19.What is the difference between an array and a vector? Number of elements in an array is fixed at the construction time, whereas the number of elements in vector can grow dynamically. 20. What is a constructor?
2

In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed. 21.What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data. 22.What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain behaviours explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage for your object, it will first call finalize ( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize ( ), gives you the ability to perform some important cleanup at the time of garbage collection. 23.What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model. 24.What is meant by Encapsulation? Encapsulation is the process of compartmentalising the elements of an abstraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation. 25.What is meant by Inheritance? Inheritance is a relationship among classes, where in one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines \"is-a\" hierarchy among classes in which one subclass inherits from one or more generalised super classes. 26.What is meant by Polymorphism? Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behaviour or value in a subclass, to something that was declared in a parent class. 27.What is an Abstract Class? Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations. 28. What is an Interface? Interface is an outside view of a class or object which emphasizes its abstraction while hiding its structure and secrets of its behaviour.

PART- B
1. Explain in detail about Basic concepts (or) Java features (or) characteristics. 3

2. Explain Benefits of OOP 3. Explain about java and write Simple java program
4. What are Type Conversions & Casting and Arrays? Explain with example 5. What are the different kinds of operators in java? With example

6. 7. 8. 9.

Explain in detail about Control Structures available in java. How the object is declared and referenced with variables? Explain method overloading with an example program Explain in detail about constructor with an example 10. Explain in detail about explicitly invoking garbage collector and finalize () method? 11. Explain method overloading and method overriding with give suitable example. 12. Explain in detail about access control and static with example 13. Explain nested classes and inner classes in java.

UNIT 2 Two Marks Questions


4

1. What are packages?

A package is a collection of related classes and interfaces providing access protection and namespace management. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. 2.What is a super class and how can you call a super class? When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the 3.What is meant by Binding? Binding denotes association of a name with a class. 4.What is meant by static binding? Static binding is a binding in which the class association is made during compile time. This is also called as Early binding. 5.What is meant by Dynamic binding? Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding. 6.What is the importance of == and equals() method with respect to String object? == is used to check whether the references are of the same object. .equals() is used to check whether the contents of the objects are the same. But with respect to strings, object refernce with same content will refer to the same object. String str1=\"Hello\"; String str2=\"Hello\"; (str1==str2) and str1.equals(str2) both will be true. If you take the same example with Stringbuffer, the results would be different. Stringbuffer str1=\"Hello\"; Stringbuffer str2=\"Hello\"; str1.equals(str2) will be true. str1==str2 will be false. 7. Is String a Wrapper Class or not? No. String is not a Wrapper class. 8. How will you find length of a String object? Using length() method of String class. 9.How many objects are in the memory after the exection of following code segment? String str1 = \"ABC\"; String str2 = \"XYZ\"; String str1 = str1 + str2; ? There are 3 Objects. 10. What is the difference between an object and object reference?
5

An object is an instance of a class. Object reference is a pointer to the object. There can be many refernces to the same object. 11. What will trim() method of String class do? trim() eliminate spaces from both the ends of a string.*** 12. What is the use of java.lang.Class class? The java.lang.Class class is used to represent the classes and interfaces that are loaded by a java program. 13.What is the possible runtime exception thrown by substring() method? ArrayIndexOutOfBoundsException. 14.What is the difference between String and Stringbuffer? Object\'s of String class is immutable and object\'s of Stringbuffer class is mutable moreover stringbuffer is faster in concatenation. 15. What is the use of Math class? Math class provide methods for mathametical functions. 16. Can you instantiate Math class? No. It cannot be instantited. The class is final and its constructor is private. But all the methods are static, so we can use them without instantiating the Math class. 17. What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign. 18. What will Math.ceil() do? This method returns always double, which is not less than the supplied value. It returns next available whole number 19. What will Math.floor() do? This method returns always double, which is not greater than the supplied value. 20.What will Math.min() do? The min() method returns smaller value out of the supplied values. 21.What will Math.random() do? The random() method returns random number between 0.0 and 1.0. It always returns double. 22.How to define an Interface? In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. Example of Interface: public interface sampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; }
6

23.Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another object. 24.Explain the different forms of Polymorphism. From a practical programming viewpoint, polymorphism exists in three distinct forms in Java: o Method overloading o Method overriding through inheritance
o

Method overriding through the Java interface

25. What are Access Specifiers available in Java? Access Specifiers are keywords that determines the type of access to the member of a class. These are: o Public o Protected o Private o Defaults 26.When should I use abstract classes rather than interfaces? Abstract classes are often used to provide methods that will be common to a range of similar subclasses, to avoid duplicating the same code in each case. Each subclass adds its own features on top of the common abstract methods. 27.Can you give an example of multiple inheritance with interfaces? To illustrate multiple inheritance, consider a bat, which is a mammal that flies. We might have two interfaces: Mammal, which has a method suckleInfant(Mammal), and Flyer, which has a method fly(). These types would be declared in interfaces 28.Can we create a Java class inside an interface? Yes, classes can be declared inside interfaces. This technique is sometimes used where the class is a constant type, return value or method argument in the interface. When a class is closely associated with the use of an interface it is convenient to declare it in the same compilation unit. This proximity also helps ensure that implementation changes to either are mutually compatible. A class defined inside an interface is implicitly public static and operates as a top level class. The static modifier does not have the same effect on a nested class as it does with class variables and methods. The example below shows the definition of a StoreProcessor interface with nested StorageUnit class which is used in the two interface methods. 29.Can an interface extend an abstract class? In Java an interface cannot extend an abstract class. An interface may only extend a super-interface. And an abstract class may implement an interface. It may help to think of interfaces and classes as separate lines of inheritance that only come together when a class implements an interface, the relationship cannot be reversed. 30.Can we create an object for an interface?
7

Yes, the most common scenario is to create an object implementation for an interface, although they can be used as a pure reference type. Interfaces cannot be instantiated in their own right, so it is usual to write a class that implements the interface and fulfils the methods defined in it. public class Concrete implements ExampleInterface { ... } 31.What is a marker interface? Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface is a typical marker interface. It does not contain any methods, but classes must implement this interface in order to be serialized and de-serialized. 32.Explain the usage of Java packages. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes. 33. Can one create a method which gets a String and modifies it? No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example: String s = "abc"; //create a new String object representing "abc" s = s.toUpperCase(); //create another object representing "ABC" 34.What are the drawbacks of inheritance? Since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation. In addition, the inheritance may make peers hardly understand your code if they don't know how your super-class acts and add learning curve to the process of development. Usually, when you want to use a functionality of a class, you may use subclass to inherit such function or use an instance of this class in your class. 35. Can a private method of a superclass be declared within a subclass? Yes, a private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features. 36. Why Java does not support multiple inheritance ? This is a classic question. Yes or No depends on how you look at Java. If you focus on the syntax of "extends" and compare with C++, you may answer 'No' and give explanation to support you. Or you may answer 'Yes'. Recommend you to say 'Yes'. Java DOES support multiple inheritance via interface implementation. Some people may not think in this way. Give explanation to support your point. 37. What is the difference between the String and StringBuffer classes? String objects are constants. StringBuffer objects are not.
8

38. How is it possible for two String objects with identical values not to be equal under the == operator? The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. 39. What is string and String Buffer in java? The String and StringBuffer classes are used to support operations on strings of characters. The String class supports constant (unchanging) strings, whereas the StringBuffer class supports growable, modifiable strings. String objects are more compact than StringBuffer objects, but StringBuffer objects are more flexible. 40. Explain Character and Substring Methods in String Handing. Several String methods allow you to access individual characters and substrings of a string. These include charAt(), getBytes(), getChars(), indexOf(), lastIndexOf(), and substring(). Whenever you need to perform string manipulations, be sure to check the API documentation to make sure that you don't overlook an easy-to-use, predefined String method. 41. Explain String Comparison in java Several String methods allow you to compare strings, substrings, byte arrays, and other objects with a given string. Some of these methods are compareTo(), endsWith(), equals(), equalsIgnoreCase(), regionMatches(), and startsWith(). 42. What are the String Conversion methods? There are a number of string methods that support String conversion. These are intern(), toCharArray(), toLowerCase(), toString(), toUpperCase(), and valueOf(). 43. What is StringBuffer Class? The StringBuffer class is the force behind the scene for most complex string manipulations. The compiler automatically declares and manipulates objects of this class to implement common string operations. The StringBuffer class provides three constructors: an empty constructor, an empty constructor with a specified initial buffer length, and a constructor that creates a StringBuffer object from a String object.

PART-B 1. How is interface used to support multiple inheritance? Explain with a program. 2. Describe the various levels of access protection available in packages and their implications with an example program. 3. Explain in detail about creating and accessing packages with an example program. 4. Describe Method overriding. Explain it with an example. 5. How can you create Multilevel hierarchy? 6. Explain the using of final with inheritance. 7. Explain the use of super in inheritance
9

8. What are the various Special String operations and explain it with example? 9. Explain Character Extraction. 10. What are String Comparison Methods? 11. Explain the methods used for String Modification. 12. Explain in detail about string Buffer.

UNIT 3 Two Marks Questions 1. What is an Exception? An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. 2. What is a Java Exception? A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object
10

representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. 3.What are the two types of Exceptions? Checked Exceptions and Unchecked Exceptions. 4.What is the base class of all exceptions? java.lang.Throwable 5.What is the difference between Exception and Error in java? Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow. 6. What is the difference between throw and throws? throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{} 7. Differentiate between Checked Exceptions and Unchecked Exceptions? Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error. Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it\'s subclasses, Error and it\'s subclasses fall under unchecked exceptions. 8. What is User defined Exceptions? Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. 9. What is the importance of finally block in exception handling? Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc. 10. Can a catch block exist without a try block? No. A catch block should always go with a try block. 11. Can a finally block exist with a try block but without a catch? Yes. The following are the combinations try/catch or try/catch/finally or try/finally. 12. How does finally block differ from finalize() method? Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected. 13.What are the constraints imposed by overriding on exception handling?
11

An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. 14. What are the different ways to generate and Exception? There are two different ways to generate an Exception. -Exceptions can be generated by the Java run-time systemExceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. -Exceptions can be manually generated by your codeManually generated exceptions are typically used to report some error condition to the caller of a method. 15.Where does Exception stand in the Java tree hierarchy? java.lang.Object java.lang.Throwable java.lang.Exception java.lang.Error 16. Is it compulsory to use the finally block? It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block. 17. What is a throw in an Exception block? throw is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable. throw new NullPointerException(\"thrownException\"); 18.What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running. 19.What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out. 20. What methods java providing for Thread communications ? Java provides three methods that threads can use to communicate with each other: wait, notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is
12

that a method called by a thread may need to wait for some condition to be satisfied by another thread; in that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll. 21.What is the difference between notify and notify All methods ? A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify). 22. What is a daemon thread? These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. 23.How many methods in the Serializable interface? There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable. 24.How many methods in the Externalizable interface? There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). 25.What is the difference between Serializalble and Externalizable interface? When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. 26.What is Serialization and deserialization ? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 27.When is the ArrayStoreException thrown? When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown. 28. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 29. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. 30. What is the difference between notify() and notifyAll()? notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary
13

(for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume). 31. What do you understand by Synchronization? Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. 32. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors. 33. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 34. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. 35. How to create a thread in a program? Two ways. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread. 36. What invokes a thread's run() method? After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. 37. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other. 38. What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. 39. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 40. What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. 41. What is an IO filter?
14

An IO filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 42. What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. 43. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? The Reader/Writer class hierarchy is InputStream/OutputStream class hierarchy is byte-oriented. 44. What is the purpose of the File class? The File class is used to create objects that provide access to the files and directories of a local file system. 45. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 46. What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. 47. How do I serialize an object to a file? The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file. 48. What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). 49. What are the different ways to handle exceptions? There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. 2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. 50. What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. 51. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's
15

character-oriented,

and

the

object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 52. What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) 53. What is the purpose of the File class? The File class is used to create objects that provide access to the files and directories of a local file system. 54. Define Streams Java input and output is based on the use of streams. Streams are sequences of bytes that travel from a source to a destination over a communication path. If your program is writing to a stream, it is the 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, file system, network, and other forms of I/O. 55.What are the subclasses of InputStream? The InputStream class has six subclasses. The ByteArrayInputStream class is used to convert an array into an input stream. The StreamBufferInputStream class uses a StreamBuffer as an input stream. The FileInputStream allows files to be used as input streams. The PipedInputStream class allows a pipe to be constructed between two threads and supports input through the pipe. The SequenceInputStream class allows two or more streams to be concatenated into a single stream. The FilterInputStream class is an abstract class from which other input-filtering classes are constructed. 56.What are the subclasses of OutputStream? The OutputStream class hierarchy consists of four major subclasses. The ByteArrayOutputStream, FileOutputStream, and PipedOutputStream classes are the output complements to the ByteArrayInputStream, FileInputStream, and PipedInputStream classes. The FilterOutputStream class provides subclasses that complement the FilterInputStream classes. PART-B 1. Explain in detail about Exception types with example 2. With suitable example explain try and catch in Exception 3. What is Multiple Catch? What is Nested Try? With example. 4. Explain the Checked and UnChecked Exception in Java. 5. Explain File with example 6. What are the Character Stream Hierarchies? Explain its Methods.
16

7. What is Serialization? What are the interfaces and classes that support serialization?

UNIT 4 Two Marks Questions 1. Which Methods are used in Applet? For Applet Initialization - init(), start(), paint(). For Applet Termination stop(), destroy(). 2. Define AWT. The Java Abstract Windowing Toolkit (AWT) provides numerous classes that support window program development. These classes are used to create and organize windows, implement GUI components, handle events, draw text and graphics, perform image processing, and obtain access to the native Windows implementation. 3. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.

17

4. Explain Relationship Between HTML and Applets An applet is like a child application of the browser. The browser launches the applet in a predefined environment inside the browser. In turn, the browser obtains the information pertaining to the applet's environment from the current document's HTML. In this sense, the relationship between HTML and an applet is that of a command line executing a program. 5. What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. 6. What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. 7. What is the difference between Swing and AWT components? AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button 8. Name Component subclasses that support painting ? The Canvas, Frame, Panel, and Applet classes support painting. 9. Can applets communicate with each other? At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable. An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members. 10.What is the advantage of the event-delegation model over the earlier event-inheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model 11.What is the highest-level event class of the event-delegation model? The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. 12.Define Delegation Event Model The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In thisscheme, the
18

listener simply waits until it receives an event. Once received, the listener processes the event and then returns. 13.What is the different Event class? ActionEvent, AdjustmentEvent, ComponentEvent, ContainerEvent, FocusEvent, InputEvent, ItemEvent, KeyEvent, MouseEvent, MouseWheelEvent, TextEvent, and WindowEvent 14. Define Event Listeners A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. 15.Define ActionEvent class The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events. 16. What is ContainerEvent Class A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that a component has been added to or removed from the container. ContainerEvent is a subclass of ComponentEvent and has this constructor: ContainerEvent(Component src, int type, Component comp) 17.What is the Collection interface? The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. 18.What is an Iterator? Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. 19.What is the Map interface? The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. 20.What are the various Collection Interfaces? Interface Collection List Set Description Enables you to work with groups of objects; it is at the top of the collections hierarchy. Extends Collection to handle sequences (lists of objects) Extends Collection to handle sets, which must contain unique elements
19

SortedSet 21.Define List Interface.

Extends Set to handle sorted sets.

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. 22. Explain the steps for using Iterator. 1. Obtain an iterator to the start of the collection by calling the collections iterator( ) method. 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 3. Within the loop, obtain each element by calling next( ). 23.Define Maps A map is an object that stores associations between keys and values, or key/value pairs.Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. 24. What are the methods() used in Audioclip Interface? play() stop() loop() getAudioClip()

PART-B 1. What is applet? Explain Applet skeleton and Applet Initialization & Termination. 2. 3. 4. Write a Java Program to display a message using Applet? Explain about HTML Applet Tag. Give an example program for passing Parameter to Applet.

5. What is Delegation Event Model? Explain Events, Event Sources, Event Listener. 6. Explain the various Event Classes in java with suitable example. 7. What are the different interfaces in Collection Interface? Explain each with its Method. 8. 9. 10. 11. Explain the Collection classes with example. Write a program using Iterator. Describe the Interface that maintains Maps. What are the Map Classes? Demonstrate the usage of Comparator.
20

12.

Explain in detail about Legacy Classes and Interfaces.

UNIT 5 Two Marks Questions 1. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 2. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. 3.What is Locale? A Locale object represents a specific geographical, political, or cultural region 4.How will you load a specific locale? Using ResourceBundle.getBundle(); 5. Define StringTokenizer Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer
21

implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer. 6.What are the StringTokenizer constructors? StringTokenizer (String str) StringTokenizer(String str, String delimiters) StringTokenizer(String str, String delimiters, boolean delimAsToken) 7. List the Methods in StringTokenizer The access methods provided by StringTokenizer include the Enumeration methods, hasMoreElements() and nextElement(), hasMoreTokens() and nextToken(), and countTokens(). The countTokens() method returns the number of tokens in the string being parsed. 8. What is Bitset? The BitSet class is used to create objects that maintain a set of bits. The bits are maintained as a growable set. The capacity of the bit set is increased as needed. Bit sets are used to maintain a list of flags that indicate the state of each element of a set of conditions. Flags are boolean values that are used to represent the state of an object. 9.Define Date class. The Date class encapsulates date and time information and allows Date objects to be accessed in a system-independent manner. Date provides methods for accessing specific date and time measurements, such as year, month, day, date, hours, minutes, and seconds, and for displaying dates in a variety of standard formats. 10.Define Random class The Random class provides a template for the creation of random number generators. It differs from the random() method of the java.lang.Math class in that it allows any number of random number generators to be created as separate objects. The Math.random() method provides a static function for the generation of random double values. This static method is shared by all program code. 11. List the Methods of Random class. The Random class provides six access methods, five of which are used to generate random values. The nextInt(), nextLong(), nextFloat(), and nextDouble() methods generate values for the numeric data types. The values generated by nextFloat() and nextDouble() are between 0.0 and 1.0. The nextGaussian() method generates a Gaussian distribution of double values with mean 0.0 and standard deviation 1.0. The setSeed() method is used to reset the seed of the random number generator. 12.Define Calendar class The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to a number of useful components. Some examples of the type of information that can be provided are: year, month, day, hour, minute, and second. 13.Explain SimpleTimeZone The SimpleTimeZone class is a convenient subclass of TimeZone. It implements TimeZones abstract methods and allows you to work with time zones for a Gregorian calendar. It also computes daylight saving time. 14. DefineCurrency.
22

Currency class encapsulates information about a currency. It defines no constructors. The following program demonstrates Currency. // Demonstrate Currency. import java.util.*; class CurDemo { public static void main(String args[]) { Currency c; c = Currency.getInstance(Locale.US); System.out.println("Symbol: " + c.getSymbol()); System.out.println("Default fractional digits: " + c.getDefaultFractionDigits()); } } The output is shown here. Symbol: $ Default fractional digits: 2 15. Define Java debugger The Java debugger enables Java programmers to debug their programs without having to insert special debugging instructions into their code. The debugger has a number of features, including support for multithreaded programs and remote applications. The debugger is invoked with the jdb command. PART-B
1. Explain StringTokenizer along with its Methods.

2. What is BitSet? Give example. 3. Write a program to display Date and Time using Date Methods. 4. Write a program to display Calendar.
5. Define GregorianCalendar. Explain with example. 6. Explain TimeZone and SimpleTimeZone.

7. List the methods defined by Random Class. Give suitable example.


8. Describe Currency class and Locale class.

23

You might also like