Nandha Engineering College, Erode - 52 (Autonomous) Department of Computer Science & Engineering Cs2305-Programming Paradigms

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

NANDHA ENGINEERING COLLEGE, ERODE 52

(Autonomous)
Department of Computer Science & Engineering
CS2305- PROGRAMMING PARADIGMS
2-MARK Questions and Answers
UNIT I
OBJECT-ORIENTED PROGRAMMING FUNDAMENTALS
1)

What is meant by Object Oriented Programming?


OOP is a method of programming in which programs are organised as
cooperative collections of objects. Each object is an instance of a class
and each class belong to a hierarchy.

2)

What is a Class?

(NOV/DEC 2010)

Class is a template for a set of objects that share a common structure


and a common behaviour.
defined conceptual boundaries relative to the perspective of the viewer. Its
the process of focussing on the essential characteristics of an object.
Abstraction is one of the fundamental elements of the object model.
3)

What is an Object?

(NOV/DEC 2010)

Object is an instance of a class. It has state,behaviour and identity. It is


also called as an instance of a class.
4)

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)

What are the core OOPs concepts?


Abstraction, Encapsulation,Inheritance and Polymorphism are the core
OOPs concepts.

6) What is meant by abstraction?


Abstraction defines the essential characteristics of an object that
distinguish it from all other kinds of objects. Abstraction provides crisply7)

What is meant by Encapsulation?


Encapsulation is the process of compartmentalising the elements of an
abtraction that defines the structure and behaviour. Encapsulation helps to
separate the contractual interface of an abstraction and implementation.

8)

What are Encapsulation, Inheritance and Polymorphism?

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

What is a constructor? What is a destructor?

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)

What is the difference between constructor and method?

Constructor will be automatically invoked when an object is created


whereas method has to be called explicitly
17)

What is Static member classes?

A static member class is a static member of a class. Like any other


static method, a static
member class has access to all static methods of
the parent, or top-level, class.
18)

What is Garbage Collection and how to call it explicitly?

When an object is no longer referred to by any variable, java automatically reclaims


memory used by that object. This is known as garbage collection. System. gc() method may be
used to call it explicitly
19)

In Java, How to make an object completely encapsulated?

All the instance variables should be declared as private and public getter and
setter methods should be provided for accessing the instance variables.
20)

What is static variable and static method?

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)

What is finalize() method?

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

a)String objects are constants and immutable whereas

StringBuffer objects are not.

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.

28)Write any four string functions.


Strlen (stringvar), strcmp,equals,equalsIgnorecase are some of the string functions.
29) Write the types of constructor.
Default constructor,Parameterized constructor and copy constructor.

30)What are the relationship between classes.


Dependence ,Aggregation and inheritance are the relationship between classes.
Dependence : A class depends on another class if its methods use or manipulate objects of that
class.
Aggregatioin:This means the has- a relationship.Cointainment means objects of one class
contain object of other class.
Inheritance:This means the is- a relationship.It represents the relation between a more special
and general class.
31)What is the default access to a member in a class?(May/June 2011)
When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.

32)What do you mean by instance variable?(May /June 2012)


A class or object can have it's own variables. In Java, these are called instance variables. By its
definition, an instance variable is unique to each instance of the class; so in general, each time a
class is "instantiated" with the new operator, there is another variable associated with it.
These variables are declared outside any methods you may have. These variables are declared
either public, private or protected. They are global to the class or object they appear in. Let's see
a small example.
public class Variables{
private int x = 0;
public Variables(){
x++;
System.out.println("Welcome! " + x); }
public static void main(String args[]){

Variables var1 = new Variables(); }}

In this example, the instance variable x is declared private. In addition, it is global to


the Variables object.

33)What is the need for Java doc multiline comments?(NOV/DEC 2011)


Java's multi-line or slash-star or traditional comment is a piece of text enclosed in slash-star (/*)
and star-slash (*/). Again there should be no white space between slash and star. Java's multi-line
comments are useful when the comment text does not fit into one line; therefore needs to span
across lines. Slash-star comments are the only choice when a comment needs to be inserted in
middle of the code line. For example:

// CommentDemo.java
// Demonstrating multi-line comments
public class CommentDemo
{ public static void main(String[] args)
{

for (int i = 0; i < 5; /* exits when i reaches to 5 */ i++)


{

OUTPUT

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

} }}

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

Comments should not be nested, especially slash star comments

Comments surrounded by double quotes are processed as string literals

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.

