0% found this document useful (0 votes)
20 views25 pages

It2301 QB

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts, including definitions of classes, objects, inheritance, encapsulation, and polymorphism. It explains key features such as methods, access modifiers, constructors, garbage collection, and the differences between various Java constructs like arrays and vectors. Additionally, it covers Java's architecture, including the Java Virtual Machine (JVM), and details on GUI components, layout managers, and event handling in Java applications.

Uploaded by

narendranvel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views25 pages

It2301 QB

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts, including definitions of classes, objects, inheritance, encapsulation, and polymorphism. It explains key features such as methods, access modifiers, constructors, garbage collection, and the differences between various Java constructs like arrays and vectors. Additionally, it covers Java's architecture, including the Java Virtual Machine (JVM), and details on GUI components, layout managers, and event handling in Java applications.

Uploaded by

narendranvel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Department of Information Technology Francis Xavier Engineering College

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?
Class is a template for a set of objects that share a common structure and a common
behaviour.
3) What is an Object?
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 OOP‟s concepts?
Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP‟s 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 crisply-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.
7) 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?
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 the 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
method‟s signature is a combination of the first three parts mentioned above.
10) What are different types of access modifiers (Access specifiers)?
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 can‟t 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 the same package.
11) What is an Object and how do you allocate memory to it?

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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 it‟s “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 initializes 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 are 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 static
variables
21) What is finalize () method?
Finalize () method is used just before an object is destroyed and can be called just
prior to garbage collection.
22) What is the difference between String and String Buffer?
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.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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?
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.
UNIT II
1) What is meant by Inheritance?
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 one subclass 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.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

8) What is final modifier?


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?
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?
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?
Reflection allows Java code to discover information about the fields, methods
and constructors of loaded classes and to dynamically invoke them.
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, and 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 class
must have at least one abstract method and others may be concrete or abstract.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

b) In abstract class, key word abstract must be used for the methods whereas
interface we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can‟t 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?
Interface is similar to a class which may contain method‟s 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 more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an object‟s 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 or MARKER 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
 notifyAll
 wait (three versions)
25) Define: Dynamic proxy.
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:
 The class loader to define the proxy class
 An invocation handler to intercept and handle method calls
 A list of interfaces that the proxy instance implements
26) What is object cloning?
It is the process of duplicating an object so that two identical objects will exist in
the memory at the same time.
UNIT III
1) What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.
2) How would you create a button with rounded edges?
There‟s 2 ways. The first thing is to know that a JButton‟s edges are drawn by a
Border. so you can override the Button‟s 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
button‟s border to it.
3) What is the difference between the „Font‟ and „FontMetrics‟ class?

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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?
AWT are heavy-weight components. Swings are light-weight components. Hence
swing works faster than AWT.
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 I‟m not in a callback. If I want the
update to happen immediately (perhaps for a progress bar component) then I‟d use
invokeAndWait. If I don‟t care when the update occurs, I‟d 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

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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 won‟t the JVM terminate when I close all the application windows?
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 are components 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
applet‟s 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. 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.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

22) Explain how to render an HTML page using only Swing.


Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the
text into the 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 JComboBox‟s editor component.‟
24) 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.
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.
UNIT IV
GENERIC PROGRAMMING
1) What is an exception?
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?
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.
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 method
must either 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?

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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?


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 file, 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.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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 the if block 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 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.
20) What is the difference between throw and throws clause?
throw is 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.
Manually generated exceptions are typically used to report some error condition
to the caller of a method.
22) Where does Exception stand in the Java tree hierarchy?
 java.lang.Object
 java.lang.Throwable
 java.lang.Exception
 java.lang.Error
23) What is StackOverflowError?
The StackOverFlowError is an Error Object thorwn by the Runtime System when it
Encounters that your application/code has ran out of the memory. It may occur in case of
recursive methods or a large amount of data is fetched from the server and stored in some
object. This error is generated by JVM.
e.g. void swap(){
swap();
}
24) Explain the exception hierarchy in java.
The hierarchy is as follows: Throwable is a parent class off all Exception classes. They
are two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type
of exceptions extends Exception class
25) How do you get the descriptive information about the Exception occurred during the
program execution?
All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method as it
works its way down the call stack from the top.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

