You are on page 1of 62

St.

Thomas
Institute For Science and Technology
Trivandrum

Department of Computer Science and Engineering

Object Oriented Design and Programming


S3 CSE
Module Wise (Modules 3 and 4)
(Important Topics)

Kerala Technological University

St.Thomas Institute For Science and Technology - S3 CSE OOD 1


Downloaded from Ktunotes.in
Module 3

Downloaded from Ktunotes.in


Q. Explain interfaces in Java with an example or How java inco-operate the concept of multiple
inheritance or How java supports dynamic method resolution at run time.

• Java use the concept of interfaces to achieve multiple inheritance.


• Using interface, we can specify what a class must do, but not how it does it.
• Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are
declared without any body(abstract methods).
• Once it is defined, any number of classes can implement an interface. Also, one class can implement any
number of interfaces.
• To implement an interface, a class must create the complete set of methods declared by the interface.
However, each class is free to determine the details of its own implementation.
• By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
• Interfaces are designed to support dynamic method resolution at run time. They disconnect the definition
of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different
hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to
implement the same interface

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Implementing interfaces
• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then define the
methods listed by the interface.
• The general form of a class that includes the implements clause looks like this:

• The methods that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface definition.

Downloaded from Ktunotes.in


Q. Write a java program to create and interface named Polygon that contains an abstract method void
getArea( int length, int breadth). Create a class named rectangle to implement the interface and define
the getArea() function

Downloaded from Ktunotes.in


Q. Explain packages in Java.
• A package as the name suggests is a pack(group) of classes, interfaces and other packages.
• In java we use packages to organize our classes and interfaces. We have two types of packages in
Java: built-in packages and the packages we can create (also known as user defined package).

Example: Built in Packages : java.awt, java.io, java.lang, java.util

Downloaded from Ktunotes.in


Defining user defined packages in java
• To create a class inside a package, declare the package name in the first statement in the
program using the keyword package.
• A class can have only one package declaration

Example: A package that contains a class consisting of a method add() for adding two functions
In the first line the package name is
given “letmecalculate”

Downloaded from Ktunotes.in


Using a package
• Packages are imported to a java program using the keyword “import”
• The previously created package letmecalculate is imported in the below given program

• In the above program we have imported the package as letmecalculate.Calculator, this only
imports the Calculator class.
• However if there are several classes inside package letmecalculate then we can import the
package like this, to use all the classes of this package

Downloaded from Ktunotes.in


Q. List some of the built in packages in java.

Downloaded from Ktunotes.in


Q. Explain how Classpath is set to use packages.

• Packages are mirrored by directories


• Java Run Time system find the packages we create as follows:
• By default, the Java run-time system uses the current working directory as its starting point.Thus, if the package is in a
subdirectory of the current directory, it will be found.
• Second, we can specify a directory path or paths by setting the CLASSPATH environmental variable.
• Third, we can use the -classpath option with java and javac to specify the path to program classes.
• Example : Assume we have created a package as: package MyPack
• In order for a program to find MyPack, one of three things must be true.
• The program can be executed from a directory immediately above MyPack,
• The CLASSPATH must be set to include the path to MyPack
• The –classpath option must specify the path to MyPack when the program is run via java.
• When the second two options are used, the class path must not include MyPack, itself. It must simply
specify the path to MyPack. For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is Compile package
C:\MyPrograms\Java javac C:\MyPrograms\Java\MyPack\Classname.java

Downloaded from Ktunotes.in


Q. Explain the access controls/ access modifiers with respect to packages.

Downloaded from Ktunotes.in


Private

Default

Downloaded from Ktunotes.in


protected

Downloaded from Ktunotes.in


public

Downloaded from Ktunotes.in


Q. Explain Keywords in java used for Exception Handling
Keywords Description Syntax
try Program statements that we want to monitor for try
exceptions are contained within a try block. If an {…..//staments
exception occurs within the try block, it is thrown. }

catch Code can catch this exception (using catch) and handle catch(Exception obj)
it in some rational manner. System-generated {
exceptions are automatically thrown by the Java …//statements
runtime system }
throw To manually throw an exception, use the keyword throw throw throwableinstance

throws Any exception that is thrown out of a method must be throws ExceptionType
specified as such by a throws clause

finally Any code that absolutely must be executed after a try finally
block completes is put in a finally block. {
…..
}
Downloaded from Ktunotes.in
Q. Describe in detail about exception handling, try block and catch clause with the help of a suitable
Java program.

try Program statements that we want to monitor try


for exceptions are contained within a try {…..//staments
block. If an exception occurs within the try }
block, it is thrown.