Be aware of Unicode characters in Java 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) {

Test obj1=new Test();


Test obj2=new Test();
obj1.a=10;
obj2.a=12;
obj1.b=24;
obj2.b=36;
System.out.println("Static a"+obj1.a); //12
System.out.println("Static a"+obj2.a); //12
System.out.println("Static a"+a); //12
System.out.println("Static b"+obj1.b); //24
System.out.println("Static b"+obj2.b); //36
}
35)How dynamic initialization of variables achieved in java(NOV/DEC 2012)
Initialization is the process of providing value to a variable at declaration time. A variable is initialized
once in its life time. Any attempt of setting a variable's value after its declaration is called assignment. To
use a local variable you have to either initialize or assign it before the variable is first used. But for class
members, the compulsion is not so strict. If you don't initialize them then compiler takes care of the
initialization process and set class members to default values.
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is
called dynamic initialization. The following piece of code (DynamicInitializationDemo.java)
demonstrates it.
/* DynamicInitializationDemo.java */
public class DynamicInitializationDemo
{
public static void main(String[] args)
{
//dynSqrt will be initialized when Math.sqrt
//will be executed at run time
double dynSqrt = Math.sqrt (16);
System.out.println("sqrt of 16 is : " + dynSqrt);
}
}
OUTPUT
======

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.

7) What is Dynamic Binding?


Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given
procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.

8) What is final modifier?(NOV/DEC 2011)


The final modifier keyword makes that the programmer cannot change the value anymore. The
actual meaning depends on whether it is applied to a class, a variable, or a method.

final Classes- A final class cannot have subclasses.


final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.
9) 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.
10) What are inner class and anonymous class? (NOV/DEC 2011)

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

14) Define superclass and subclass?


Superclass is a class from which another class inherits. Subclass is a class that inherits from one
or more
classes.

15) What is meant by Binding, Static binding, Dynamic binding?


Binding: Binding denotes association of a name with a class.
Static binding: Static binding is a binding in which the class association is made during compile
time. This is also called as Early binding. 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.

16) What is reflection API? How are they implemented?


Reflection is the process of introspecting the features and state of a class
at runtime and dynamically manipulate at run time. This is supported using Reflection API with
built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API
we can get the class name, by using the getName method.
17) What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are . associated with instances of the
class's outer class. A static inner class does not have any object instances.
18) What is the difference between abstract class and interface?
a) All the methods declared inside an interface are abstract whereas abstract.classmust have at
least one abstract method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods where as interface we need
not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface cant have subclasses.
19)

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)

What is interface and its use? NOV/DEC 2011)

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.

21) How is polymorphism acheived in java?


Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.

22) What modifiers may be used with top-level class?


public, abstract and final can be used for top-level class.
23) What is a cloneable interface and how many methods does it contain? It is not having any
method because it is a TAGGED orMARKER interface.

24) What are the methods provided by the object class?


The Object class provides five methods that are critical when writing multithreaded Java
programs:

notify com

notifyAll

wait (three versions)

25) Define: Dynamic proxy. .

The class . loader to define the proxy class

A dynamic proxy is a class that implements a list of interfaces, which you


specify at runtime when you create the proxy. To create a proxy, use the static method
java.lang.reflect.Proxy::newProxyInstance(). This method takes three arguments:
An invocation handler to intercept and handle method calls
A list of interfaces that the proxy instance implements
26) What is object cloning? (NOV/DEC2011)
It is the process of duplicating an object so that two identical objects will exist in the memory at
the same time. The object cloning is a way to create exact copy of an object. For this purpose,
clone() method of Object class is used to clone an object.The java.lang.Cloneable interface must
be implemented by the class whose object clone we want to create. If we don't implement
Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
use clone() method :
The clone() method saves the extra processing task for creating the exact copy of an object. If we
perform it by using the new keyword, it will take a lot of processing to be performed that is why
we use object cloning.

Advantage of Object cloning


Less processing task.
Example of clone() method (Object cloning)
Let's see the simple example of object cloning
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Output:101 amit
101 amit
27)What is meant by abstract class?(NOV?DEC 2011)
An abstract class is a class that is declared abstractit may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}

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.

28) How to prevent inheritance?(May/June 2011)