UNIT V
1) Explain different way of using thread?
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?
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?
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 difference 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 ?

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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.
16) What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back
ground doing the garbage collection operation for the java runtime system. 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

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

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?
Thread Priority is an integer value that identifies the relative order in which it
should be executed with respect to others. The thread priority values 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.
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, by blocking 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?
The ThreadPool 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.

16 MARK QUESTIONS AND ANSWERS

UNIT I
1. Explain briefly the following object oriented paradigms
i. abstraction and encapsulation (4)
An essential element of object-oriented programming is abstraction. Abstraction
refers to the act of representing essential features without including the background
details or explanations. Encapsulation is the mechanism that binds together code and
the data it manipulates, and keeps both safe from outside interference and misuse.
Types : function abstraction, data abstraction.
ii. Methods and messages (4)
Message: a request for execution of a procedure
Method: a receiving object that generates the desired result.
Benefits of messages.
iii. inheritance (4)
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical classification.
iv. Polymorphism (4)
Polymorphism means the ability to take more than one form. Subclasses of a class
can define their own unique behaviors and yet share some of the same functionality of
the parent class.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

2. i. How objects are constructed? Explain constructor overloading with an


example. (10)
Object Definition:
An object in java essentially a block of memory that contains space to store the
entire instance variable.
Creating an object is also referred to as instantiating an object.
Objects in java are created using the new operator.
Syntax:
Classname objectname=new objectname();
Example:
Student s1;
S1=new student (4,3);
Characteristics of objects
Initializing a object
Overloading Constructors: A class can have more than one constructor that has
the same name but different parameters. Example program

ii. Write short notes on access specifiers in java (6)


Java‟s access specifiers are
 Public
 Private
 Protected
 default access level.

3. What is a constructor? What is the use of new method? (4)


A constructor is a special method whose purpose is to construct and initialize
objects. Constructors always have the same name as the class name. The constructor
is automatically called immediately after the object is created, before the new
operator completes. A constructor can only be called in conjunction with the new
operator. You can't apply a constructor to an existing object to reset the instance
fields.

4. Give the syntax for static method and its initialization? (4)
Static methods are methods that do not operate on objects.
Static
{
// code
}
Example program
5. What is a class? How do you define a class in java? (4)
A class is a user-defined data type with a template that serves to define its properties.
The basic form of a class definition is:
Syntax:
Class classname [ extends superclassname]
{
Field declaration;

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

Method definition;
}
Instantiating a class
Accessing the members of a class.