catch Code can catch this exception (using catch) catch(Exception obj)
and handle it in some rational manner. {
System-generated exceptions are …//statements
automatically thrown by the Java runtime }
system. The details of exception will be
stored in an Exception object obj.

Downloaded from Ktunotes.in


Example:

In the above program, inside the try block, when a division by zero exception occurs, the catch
block for Arithmetic Exception will handle the situation. The details of exception will be stored
in object e.
Downloaded from Ktunotes.in
Q. Explain the use of finally using a java program

• When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method.
• Depending upon how the method is coded, it is even possible for an exception to
cause the method to return prematurely.This could be a problem in some methods.
• For example, if a method opens a file upon entry and closes it upon exit, then you
will not want the code that closes the file to be bypassed by the exception-handling mechanism.
• The finally keyword is designed to address this contingency.
• finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block.
• The finally block will execute whether or not an exception is thrown.
• If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
• Any time a method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the method
returns.

Downloaded from Ktunotes.in


In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is
executed on the way out. procB( )’s try statement is exited via a return statement. The finally clause is
executed before procB( ) returns. In procC( ), the try statement executes normally, without error. However,
the finally block is still executed
Downloaded from Ktunotes.in
Q. Difference between throw and throws

throw
• Used to throw an exception explicitly(manually)
• Syntax:
throw ThrowableInstance;.
Here, ThrowableInstance must be an object of
type Throwable or a subclass of Throwable.
• The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
• The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of
exception. If it does find a match, control is transferred
to that statement. If not, then the next enclosing try
statement is inspected, and so on.
• If no matching catch is found, then the default exception
handler halts the program and prints the stack trace.

Downloaded from Ktunotes.in


throws
• If a method is capable of causing an exception
that it does not handle, it must specify this
behavior so that callers of the method can guard
themselves against that exception.
• This is done by including a throws clause in the
method’s declaration.
• A throws clause lists the types of exceptions that a
method might throw.
• Syntax:

In the example, throwOne() function is throwing an IllegalAccessException. So


the function header is given as:
static void throwOne() throws Illegal Exception
This throw will be handled by the callers catch block which prints
caught java.lang.IllegalAccessException: demo
Downloaded from Ktunotes.in
Q. Difference between Checked and Unchecked Exceptions

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Module 4

Downloaded from Ktunotes.in


Q. Explain in detail about byte streams and character streams

Downloaded from Ktunotes.in


Q. Write a program to demonstrate the usage of the
PrintWriter class.
• The PrintWriter class of the java.io package can be used to
write output data in a commonly readable form (text).
• It extends the abstract class Writer.
• PrintWriter converts the primitive data (int, float, char, etc.)
into the text format. It then writes that formatted data to the
writer.
• Also, the PrintWriter class does not throw any input/output
exception. Instead, we need to use the checkError() method to
find any error in it.
• The PrintWriter class provides various methods that allow us
to print data to the output.
print() - prints the specified data to the writer
println() - prints the data to the writer along with a new
line character at the end
• The following program use PrintWriter class to write a string Output:
to the console as well as to a file named testout.txt

Downloaded from Ktunotes.in


Q. Explain String constructors in java with examples

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Q. Explain some String Functions in
JAVA with examples

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Output:

Downloaded from Ktunotes.in


Q. Difference between = = and equals()
• The = = is a relational operator in Java that is used
to compare primitive types such as int, double,
char, float, etc. We should not use it to compare
two object references since for any non-null
reference values x and y, x = = y returns true only
when x and y refer to the same object
As evident from the above program, comparing
• On the contrary, the equals() method in the Object two strings using the == and equals() method
class is used to compare objects. It behaves
similarly to the = = operator if not overridden by a returns the different output. This is because == is
class. Every class should override the equals() performing a reference comparison, i.e.,
method of the Object class and specify the comparing if two variables refer to the same
equivalence relation on objects. The equivalence object or not. Since we’re creating two new
relation should be such that equals() methods string objects using the String constructor, they
evaluate the comparison of values in the objects will not share the same reference, and s1 == s2
irrespective of the two objects refer to the same returns false. Hence, we should never use the ==
instance or not. operator for comparing two strings.
• Since String is an object in Java, we should always
use the equals() method for comparing two strings On the other hand, the equals() method of the
in Java. This works since the String class overrides String class compares the contents of the backed
the equals() method of the Object class. char array and returns a boolean value as a result
of the comparison.
Downloaded from Ktunotes.in
class Main
{
public static void main(String[] args)
{
String s1 = "ABC";
String s2 = s1;

System.out.println(s1 == s2); // true


System.out.println(s1.equals(s2)); // true
}
}

The above code gives different results. This is because string literals are stored in the string constant
pool, and both s1 and s2 shares the same reference. Therefore, s1 == s2 returns true.