Using final to Prevent Inheritance
Declaring a class as final implicitly declares all of its methods as final. So it prevents
a class from being inherited. To do this, precede the class declaration with final.
It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final
class: final class A
{
// ...
}
// The following class is illegal.
class B extends A
{ // ERROR! Can't subclass A
// ...
}
29)Differentiate between copying and cloning.(MAY/JUNE 2011)
COPYING:
instance an Array:
int [] numbers = { 2, 3, 4, 5};
int [] numbersCopy = numbers;
The numbersCopy array now contains the same values, but more importantly the array object
itself points to the same object reference as the numbers array.
numbersCopy[2] = 0;
the output for the following statements?
System.out.println(numbers[2]);
System.out.println(numbersCopy[2]);
Considering both arrays point to the same reference the ouput is
0
0
CLONING
to make a distinct copy of the first array with its own reference
To clone the array, each array have its own object reference.
int [] numbers = { 2, 3, 4, 5};

int [] numbersClone = (int[])numbers.clone();


The numbersClone array now contains the same values, but in this case the array object itself
points a different reference than the numbers array.
numbersClone[2] = 0;
the output now for the following statements:
System.out.println(numbers[2]);
System.out.println(numbersClone[2]);
OUTPUT:
4
0
30)What is meant by dynamic method dispatch?(NOV/DEC 2011)
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how
java implements runtime polymorphism. When an overridden method is called by a reference, java determines which
version of that method to execute based on the type of object it refer to. In simple words the type of object which it
referred determines which version of overridden method will be called.

31)What is meant by inheritance hierarch?( NOV/DEC 2011)


The collection of all classes extending from a common superclass is called an
inheritance hierarchy; the path from a particular class to its ancestors in the inheritance
hierarchy is its inheritance chain.
Simple class hierarchies consist of only a superclass and a subclass. But you can
build hierarchies that contain as many layers of inheritance as you like.
For example, create three classes called A, B, and C, C can be a subclass of B, which
is a subclass of A. When this type of situation occurs, each subclass inherits all of the traits
found in all of its superclasses. In this case, C inherits all aspects of B and A.
32)Can an abstract class be declared final?Why?(nov/dec 2011)
No a class cannot be marked "abstract" as well as "final".Making a class "abstract" means
it contains partial implementation of methods and hence depends on its subclasses to provide

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.

7) Difference between Swing and Awt?

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.

9) How are the elements of different layouts organized?


FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right
fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East
and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked,
on top of the other, like a deck of cards.

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.

10) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?


I want to update a Swing component but Im not in a callback. If I want the update to happen
immediately (perhaps for a progress bar component) then Id use invokeAndWait. If I dont care
when the update occurs, Id use invokeLater.

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

12) What is the difference between scrollbar and scrollpane?


A Scrollbar is a Component, but not a Container whereas.Scrollpane is a
Conatiner and handles its own events and perform its own scrolling.

13) Why wont the JVMterminatewhenIclosealltheapplicationwindows?


The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to
terminate the JVM.

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.

These controls are subclasses of Component.


15) What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of
available choices. Only one item may be selected from a Choice. A List may be displayed in such
a way that several List items are visible. A List supports the selection of one or more List items.
16) What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally,an event
is enabled when a listener is added to an object for a particular event. The enableEvents() method
is used by objects that handle events by overriding their eventdispatch methods.
17) 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.
18) What is the lifecycle of an applet?
init() method - Can be called when an applet is first loaded start() method - Can be called each
time an applet is started. paint() method - Can be called when the applet is minimized or
maximized. stop() method - Can be used when the browser moves off the applets page. destroy()
method - Can be called when the browser is finished with the applet.
19) What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be
checked or unchecked.
20) 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.
21) What is source and listener?
source : A source is an object that generates an event. This.occurs when
the internal state of that object changes in some way.
listener : A listener is an object that is notified when an event occurs. It has two
major requirements.rejinpaulFirst,itmusthavebeenregisteredwithoneormore sources to receive
notifications about specific types of events. Second, it must

implement methods . to receive and process these notifications.


22) Explain how to render an HTML page using only Swing.
Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then wwwloadthetextintothe
pane.
23) How would you detect a keypress in a JComboBox?
This is a trick. most people would say add a KeyListener to the JComboBox - but the right
answer is add a KeyListener to the JComboBoxs editor component.
24) What an I/O filter?(NOV/DEC 2012)
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.
25) How can I create my own GUI components?
Custom graphical components can be created by producing a class that inherits from
java.awt.Canvas. Your component should override the paint method, just like an applet does, to
provide the graphical features of the component.
26)How are frames created in Java? (apr/may 2011)
Frame is a top-level window that has a title bar, menu bar, borders, and
resizing corners. By default, a frame has a size of 0 0 pixels and it is not
visible.Frames are examples of containers. It can contain other user interface
components such as buttons and text fields.
Frames can be created by using the Frame class.
Syntax : Frame f = ne Frame ( );
27) State the function of action in event handler. (apr/may 2011)
An action is an object that encapsulates
A Description of the command(as a text string and an optional icon)and
Parameters that are necessary to carry out the command(Such as requested Color in our
example).
The Swing package provides very useful mechanism to encapsulate commands and to attach
them to multiple event sources.
An Action can be used to separate functionality and state from a component. For example, if
you have two or more components that perform the same function, consider using an Action
object to implement the function. An Action object is an action listener that provides not only
action-event handling, but also centralized handling of the state of action-event-firing
components such as tool bar buttons, menu items, common buttons, and text fields. The state
that an action can handle includes text, icon, mnemonic, enabled, and selected status.