6. Create a Class called Math that supports the following constants and methods.
(8)
a. pi=3.14159
b. Area of rectangle that is passed a height and a width.
c. perimeter of rectangle that is passed a height and width.
d. area of circle that is passed a radius
e. perimeter of circle that is passed a radius
class math
{
Const long pi=3.14154;
Void peri(int height,int width);
Void area(int height, int width);
Void peri(int radius);
Void area(int radius);
}
Class Mathtest
{
Public static void main(String args[])
{
Math m= new math();
m.peri(10,20);
m.area(10.20);
m.peri(20);
m.area(20);
}

6. Write note on Finalize method.


Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation. In some languages, such as C++, dynamically allocated objects must be
manually released by use of a delete operator. The finalize method will be called
before the garbage collector sweeps away the object.
Protected void finalize ()
{
// finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize () by


code defined outside its class.

7. Explain the types of constructors with an example for each? (16)

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

Types:
1. Default constructor
 Default field initialization
 Explicit field initialization
2. Parameterized constructor
8. Explain the basic concepts of object oriented programming with real time
example. (16)
1. object
2. class
3. data abstraction
4. encapsulation
5. inheritance
6. polymorphism
7. dynamic binding
8. message communication

UNIT II

1. What is a package? What are the benefits of using packages? Write down the
steps in creating packages and using it in a java program with an example.
(16)
Java allows you to group classes in a collection called a package. A class can use
all classes from its own package and all public classes from other packages. You
can import a specific class or the whole package. You place import statements at
the top of your source files (but below any package statements). For example, you
can import all classes in the java.util package with the statement: import
java.util.*;
Package scope
 Public features can be used by any class.
 Private features can only be used by the class that defines them.
 If you don't specify either public or private, then the feature (that is, the class,
method, or variable) can be accessed by all methods in the same package.
Advantages of Packages:
 Classes can be easily reused.
 Two classes in different packages can have same name.
 It provide a way to hide classes.

2. What is dynamic binding? Show with an example how dynamic binding


works. (16)
Dynamic binding means that the code with a given procedure calls is not known
until the time of the call at run-time.

3. Explain arrays in java? (8)


An array is a container object that holds a fixed number of values of a single type.
The length of an array is established when the array is created. After creation, its
length is fixed.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

 One dimensional array


 Declaring a Variable to Refer to an Array
 Creating, Initializing, and Accessing an Array
 Copying Arrays
 Anonymous arrays

4. Explain any our methods available in string handling? (4)


The String class is defined in the java.lang package and hence is implicitly
available to all the programs in Java. The String class is declared as final, which
means that it cannot be subclassed. It extends the Object class and implements the
Serializable, Comparable, and CharSequence interfaces.
Methods and Constructors of String Class:
public String(String value)
public String()
public String(char[] value)
public String(char[] value, int startindex, int len)

public int length()


equals()
public boolean equalsIgnoreCase(Object str)
public boolean startsWith(String prefix)
Public String substring(int startindex)
public String substring(int startindex, int endindex)
public String replace(char old_char, char new_char)
public String toUpperCase()
public String toLowerCase()
5. Explain concatenation and substrings w.r.t java. (4)
Concatenation
The + operator is used to concatenate two strings, producing a new String object as
the result. For example,
String sale = "500";
String s = "Our daily sale is" + sale + "dollars";
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars".
The + operator may also be used to concatenate a string with other data types. For
example,

int sale = 500;


String s = "Our daily sale is" + sale + "dollars";
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars". In this case, the
variable sale is declared as int rather than String, but the output produced is the same.
This is because the int value contained in the variable sale is automatically converted
to String type, and then the + operator concatenates the two strings.
Substrings

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

The substring() method creates a new string that is the substring of the string that
invokes the method. The method has two forms:
public String substring(int startindex)
public String substring(int startindex, int endindex)
where, startindex specifies the index at which the substring will begin and endindex
specifies the index at which the substring will end. In the first form where the
endindex is not present, the substring begins at startindex and runs till the end of the
invoking string.

6. Explain inheritance and class hierarchy? (4)


The term inheritance refers to the fact that one class can inherit part or all of its
structure and behavior from another class. The class that does the inheriting is
said to be a subclass of the class from which it inherits. If class B is a subclass of
class A, we also say that class A is a superclass of class B.
Class Hierarchy: the collection of all classes extending from a common super
class is known as class hierarchy.
7. Write briefly about abstract classes with an example. (8)
An abstract class is one that is not used to construct objects, but only as a basis for
making subclasses. An abstract class exists only to express the common properties of
all its subclasses. A class that is not abstract is said to be concrete. You can create
objects belonging to a concrete class, but not to an abstract class. A variable whose
type is given by an abstract class can only refer to objects that belong to concrete
subclasses of the abstract class.
Example: Shape Class with a draw function to draw shapes like rectangle, square,
triangle, round rectangle etc…
8. Write a program in Java which finds the sum of two arrays given below. (4)
A=1 2 3 4
2 3 4
5 6
A=4 3 2 1
3 2 1
2 1
9. State the design hints of inheritance. (8)
1. Place common operations and fields in the superclass.
2. Don‟t use protected fields.
3. Use inheritance to model the “is–a” relationship.
4. Don‟t use inheritance unless all inherited methods make sense.
5. Don‟t change the expected behavior when you override a method.
6. Use polymorphism, not type information.
7. Don‟t overuse reflection

9. Explain the various types of Inheritance with example? (10)


Inheritance
Definition
Extending classes
Using super

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

Advantages
Types
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hierarchical inheritance
e. Hybrid inheritance
11. Explain polymorphism in detail? (16)
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object.
 Method overloading
 Method overriding
12. Discuss the various methods of java documentation. (8)
Java supports three types of comments. The first two are the // and the /* */. The
third type is called a documentation comment. It begins with the character
sequence /** and it ends with */.
Documentation comments allow you to embed information about your program
into the program itself. You can then use the javadoc utility program to extract the
information and put it into an HTML file.
Documentation comments make it convenient to document your programs.
Tag Description Example
@author Identifies the author of a class. @author description
Specifies that a class or member is
@deprecated @deprecated description
deprecated.
Specifies the path to the root
{@docRoot} directory of the current Directory Path
documentation
Identifies an exception thrown by a @exception exception-name
@exception
method. explanation
Inherits a comment from the Inherits a comment from the
{@inheritDoc}
immediate superclass. immediate surperclass.
Inserts an in-line link to another
{@link} {@link name text}
topic.
Inserts an in-line link to another
Inserts an in-line link to another
{@linkplain} topic, but the link is displayed in a
topic.
plain-text font.
@param parameter-name
@param Documents a method's parameter.
explanation
@return Documents a method's return @return explanation

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

value.
@see Specifies a link to another topic. @see anchor
Documents a default serializable
@serial @serial description
field.
Documents the data written by the
@serialData writeObject( ) or writeExternal( ) @serialData description
methods
Documents an ObjectStreamField @serialField name type
@serialField
component. description
States the release when a specific
@since @since release
change was introduced.
The @throws tag has the same
@throws Same as @exception.
meaning as the @exception tag.
Displays the value of a constant, Displays the value of a constant,
{@value}
which must be a static field. which must be a static field.
@version Specifies the version of a class. @version info

13. Write a java program to implement matrix multiplication. (8)


import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();

if ( n != p )

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

System.out.println("Matrices with entered orders can't be multiplied with each other.");


else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}