Downloaded from Ktunotes.in


Q. Explain Object Serialization with example.
• Serialization is the conversion of the state of an object into a byte stream.
• The conversion of a Java object into a static stream (sequence) of bytes which can then be saved to
a database or transferred over a network.
• Deserialization is the reverse process where the byte stream is used to recreate the actual Java
object in memory.

Downloaded from Ktunotes.in


• To make a Java object serializable we implement the java.io.Serializable interface.
• The ObjectOutputStream class contains writeObject() method for serializing an Object.
public final void writeObject(Object obj) throws IOException
• The ObjectInputStream class contains readObject() method for deserializing an object.
public final Object readObject() throws IOException, ClassNotFoundException
• Example: package Serial1;

import java.io.*;
class Persist{
public static void main(String args[]){
try{
Employee emp1 =new Employee(20110,"John");
Employee emp2 =new Employee(22110,"Jerry");
Employee emp3 =new Employee(20120,"Sam");
FileOutputStream fout=new FileOutputStream("output.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(emp1);
out.writeObject(emp2);
out.writeObject(emp3);
out.flush();
out.close();
System.out.println("Serialization is been successfully executed");
}
catch(Exception e){
System.out.println(e);}
}
}

Downloaded from Ktunotes.in


Deserialization
package Serial1;

import java.io.*;
class Depersist{
public static void main(String args[]){
try{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("output.txt"));
Employee e1=(Employee)in.readObject();
Employee e2=(Employee)in.readObject();
Employee e3=(Employee)in.readObject();
System.out.println(e1.id+" "+e1.name);
System.out.println(e2.id+" "+e2.name); In the above programs 3 objects of
System.out.println(e3.id+" "+e3.name); Employee class has been converted into
in.close(); byte stream and stored in a file named
}
Output.txt during serialization.
catch(Exception e){
Later during deserialization these byte
System.out.println(e);} streams are again restored into objects of
} Employee class.
} Downloaded from Ktunotes.in
Q. Explain any 2 Collection interfaces

1. Collection interface
• The Collection interface is the foundation upon which the Collections Framework is built because it
must be implemented by any class that defines a collection.
• Collection is a generic interface that has this declaration:
interface Collection<E>
Here, E specifies the type of objects that the collection will hold.
• Collection implements the Iterable interface. This means that all collections can be cycled through by
use of the for-each style for loop.
• Some methods in Collection interface can throw
• An UnsupportedOperationException. this occurs if a collection cannot be modified.
• A ClassCastException is generated when one object is incompatible with another, such as when an attempt is made to
add an incompatible object to a collection.
• A NullPointerException is thrown if an attempt is made to store a null object and null elements are not allowed in the
collection.
• An IllegalArgumentException is thrown if an invalid argument is used.
• An IllegalStateException is thrown if an attempt is made to add an element to a fixed-length collection that is full.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
List Interface
• The List interface extends Collection and declares the
behavior of a collection that stores a sequence of elements.
• Elements can be inserted or accessed by their position in the list,
using a zero-based index. A list may contain duplicate elements.
• List is a generic interface with the following declaration
interface List<E>
Here, E specifies the type of objects that the list will hold.
• The methods in this interface will throw an
• UnsupportedOperationException if the list cannot be
modified
• A ClassCastException when one object is incompatible
with another, such as when an attempt is made to add an
incompatible object to a list.
• IndexOutOfBoundsException if an invalid index is used.
• A NullPointerException is thrown if an attempt is made
to store a null object and null elements are not allowed
in the list.
• An IllegalArgumentException is thrown if an invalid
argument is used

Downloaded from Ktunotes.in


Q. Write notes on ArrayList in java or Explain about dynamic arrays in Java

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Q. Explain Different iterators used for accessing elements in an ArrayList with an example

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Q. Write a note about threads in java. Explain the ways in which threads can be created.
• A multithreaded program contains two or more parts that can run concurrently.
• Each part of such a program is called a thread, and each thread defines a separate path of
execution. Thus, multithreading is a specialized form of multitasking.
• Java’s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable.
• To create a new thread, the program will either extend Thread or implement the Runnable
interface.
• When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of the program, because it is the one that is executed when the program begins. The
main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• It must be the last thread to finish execution because it performs various shutdown actions.
• It can be controlled through a Thread object. To do so, we must obtain reference to it by
calling the method currentThread( ), which is a public static member of Thread. Its general
form is shown here:
static Thread currentThread( )

Downloaded from Ktunotes.in


Creating a Thread
• Implementing the Runnable interface
• Extending (Inheriting) the Thread Class

Implementing the Runnable interface


