Nandha Engineering College, Erode - 52 (Autonomous) Department of Computer Science & Engineering Cs2305-Programming Paradigms
Nandha Engineering College, Erode - 52 (Autonomous) Department of Computer Science & Engineering Cs2305-Programming Paradigms
Nandha Engineering College, Erode - 52 (Autonomous) Department of Computer Science & Engineering Cs2305-Programming Paradigms
(Autonomous)
Department of Computer Science & Engineering
CS2305- PROGRAMMING PARADIGMS
2-MARK Questions and Answers
UNIT I
OBJECT-ORIENTED PROGRAMMING FUNDAMENTALS
1)
2)
What is a Class?
(NOV/DEC 2010)
What is an Object?
(NOV/DEC 2010)
What is an Instance?
.An instance has state, behaviour and identity. The structure and
behaviour of similar classes are defined in their common class. An
instance is also called as an object.
5)
8)
(NOV/DEC 2011)
Encapsulation is the mechanism that binds together code and data it manipulates and
keeps both safe from outside interference and
misuse. Inheritance is the process by which
one object acquires properties of another object. Polymorphism is the feature that allows one
interface to be used for general class actions.
9) What are methods and how are they defined?
Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes. Method
definition has four parts. They are name of the method, type of object or primitive type the
method returns, a list of parameters and the body of the method. A methods signature is a
combination of the first three parts mentioned above.
10) What are different types of access modifiers (Access specifiers)?(NOV/DEC 2011)
Access specifiers are keywords that determine the type of access to the member of a class. These
keywords are for allowing privileges to parts of a program such as functions and variables. These
are:
public: Any thing declared as public can be accessed from anywhere. private: Any thing declared
as private cant be seen outside of its class. protected : Any thing declared as protected can be
accessed by classes in the same package and subclasses in the other packages.
default modifier : Can be accessed only to classes in thesame package.
.
11) What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines a structured set of data
with a set of operations for inspecting and manipulating that data. When an object is created
using new operator, memory is allocated to it.
12) 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.
13) What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with different
arguments is said to be method overloading. Method overriding : When a method in a class
having the same method name with same arguments is said to be method overriding.
14) What gives java its write once and run anywhere nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be
run in any platform and hence java is said to be platform independent.
15)
Constructor is an operation that creates an object and/or initialises its state. Destructor is an
operation that frees the state of an object and/or
destroys the object itself. In Java, there is no
concept of destructors. Its
taken care by the JVM.
16)
All the instance variables should be declared as private and public getter and
setter methods should be provided for accessing the instance variables.
20)
static variable is a class variable which value remains constant for the entire class static
method is the one which can be called with the class itself and can hold only the staic
variables
21)
(May/June 2012)
finalize () method is used just before an object is destroyed and canbe called just
prior to garbage collection.
22)
What is the difference between String and String Buffer? (nov/dec 2010)
b) String class supports constant strings whereas StringBuffer class supports growable and
modifiable
strings.
23) What is the difference between Array and vector?
Array is a set of related data type and static whereas vector is a growable array of objects and
dynamic
24) What is a package? (May/June 2011)
A package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.
25) What is the difference between this() and super()?
this() can be used to invoke a constructor of the same class whereas super() can be used to
invoke a super class constructor.
26) Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first
converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and
Interpreter reads byte codes.
27)Write any four java comments.
Dec 2011
The basic structure of writing document comments is embed them inside /** ...
*/.
Tag & Parameter
@author name
@version version
@since since-text
@see reference
Usage
Applies to
Describes an author.
Class, Interface
Provides version entry. Max one per Class or Class, Interface
Interface.
Describes since when this functionality has
Class, Interface, Field, Method
existed.
Provides a link to other element of
Class, Interface, Field, Method
documentation.
// CommentDemo.java
// Demonstrating multi-line comments
public class CommentDemo
{ public static void main(String[] args)
{
OUTPUT
} }}
======
01234
In CommentDemo.java a comment is inserted in for loop header. If we need to supply a
comment somewhere in middle of the code line, then we are left with the only choice of slashstar comment.
It is very important to keep following points in mind, while inserting comments in a Java
programs.
Nesting of slash-star (/* and */) comments have no special meaning in double slash (//) or
single line comments.
Nesting of double slash (//) comments has no special meaning in slash-star (/*) comments
or Javadoc (/**) comments.
34)What is the difference between static and non static variable(NOV/DEC 2010)
Static Variable:
static variable belongs to the class and not an instance(object of the class)
It is created before the initialization of object and only once at the start of the execution.
Its values are shared by all the instances of that class.
It can be accessed directly by the class without object.
Non- Static Variable:
A non-static variable is specific to a single instance of that class.
Every time the class is instantiated, the object has their own copy of these variables.
Its life cycle is dependent on the scope of the braces where it has been initialized.
It cannot be called from the static method directly without its class reference.
Example:
public class Test {
static int a=6;
int b=8;
public static void main(String[] args) {
sqrt of 16 is : 4.0
UNIT I
Part B
1. Explain OOP Principles.
2. Explain the features of Java Language.
3. Compare and Contrast Java with C.
4. Compare and Contrast Java with C++.
5. Explain Constructors with examples.
6. Explain the methods available under String and String Buffer Class.
7. Explain the Date Class methods with examples.
8. Discuss in detail the access specifiers available in Java.
9. Explain the different visibility controls and also compare with each of them.
10. Explain the different methods in java.Util.Arrays class with example.
11. Explain Packages in detail.
12. Discuss the methods under Array Class.
13. Discuss some of the classes available under Lang package.
14. Illustrate with examples: static and final.
15. Explain method overriding with example program.
16. What is javaDoc? Explain the comments for classes, methods, fields and link.
17. Application Programs in Java.
UNIT II
OBJECT-ORIENTED PROGRAMMING INHERITANCE
1) What is meant by Inheritance? (May/June 2012)
Inheritance is a relationship among classes, wherein 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 onesubclass inherits from one or more generalised
superclasses.
2) What is meant by Inheritance and what are its advantages?
Inheritance. is the process of inheriting all the features from a class. The advantages of
inheritance are reusability of code and accessibility of variables and methods of the super class
by subclasses.
3) What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the inheriting.
4) Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to
represent the classes and interfaces that are loaded by a Java program. The Class class is used to
obtain information about an object's design. A Class is only a definition or prototype of real life
object. Whereas an object is an instance or living representation of real life object. Every object
belongs to a class and every class contains one or more related objects.
5) What is meant by Binding?
Binding denotes association of a name with a class
6) What is meant by Polymorphism?
Polymorphism literally means taking more than one form. Polymorphism is a characteristic of
being able to assign a different behavior or value in a subclass, to something that was declared in
a parent class.
Inner class: classes defined in other classes, including those defined in methods are called inner
classes. An inner class can have any accessibility including private.
Anonymous class: Anonymous class is a class defined inside a method without a name and is
instantiated and declared in the same place and cannot have explicit constructors
11) What is an Interface? NOV/DEC 2011)
Interface is an outside view of a class or object which emphaizes its abstraction while hiding its
structure and secrets of its behaviour.
12) What is a base class?
Base class is the most generalised class in a class structure. Most applications have such root
classes. In Java, Object is the base class for all classes.
13) What is reflection in java?(NOV/DEC 2012)(MAY/JUNE 12)
Reflection allows Java code to discover information about the fields, methods and constructors
of loaded classes and to dynamically invoke them.
Reflection is the ability of the software to analyze itself at runtime.
Reflection is provided by the java.lang.reflect package and elements in class.
This mechanism is helpful to tool builders, not application programmers.
The reflection mechanism is extremely used to
Analyze the capabilities of classes at run time
Inspect objects at run time
Implement generic array manipulation code
Can you have an inner class inside a method and what variables can you access?
Yes, we can have an inner class inside a method and final variables can be accessed.
20)
Interface is similar to a class which may contain methods signature only but not bodies and it is
a formal set of method and constant declarations that must be defined by the class that
implements it.
Interfaces are useful for
a) Declaring methods that one or moreclasses are expected to implement
b) Capturing similarities betweenunrelated classes without forcing a class relationship.
c) Determining an objects programming interface without revealing the actual body of the class.
notify com
notifyAll
When an abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class. However, if it does not, then the subclass must also be
declared abstract.
concrete implementation.Marking the class "final" means that no other class can extend it and
hence abstract classes cannot be marked final.
UNIT II
PART B
. Explain the concept of inheritance and its types.
2. Explain the concept of overriding with examples.
3. What is dynamic binding? Explain with example.
4. Explain the uses of reflection with examples.
5. Define an interface. Explain with example.
6. Explain the methods under object class and class class.
7. What is object cloning? Explain deep copy and shallow copy with examples.
8. Explain static nested class and inner class with examples.
9. With an example explain proxies.
10. Develop a message abstract class which contains playMessage abstract method. Write a different
sub-classes like TextMessage, VoiceMessage and FaxMessage classes for to implementing the
playMessage method.
11. Develop a abstract Reservation class which has Reserve abstract method. Implement the subclasses like ReserveTrain and ReserveBus classes and implement the same.
12. Develop an Interest interface which contains simpleInterest and compInterest methods and static
final field of Rate 25%. Write a class to implement those methods.
13. Develop a Library interface which has drawbook(), returnbook() (with fine), checkstatus() and
reservebook() methods. All the methods tagged with public.
14. Develop an Employee class which implements the Comparable and Cloneable interfaces.
Implement the sorting of persons (based on name in alphabetical). Also implement the shallow copy
(for name and age) and deep copy (for DateOfJoining).
15. Explain the different methods supported in Object class with example.
16. Explain the methods supported in Class class.
17. Explain the Methods supported in reflect package. Also write a program to implement the
reflection of a particular class details like constructors, methods and fields with its modifiers.
18. Develop a static Inner class called Pair which has MinMax method for finding min and max
values from the array.
19. What is proxy class? Develop a code for constructing a proxy objects to trace a binary search
method with explanations.
UNIT III
EVENT-DRIVEN PROGRAMMING
1) What is the relationship between the Canvas class and the Graphics class? (MAY/JUNE 2011)
A Canvas object provides access to a Graphics object via its paint() method.
2) How would you create a button with rounded edges? (MAY/JUNE 2011)
Theres 2 ways. The first thing is to know that a JButtons edges are drawn by a Border. so you
can override the Buttons paintComponent(Graphics) method and draw a circle or rounded
rectangle (whatever), and turn off the border. Or you can create a custom border that draws a
circle or rounded rectangle around any component and set the buttons border to it.
3) What is the difference between the Font and FontMetrics class?
The Font Class is used to render glyphs - the characters you see on the screen. FontMetrics
encapsulates information about a specific font on a specific Graphics object. (width of the
characters, ascent, descent)
4) 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.
5) Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
6) What is the difference between applications and applets?
a)Application must be run on local machine whereas applet needs
no explicit installation on local machine.
b)Application must be run explicitly within a java-compatible virtual
machine whereas applet loads and runs itself automatically in a java-enabled
browser.
c)Application starts execution with its main method whereas applet starts
execution with its init method.
d)Application can run with or without graphical user interface
whereas applet must run within a graphical user interface.
S.No
1
2
3
4
AWT(Abstract Window
Toolkit)
AWT components are heavy
weight, components are
platform dependent.
AWT components support
Delegate Event Model.
AWT components provide
static look and feel.
It does not provide Tooltip
text for components
Swing
Swing components are light
weight, components are
platform independent.
Swing components support
MVC (model, view, control
architecture)
Swing components provide
dynamic look and feel
It provide Tooltip text for
components
8) What is a layout manager and what are different types of layout managers
available in java AWT?
A layout manager is an object that is used to organize components in a container. The different
layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and
GridBagLayout.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a
grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid.
However, the elements are of different size and may occupy more than one row or column of the
grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub classes is FlowLayout.
11) What is an event and what are the models available for event handling?
An event is an event object that describes a state of change in a source. In other words, event
occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc.
There are two types of models for handling events and they are: a) event-inheritance model and
b) event-delegation model
14) What is meant by controls and what are different types of controls in AWT?
Controls .arecomponents that allow a user to interact with your application and the AWT
supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists,
Scrollbars, and Text Components.
UNIT III
EVENT-DRIVEN PROGRAMMING
1.
2.
3.
4.
5.
6.
UNIT IV
GENERIC PROGRAMMING
1) What is an exception?(MAY/JUNE 2011)(MAY/JUNE 2012)
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.
2) What is error? MAY/JUNE 2011)(
An Error indicates that a non-recoverable condition has occurred that should not be caught.
Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError,
which would be reported by the JVM itself.
3) Which is superclass of Exception?
"Throwable", the parent class of all exception related classes.
4) What are the advantages of using exception handling?
Exception handling provides the following advantages over "traditional" error management
techniques:
Separating Error Handling Code from "Regular" Code. .com
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
Checked exceptions:. A checked exception is some subclass of Exception (or Exception itself),
excluding class RuntimeException and its subclasses. Each methodmusteither handle all checked
exceptions by supplying a catch clause or list each unhandled checked exception as a thrown
exception.
Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked
exceptions. Class Error and its subclasses also are unchecked.
7) How does a try statement determine which catch clause should be used to handle an
exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. The first catch clause that is capable of
handling the exception is executed. The remaining catch clauses are ignored.
8) What is the purpose of the finally clause of a try-catch-finally statement? (NOV/DEC 2011)
The finally clause is used to provide the capability to execute code no matter whether or not an
exception is thrown or caught.
9) What is the difference between checked and Unchecked Exceptions in Java? All predefined
exceptions in Java are either a checked exception or an unchecked exception. Checked
exceptions must be caught using try.. catch () block or we should throw the exception using
throws clause. If you dont, compilation of program will fail.
What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return
statement encountered, and before the return executes.
14)
Wrapping the desired code in a try block followed by a catch block to catch the
exceptions.
List the desired exceptions in the throws clause of the method and let the caller of the
method handle those exceptions.
15) How to create custom exceptions?
By extending the Exception class or one of its subclasses.
Example:
class MyException extends Exception { public MyException() { super(); }
public MyException(String s) { super(s); }
}
16) Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.
17) What is the difference between swing and applet?
Swing is a light weight component whereas Applet is a heavy weight Component. Applet does
not require main method, instead it needs init method.
18) What is the use of assert keyword?
Assert keyword validates certain expressions. It replaces .theifblock
effectively and throws an AssertionError on failure. The assert keyword should be
used only for critical arguments (means without that the method does nothing). 19) How does
finallyblockdifferfromfinalize()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.theJVM just
before an object is garbage collected.
20) What is the difference between throw and throws clause?
throwis used to throw an exception manually, where as throws is
used in the case of checked exceptions, to tell the compiler that we haven't handled the
exception, so that the exception will be handled by the calling function.
21) What are the different ways to generate and Exception? There are two different ways to
generate an Exception.
1.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language
or the constraints of the Java execution environment.
2.
First event-delegation enables the handling of events by objects other than the ones which
generate the events. It is a clean separation between design and usage of a component.
Second It s performance is much better in applications in which many events are generated.
This improvement of performance is due to the fact that the unhandled events need not be
repeatedly processed, which is the case of event-inheritance model.
23)What happens if an exception is not caught? NOV/DEC 2010)
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup
being invoked, which eventually results in the termination of the program in which it is thrown.
24)Give any two methods available in stack trace element? NOV/DEC 2010)
getClassName
public String getClassName()
Returns the fully qualified name of the class containing the execution point represented
by this stack trace element.
Returns:
the fully qualified name of the Class containing the execution point represented by this
stack trace element.
getMethodName
public String getMethodName()
Returns the name of the method containing the execution point represented by this
stack trace element. If the execution point is contained in an instance or class initializer,
this method will return the appropriate special method name, <init> or <clinit
Returns:
the name of the method containing the execution point represented by this stack trace
element.
25)Write down the fundamentals of exception handling? NOV/DEC 2012)
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including the following:
A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at
the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors
generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
PART B
1.
2.
3.
4.
5.
6.
UNIT V
CONCURRENT PROGRAMMING
1) Explain different way of using thread?(MAY/JUNE 2011)
The thread could be implemented by using runnable interface or by inheriting from the Thread
class. The former is more advantageous, 'cause when you are going for multiple inheritance..the
only interface can help.
2) What are the different states of a thread ?
The different thread states are ready, running, waiting and dead.
3) Why are there separate wait and sleep methods?
The static Thread.sleep(long) method maintains control of thread execution but delays the next
action until the sleep time expires. The wait method gives up control over thread execution
indefinitely so that other threads can run.
4)
What is multithreading and what are the methods for inter-thread communication and
what is the class in which these methods are defined? (MQAY/JUNE 2011)
Multithreading is the mechanism in which more than one thread run independent of each other
within the process. wait (), notify () and notifyAll() methods can be used for inter-thread
communication and these methods are in Object class. wait() : When a thread executes a call to
wait() method, it surrenders the object lock and enters into a waiting state. notify() or
notifyAll() : To remove a thread from the waiting state, some other thread must make a call to
notify() or notifyAll() method on the same object.
5)
Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false
the thread was either new or terminated but there was simply no way to differentiate between the
two.
12) What is synchronized keyword? In what situations you will Use it? Synchronization is the
act of serializing access to critical sections of
code. We will use this keyword when we expect multiple threads to access/modify the same data.
To understand synchronization we need to look into thread execution manner.
When you expect your code will be accessed by different threads and
these threads may change a particular data causing data corruption.
Daemon thread is a low priority thread which runs intermittently in the back ground doing the
garbage collection operation for the java runtime system.
16) What is daemon thread and which method is used to create the daemon thread?
setDaemon method is used to create a daemon thread.
17) 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.
18) What is casting?
There are two types of casting, casting between primitive numeric types and casting between
object references. Casting between numeric types is used to convert larger values, such as double
values, to smaller values, such as byte values. Casting between object references is used to refer
to an object by a compatible class, interface, or array type reference.
19) What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
20) A Thread is runnable, how does that work?
The Thread class' run method normally invokes the run method of the Runnable type it is passed
in its constructor. However, it is possible to override the thread's run method with your own.
21) Can I implement my own start() method?
The Thread start() method is not marked final, but should not be overridden. This method
contains the code that creates a new executable thread and is very specialised. Your threaded
application should either pass a Runnable type to a new Thread, or extend Thread and override
the run() method.
22) Do I need to use synchronized on setValue(int)?
It depends whether the method affects method local variables, class static or instance variables. If
only method local variables are changed, the value is said to be confined by the method and is
not prone to threading issues.
23) What is thread priority?
which it should be executed with respect to others. The thread priority.comvalues ranging from
1- 10 and the default value is 5. But if a thread have higher priority doesn't means that it will
execute first. The thread scheduling depends on the OS.
Thread Priority is an integer value that identifies the relative order in
24) What are the different ways in which a thread can enter into waiting state?
There are three ways for a thread to enter into waiting state. By invoking
its sleep() method,.byblocking on I/O, by unsuccessfully attempting to acquire an object's lock,
or by invoking an object's wait() method.
25) How would you implement a thread pool? TheThreadPool class is a generic implementation
of a thread pool,
which takes the following input Size of the pool to be constructed and name of the class which
implements Runnable (which has a visible default constructor) and constructs a thread pool with
active threads that are waiting for activation. once the threads have finished processing they
come back and wait once again in the pool.
26) What is a thread group?
A thread group is a data structure that controls the state of collection of thread as a whole
managed by the particular runtime environment.
27)What is meant by notify methods in multithreading (nov/dec 2011)?
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 notifyAll so, sometimes it
is better to use notify than notifyAll.
Part B
1.
2.
3.
4.
5.