14. Define ragged arrays with an example. (4)


It is an array with more than one dimension each dimension has different size
Example :
10 20 30
11 22 22 33 44
77 88

UNIT III
1. What is object cloning? Why it is needed? Explain how objects are cloned?
(16)
A clone of an object is a new object that has the same state as the original. In
particular, you can modify the clone without affecting the original.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

Types of cloning: Deep Copy, Shallow copy


Example program

2. How is a Frame created? Write a Java Program that creates a product


enquirer form using frames? (16)
Frame creation:
Jframe frame= new Jframe(“ Frame”);
Frame.setsize(200,200);
Frame.setvisible(true);

3. What is a static inner class? Explain with an example. (8)


It is an inner class which is used to hide one class inside another, but the inner
class to have reference to the outer class is not needed.
 General Form
 Properties
 Example program

4. Explain the cloneable interface with an example. (8)


 Definition of a clone
 Example program
5. Give the methods available in graphics for COLOR (4)
Color c = new Color(int red, int green, int blue)
Setpaint()
Fill()
Setbackground()
Setforeground()

6. List the methods available to draw shapes. (4)


 Line
 Rectangle
 Ellipse
 Arc
 Point

7. Explain interfaces, its properties. Write a java program for sorting an


employee array. (6)
It is a way of describing what classes should do, without specifying how they
should do it.
 Defining an Interface
 Properties
 Interfaces and abstract classes
 Interfaces and callbacks
Example program: sorting an employee
8. Write a java program to draw a polygon(4)
polygon of three sides:
for (int i = 0; i < 3; i++){

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

polygon1.addPoint((int) (40 + 50 * Math.cos(i *


2 * Math.PI / 3)),
(int) (150 + 50 * Math.sin(i * 2 * Math.PI /
3)));}
g.drawPolygon(polygon1);