• To implement Runnable, a class need only implement a single method called run( ), which is declared like
this:
public void run( )
• Inside run( ), we need to define the code that constitutes the new thread.
• run( ) establishes the entry point for another, concurrent thread of execution within the program. This
thread will end when run( ) returns
• After we create a class that implements Runnable, instantiate (create) an object of type Thread from within
that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName)
• Here, threadOb is an instance of a class that implements the Runnable interface. This defines where
execution of the thread will begin. The name of the new thread is specified by threadName.
• After the new thread is created, it will not start running until start( ) method is invoked, which is declared
within Thread. In turn start( ) executes a call to run( ).

Downloaded from Ktunotes.in


Output:

• In this program, Inside NewThread’s constructor, a new Thread object is created


by the following statement:
t = new Thread(this, "Demo Thread"); which means we want the new thread to
call the run( ) method on this object.
• Next, start( ) is called, which starts the thread of execution beginning at the run( )
method. This causes the child thread’s for loop to begin .
• After calling start( ), NewThread’s constructor returns to main( ). When the
main thread resumes, it enters its for loop
• Both threads continue running, sharing the CPU, until their loops finish.
Downloaded from Ktunotes.in
Extending the Thread class
• The second way to create a thread is to create a new class that extends Thread, and then
to create an instance of that class.
• The extending class must override the run( ) method, which is the entry point for the new
thread. It must also call start( ) to begin execution of the new thread.
• In the following program, the child thread is created by instantiating an object of
NewThread, which is derived from Thread.
• The call to super( ) inside NewThread. This invokes the following form of the Thread
constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread.

Downloaded from Ktunotes.in


Output:

Downloaded from Ktunotes.in


Q. How synchronization is achieved in a multi threaded java program.

• 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 is achieved is
called synchronization.
• Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a
given time. When a thread acquires a lock, it is said to have entered the monitor.
• All other threads attempting to enter the locked monitor will be suspended until the first thread
exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a
monitor can reenter the same monitor if it so desires.
• To enter an object’s monitor, just call a method that has been modified with the synchronized
keyword.
• While a thread is inside a synchronized method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait.
• To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the
monitor simply returns from the synchronized method.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
• In the above program there are two classes MyThread1
and MyThread2 which extends Thread class. Here both
threads are trying to call void printTable() method which
is considered as the shared resource that prints the
multiplication table of an integer. Here printTable() is a
synchronized as
synchronized void printTable(int n)
• Inside the main function objects of Thread1 and Thread2,
t1 and t2 respectively, are created. t1.start() will invoke
the run() method of Thread1 and t2.start() will invoke the
run() method of Thread2.
• Both working simultaneously tries to access the
printTable() method which can be accessed only in a
synchronized manner. This means, if Thread1 enters its
monitor and access the printTable() function the Thread2
needs to wait until thread1 relinquishes its control over
printTable() and viceversa.
• The above program will give an output as:

Downloaded from Ktunotes.in


Q. Explain the delegation event model used for event handling in java

Downloaded from Ktunotes.in


• Events: In the delegation model, an event is an object that describes a state change in a
source. It can be generated as a consequence of a person interacting with the elements in a
graphical user interface. Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list, etc.
• Event Sources: A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the
general form:
public void addTypeListener(TypeListener el)
• Here, Type is the name of the event, and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ).
• When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
• Event Classes

Downloaded from Ktunotes.in


• Event Listeners
• An event listener interface defines the methods used by a component to dispatch events. Each
event type will have at least one corresponding dispatch method in a listener interface.

Downloaded from Ktunotes.in


Q. List different Event Classes, Corresponding listeners and their functions
Event Classes Listener Functions
ActionEvent ActionListener void actionPerformed(ActionEvent ae)

AdjustmentEvent AdjustmentListener void adjustmentValueChanged(AdjustmentEvent ae)

ComponentEvent ComponentListener void componentResized(ComponentEvent ce)


void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

ContainerEvent ContainerListener void componentAdded(ContainerEvent ce)


void componentRemoved(ContainerEvent ce)

FocusEvent FocusListener void focusGained(FocusEvent fe)


void focusLost(FocusEvent fe)

ItemEvent ItemListener void itemStateChanged(ItemEvent ie)

KeyEvent KeyListener void keyPressed(KeyEvent ke)


void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

Downloaded from Ktunotes.in


Event Classes Listener Functions
MouseEvent MouseListener void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

MouseMotionEvent MouseMotionListener void mouseDragged(MouseMotionEvent mme)


void mouseMoved(MouseMotionEvent mme)

TextEvent TextListener void textChanged(TextEvent te)

Downloaded from Ktunotes.in

You might also like