UNIT III
EVENT-DRIVEN PROGRAMMING

1.
2.
3.
4.
5.
6.

. Explain the classes under 2D shapes.


Explain event handling with examples.
Explain action event with an example.
What are the swing components. Explain.
Describe the AWT event hierarchy.
Explain about Model view controller.

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

Propagating Errors Up the Call Stack.

Grouping Error Types and Error Differentiation.

5) What are the types of Exceptions in Java

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.

6) Why Errors are Not Checked?


A unchecked exception classes which are the error classes (Error and its subclasses) are
exempted from compile-time checking because they can occur at many points in the program and
recovery from them is difficult or impossible. A program declaring such exceptions would be
pointlessly.

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.

10) What is the difference between exception and error?


The exception class defines mild error conditions that your program encounters. Exceptions can
occur when trying to open the comfile,which does not exist, the network connection is disrupted,
operands being.manipulated are out of prescribed ranges, the class file you are interested in
loading is
missing. The error class defines serious error conditions that you should not attempt to recover
from. In most cases it is advisable to let the program terminate when such an error is
encountered.
11) What is the catch or declare rule for method declarations?
If a checked. exception may be thrown within the body of a method, the method must either
catch the exception or declare it in its throws clause.
12) When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of
execution terminates or an exception occurs within the execution of the finally clause.
13)

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)

What are the different ways to handle exceptions?

There are two ways to handle exceptions:

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 can be generated by the Java run-time system.

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.

Exceptions can be manually generated by your code.

22)What are the advantages of event delegation model?(NOV/DEC 2010)


There are two advantages of event-delegation model over event-inheritance model.

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 user has entered invalid data.

A file that needs to be opened cannot be found.

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:

Checked exceptions: A checked exception is an exception that is typically a user error or a


problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file
cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of
compilation.

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.

26)What is AWT? NOV/DEC 2012)


Abstract Window Toolkit (AWT) is a set of application program interfaces ( API
s) used by Java programmers to create graphical user interface ( GUI ) objects, such as buttons,
scroll bars, and windows. AWT is part of the Java Foundation Classes ( JFC ) from Sun
Microsystems, the company that originated Java. The JFC are a comprehensive set of GUI class
libraries that make it easier to develop the user interface part of an application program.
A more recent set of GUI interfaces called Swing extends the AWT so that the programmer can
create generalized GUI objects that are independent of a specific operating system's windowing
system .
UNIT IV

PART B
1.
2.
3.
4.
5.
6.

Explain generic classes and methods.


Explain exception hierarchy.
What are the advantages of Generic Programming?
Explain the different ways to handle exceptions.
How Java handle overflows and underflows?
. Explain about Assertion and Logging.

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)

What is synchronization and why is it important? (MAY/JUNE 2012)(NOV/DEC 2010)

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 leads to
significant errors.
6) How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly
switching between executing tasks, it creates the impression that tasks execute sequentially.

7) What is the differencel between process and thread?


Process is a program in execution whereas thread is a separate path of
execution in a program.

8) What happens when you invoke a thread's interrupt method while it


is sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the
task enters the running state, an InterruptedException is thrown.
9) How can we create a thread?
A thread can be created by extending Thread class or by implementing Runnable interface. Then
we need to override the method public void run().
10) 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 I/O, 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.
11) How can i tell what state a thread is in ?

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.

13) What is serialization?


Serialization is the process of writing complete state of java object into output stream, that
stream can be file or byte array or stream associated with TCP/IP socket.
14) What does the Serializable interface do?
Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable
data type to the tagged class and to identify the class as one which the developer has designed
for persistence. ObjectOutputStream serializes only those objects which implement this interface.

15) When you will synchronize a piece of your code?

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.

Explain the different states of a thread.


Explain thread synchronization with examples.
Explain the algorithm used for thread scheduling.
Describe multi threading.
Explain Deadlocks.

You might also like