9. Explain briefly the various stream classes with suitable examples. (6)
 Byte stream
o Input stream
o Output stream
 Character stream
o Reader class
o Writer class

10. Explain the usage of reflection in detail. (16)


a. Analyse objects at runtime
b. Analyze the capabilities of class
c. Implement generic array manipulation code

11. Explain proxies in detail? (8)


A dynamic proxy class (simply referred to as a proxy class below) is a class that
implements a list of interfaces specified at runtime when the class is created, with
behavior as described below. A proxy interface is such an interface that is implemented
by a proxy class. A proxy instance is an instance of a proxy class. Each proxy instance
has an associated invocation handler object, which implements the interface
InvocationHandler. A method invocation on a proxy instance through one of its proxy
interfaces will be dispatched to the invoke method of the instance's invocation handler,
passing the proxy instance, a java.lang.reflect.Method object identifying the method that
was invoked, and an array of type Object containing the arguments. The invocation
handler processes the encoded method invocation as appropriate and the result that it
returns will be returned as the result of the method invocation on the proxy instance.
A proxy class has the following properties:
 Proxy classes are public, final, and not abstract.
 The unqualified name of a proxy class is unspecified. The space of class names
that begin with the string "$Proxy" should be, however, reserved for proxy classes.
 A proxy class extends java.lang.reflect.Proxy.
 A proxy class implements exactly the interfaces specified at its creation, in the
same order.
 If a proxy class implements a non-public interface, then it will be defined in the
same package as that interface. Otherwise, the package of a proxy class is also
unspecified. Note that package sealing will not prevent a proxy class from being
successfully defined in a particular package at runtime, and neither will classes
already defined by the same class loader and the same package with particular
signers.

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

 Since a proxy class implements all of the interfaces specified at its creation,
invoking getInterfaces on its Class object will return an array containing the same
list of interfaces (in the order specified at its creation), invoking getMethods on its
Class object will return an array of Method objects that include all of the methods
in those interfaces, and invoking getMethod will find methods in the proxy
interfaces as would be expected.
 The Proxy.isProxyClass method will return true if it is passed a proxy class-- a
class returned by Proxy.getProxyClass or the class of an object returned by
Proxy.newProxyInstance-- and false otherwise.
 The java.security.ProtectionDomain of a proxy class is the same as that of system
classes loaded by the bootstrap class loader, such as java.lang.Object, because the
code for a proxy class is generated by trusted system code. This protection
domain will typically be granted java.security.AllPermission.

12. Explain inner classes and its types in detail. (16)


o Definition
o General form
o Using an inner class to access object state
o Special syntax rules
o Types
 Local inner classes
 Anonymous inner classes
 Static inner classes
o Properties

UNIT IV
1. Explain generic classes and methods.
 They are static methods that can be invoked for all methods.
 Generic classes are classes that can be used for all types of values
2. Explain exception hierarchy.
Try
Catch
Throw
Throws
finally
3. What are the advantages of Generic Programming?
 To be specified later types
 That are instantiated when needed for specific types
4. Explain the different ways to handle exceptions.
Checked exceptions
Unchecked exceptions
5. Explain the model view controller design pattern and list the advantages and
disadvantages.
 Model
 View

http://www.francisxavier.ac.in
Department of Information Technology Francis Xavier Engineering College

 Controller

UNIT V
1. Explain the different states of a thread.
 Newborn
 Runnable
 Running
 Waiting
 Timed waiting
 Death state

2. Explain thread synchronization with examples.


 Semaphore
 Mutexes
 Barriers
 Latches
 exchangers
3. Explain how to create threads
 Implementing the runnable interface
 Extending the thread class.
4. Describe multi threading.
 A specialized form of multitasking.
 Multitasking threads require less overhead than multitasking
processes.
5. Explain thread properties
Daemon threads
Thread group
Thread priority

http://www.francisxavier.ac.in

You might also like