Object Oriented Programming Using Java
Object Oriented Programming Using Java
TEXT BOOKS
1. Herbert Schildt, “Java The complete reference”, 8th Edition, McGraw Hill Education, 2011.
2. Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, 9th Edition, Prentice
Hall, 2013.
REFERENCES
1. Paul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition, Pearson, 2015.
2. Steven Holzner, “Java 2 Black book”, Dreamtech press, 2011.
3. Timothy Budd, “Understanding Object-oriented programming with Java”, Updated Edition,
Pearson Education, 2000.
QUESTIONS
Q.N
O
1. Define Objects and classes in java.
Class is a template for a set of objects that share a common structure and a common
behaviour. A class is a blueprint, or prototype, that defines the variables and the methods
common to all objects of a certain kind.
import java.util.Vector;
class Test {
Vector vector;
Test() {
vector = new Vector();
}
}
3. What is the default access to a member in a class?
Default is no access specifier. For classes, and interface declarations, the default is package
private. This falls between protected and private, allowing only classes in the same package access.
(protected is like this, but also allowing access to subclasses outside of the package.
For interface members (fields and methods), the default access is public. But note that the
interface declaration itself defaults to package private.
4. What is a package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually
can think of packages as being similar to different folders on our computer.
Because software written in the Java programming language can be composed of hundreds or
thousands of individual classes, it makes sense to keep things organized by placing related classes
and interfaces into packages.
5. Define class.
Class is a template for a set of objects that share a common structure and a common behaviour. A
class is a blueprint, or prototype, that defines the variables and the methods common to all objects
of a certain kind.
{ /**
Javadoc utility enables you to keep the code and the documentation in sync easily. The
javadoc utility lets you put your comments right next to your code, inside your ".java"
source files.
All you need to do after completing your code is to run the Javadoc utility to create your
HTML documentation automatically.
● public
● protected
● default (no specifier)
● private
Private
Private methods and fields can only be accessed within the same class to which the methods
and fields belong. private methods and fields are not visible within subclasses and are not inherited by
subclasses. So, theprivate access specifier is opposite to the public access specifier. It is mostly used
for encapsulation: data are hidden within the class and accessor methods are provided. An example, in
which the position of the upper-left corner of a square can be set or obtained by accessor methods, but
individual coordinates are not accessible to the user.
● The Object’s behaviour – What can you do with this object , or what methods can you
apply to it?
● The Object’s state – How does the object react when you apply those methods?
● The Object’s identity – How is the object distinguished from others that may have the
same behaviour and state
finalize( ) method is used just before an object is destroyed and can be called just prior to
garbage collection.
An object has state (it has various properties, which might change).
An object has behavior (it can do things and can have things done to it).
16. What is Abstract class?
Abstract class is a class that has no instances. An abstract class is written with the
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 /**.
It ends with*/.
In Java have javadoc tags
Tag Meaning
@author Identifies the author of a class
@deprecated Specifies that a class or member is deprecated @param
Documents a method’s parameter
@return Documents a method’s return value
24. 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.
helps resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows protecting data from being used by the non-
authorized classes.
27. 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.
Q.NO QUESTIONS
(1) Concatenation
(2) Substrings.
Refer page no:53
(iii) Explain any four methods available in string handling.
Refer page no: 53
34. (i) Define package. Explain the types of package with its importance.
(ii) What is package? How to add a class into a package? Give example. Refer page
no:153
35. (i) Explain briefly about object oriented programming concepts differ from structured
programming concepts.
36. Write a java program for push and pop operations in stack using arrays in classes and
object.
Refer page no:90
(ii) What is meant by overriding method? Give example. Refer page no: 171
(iii) Write a JAVA program to reverse the given number. Refer notes
39. What is meant by package? How it is created and implemented in JAVA.
(ii) Write a JAVA program to find the smallest number in the given list. Refer page no:153
iv) Explain the term static fields and methods and explain its types with examples.
42. Define array. What is array sorting and explain with an example?
QUESTIONS
Q.N
O
1. What is meant by parameter passing constructors? Give example. NOV/DEC
2013
Parameter passing constructors are called Parameterized Constructors. Parameterized
Constructor is a constructor with parameters.
2. What is Constructor?
A constructor is a special method of a class or structure in object-oriented programming that
initializes an object of that type. A constructor is an instance method that usually has the same name
as the class, and can be used to set the values of the members of an object, either to default or to user-
defined values.
Definitions: A class that is derived from another class is called a subclass (also
a derived class, extended class, or child class). The class from which the subclass is derived is called
a superclass (also a base class or a parent class).
The idea of inheritance is simple but powerful: When you want to create a new class and there
is already a class that includes some of the code that you want, you can derive your new class from
the existing class. In doing this, you can reuse the fields and methods of the existing class without
having to write (and debug!) them.
To use an interface, we have to write a class that implements the interface. When an instantiable
class implements an interface, it provides a method body for each of the methods declared in the
interface.
This means that the Account class cannot be a superclass and the OverdraftAccount class can no longer
be its subclass.
8. What is Interface?
An interface is basically a kind of class. Like classes, interfaces contain methods and
variables but but with a major difference.The difference is that interfaces define only abstract
methods and final fields. This means that interfaces do not specify any code to implement these
methods and data fields contain only constants
9. What is object cloning?How to object clone? What is meant by object cloning?
It is the process of duplicating an object so that two identical objects will exist in the memory at
the same time.
In Java, Assign an object to another variable, only the memory address of the object is
copied and hence any changes in the original object will be reflected in the new variable.
Cloning means creating a copy of the object. The precise meaning of "copy" may depend on
the class of the object. The general intent is that, for any object x, the expression:
11. What are the conditions to be satisfied while declaring abstract classes?
An abstract class is a class that is incomplete, or to be considered incomplete.
those defined in methods are called inner classes. An inner class can have any
13. Can we override a super class method which is throwing an unchecked exception with
checked exception in the sub class?
No. If a super class method is throwing an unchecked exception, then it can be overridden in the
sub class with same exception or any other unchecked exceptions but can not be overridden with
checked exceptions.
14. What is meant by an innerclass?
An inner class is a nested class whose instance exists within an instance of its enclosing
class and has direct access to the instance members of its enclosing instance
class <EnclosingClass>
{
class <InnerClass>
{
}
}
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 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.
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.
21. 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.
22. Define superclass and subclass?
Superclass is a class from which another class inherits. Subclass is a class
that inherits from one or more classes.
23. 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 builtin
classes like Class, Method, Fields, and Constructors etc. Example: Using Java Reflection
API we can get the class name, by using the getName method.
● Single Inheritance.
● Multiple Inheritance (Through Interface)
● Multilevel Inheritance.
● Hierarchical Inheritance.
● Hybrid Inheritance (Through Interface)
Q.No Questions
ii) Explain about java building string functions with an example. Refer page no: 53
35. What is meant by constructor? Describe the types of constructors supported by Java with
example?
Refer page no: 144
Questions
Q.N
o
1. What is the use of final keyword?
The final keyword is used in several different contexts to define an entity which cannot later be
changed. the keyword final is a simple but powerful tool that allows us to write code that is
more readable, enables the compiler to catch some
logic errors, and prevents accidental misuse of classes and member functions.
If a method needs to be able to throw an exception, it has to declare the exception(s) thrown
in the method signature, and then include a throw-statement in the method. Here is
an example:
public void divide(int numberToDivide, int numberToDivideBy) throws
BadNumberException{
if(numberToDivideBy == 0){
throw new BadNumberException("Cannot divide by 0");
}
return numberToDivide / numberToDivideBy;
}
3. What is an exception?
Exceptions are such anomalous conditions (or typically an event) which changes the normal flow of
execution of a program. Exceptions are used for signaling
erroneous (exceptional) conditions which occur during the run time processing.
No. We shouldn’t write any other statements in between try, catch and finally blocks.
They form a one unit.
Checked exceptions are the exceptions which are known to compiler. These exceptions are checked at
compile time only. Hence the name checked
exceptions. These exceptions are also called compile time exceptions. Because, these exceptions
will be known during compile time.
Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions
occur only at run time. These exceptions are also called as run time exceptions. All sub classes of
java.lang.RunTimeException and java.lang.Error are unchecked exceptions.
8. What are run time exceptions in java. Give example?
The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run
time exceptions. These exceptions are unchecked type of exceptions. For example,
NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException, StackOverflowError etc.
9. There are three statements in a try block – statement1, statement2 and statement3. After that
there is a catch block to catch the exceptions occurred in the try block. Assume that exception
has occurred in statement2. Does statement3 get executed or not?
No. Once a try block throws an exception, remaining statements will not be executed. control comes
directly to catch block.
10. Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally
block. You can remove either catch block or finally block but not both
object;
3.close the file when we are finished reading from it.
OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out
of memory.
NullPointerException, ArrayIndexOutOfBoundsException,
NumberFormatException
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused
by the application itself. For example, NullPointerException occurs when an application tries to
access null object.
29. Give example for built in exception ?
Serializable
32. (i) Explain the concept of throwing and catching exception in java.
Refer page no:557 - 559
33. Explain briefly about user defined exceptions and stack trace elements in exception handling
mechanisms.
35. What is meant by exceptions? Why it is needed?Describe the exception hierarchy. Write note
on Stack Trace Elements. Give example.
36. I)Define exception and explain its different types with example
Refer page no:553
Questions
Q.N
o
1. What are the different states in thread? NOV/DEC 2010
● New: A new thread begins its life cycle in the new state. It remains in this state until
the
program starts the thread. It is also referred to as a born thread.
● Runnable: After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
thread waits for another thread to perform a task.A thread transitions back to the runnable
state only when another thread signals the waiting thread to continue executing.
● Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
● Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
2. What do you mean Synchronization?
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization. The
synchronized keyword in Java creates a block of code referred to as a critical section.
Every Java object with a critical section of code gets a lock associated with the object. To
enter a critical section, a thread needs to obtain the corresponding object's lock. This is
the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
3. Mention the two mechanisms for protecting a code block from concurrent access.
Java 5 introduces general purpose synchronizer classes, including semaphores, mutexes,
barriers, latches, and exchangers, which facilitate coordination between threads. These classes
are a apart of the java.util.concurrent package
A thread is a program's path of execution. Most programs written today run as a single thread,
causing problems when multiple events or actions need to occur at the
same time. Let's say, for example, a program is not capable of drawing pictures while reading
keystrokes. The program must give its full attention to the keyboard input lacking the ability to
handle more than one event at a time. The ideal solution to this problem is the seamless execution of
two or more sections of a program at the same time.
5. What is multithreading.
Multithreading enables us to write very efficient programs that make maximum use of the CPU,
because idle time can be kept to a minimum.
The Java Virtual Machine allows an application to have multiple threads of execution running
concurrently
Multithreaded applications deliver their potent power by running many threads concurrently within
a single program. From a logical point of view, multithreading means multiple lines of a single
program can be executed at the same time,
6. What is meant by notify methods in multithreading?
Used for Inter thread Communication:
To avoid polling, Java includes an elegant interprocess communication mechanism via the following
methods:
wait( ): This method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).
notify( ): This method wakes up the first thread that called wait( ) on the same object.
notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c The
highest priority thread will run first.
1) public Thread()
2) public Thread(String name)
3) Thread t1=new Thread();
4) Thread t2=newThread(“MYTHREAD”);
A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be
interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support
its own interruption.
name: the name of the thread (used mainly for logging or other diagnostics)
id: the thread's id (a unique, positive long generated by the system when the thread was created)
daemon: the thread's daemon status. A daemon thread is one that performs services for other
threads, or periodically runs some task, and is not expected to run to completion.
This is one of better interview question in Generics. Generics is implemented using Type
erasure, compiler erases all type related information during compile time and no type
related information is available during runtime. for example List<String> is represented by
only List at runtime. This was done to ensure binary compatibility with the libraries which
were developed prior to Java 5. you don't have access to Type argument at runtime and
Generic type is translated to Raw type by compiler during runtime.
17. How to write a generic method which accepts generic argument and return Generic
Type?
writing generic method is not difficult, instead of using raw type you need to use Generic
Type like T, E or K,V which are well known placeholders for
Type, Element and Key, Value. Look on Java Collection framework for examples of generics
methods. In simplest form a generic method would look like:
(or lock) in the same critical section to be executed.It is implemented by following methods
of Object class:
● wait()
● notify()
● notifyAll()
25. Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the
The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description
Q.No Questions
37. Explain the following (i) States of a thread with a neat diagram.
(ii) Thread priorities.
Refer page no:716 & 733
38. i) How to implement runnable interface for creating and starting threads?
ii) Define threads. Describe in detail about thread life cycle.
Questions
Q.N
o
1. What is virtual machine in generic programming?
name is followed by a type parameter section. As with generic methods, the type parameter
section of a generic class can have one or more type parameters separated by commas.
These classes are known as parameterized classes or parameterized types because they
accept one or more parameters.
3. Define the term virtual machine.
The fundamental idea behind a virtual machine is to abstract the hardware of a single computer (the
CPU, memory, disk drives, network interface cards, and so forth) into several different execution
environments, thereby creating the illusion that each separate execution environment is running its own
private computer.
T second )
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Using Java Generic concept we might write a generic method for sorting an array of objects, then
invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort
the array elements.
In HTML, refers to dividing the browser display area into separate sections, each of which is really a
different Web page.
getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
isDefaultButton()
Gets the value of the defaultButton property, which if true means that
this button is the current default button for its JRootPane.
isDefaultCapable()
paramString()
extends Object
implements WindowListener
The GridBagLayout class is a flexible layout manager that aligns components vertically and
horizontally, without requiring that the components be of the same size. Each GridBagLayout
object maintains a dynamic, rectangular grid of cells, with each component occupying one or
more cells, called its display area.
A Frame is a top-level window with a title and a border. The size of the frame includes any area
designated for the border. The dimensions of the border area may be obtained using the
getInsets method. Since the border area is included in the overall size of the frame, the border
effectively obscures a portion of the frame, constraining the area available for rendering and/or
displaying subcomponents to the rectangle which has an upper-left corner location
A frame, implemented as an instance of the JFrame class, is a window that has decorations such
as a border, a title, and supports button components that close or iconify the window.
Applications with a GUI usually include at least one frame
18. Give the value for the following predefined actions.
(a) SMALL-ICON - Place to store small icon, The icon for the action used in the tool bar or on a
button. You can set this property when creating the action using the AbstractAction(name, icon)
constructor.
(b) MNEMONIC-KEY - The mnemonic abbreviations, for display in menu items.
20. What method is used to distinguish between single, double and triple mouse clicks?
Button( )
Button( String str)
The first version creates an empty button. The second creates a button that contains str as a
label.
24. Distinguish between component and container
Component is an abstract class that encapsulates all of the attributes of a visual component.
All user interface elements that are displayed on the screen and that interact with the user
are subclasses of Component.
The container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. Other Container objects can be stored inside of a
container.
26. 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)
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.
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing
works faster than AWT.
29. 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
30. What is the difference between scrollbar and scrollpane?
Q.N QUESTIONS
O
31. Explain about the concepts of creating and positioning of frame
38. Give the methods available in graphics for COLOR and FONTS.