SlideShare a Scribd company logo
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 1
UNIT 2 – PACKAGES AND INTERFACES
PART A
S.
No.
Question
1. What is package and how is it used?
A package in Java is used to group related classes, sub packages and interfaces. Think of it as a
folder in a file directory. Packages are used to avoid name conflicts, and to write a better
maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
Example:
package Mypack;
import java.io.*;
2. What is an interface? Why do we need interface? Justify
An interface in java is a blueprint of a class. It has static constants and abstract methods.
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.
access interface name
{
final type varname1 = value;
final type varname2 = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
}
There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
3. Differentiate class, abstract class and interface.
Class Abstract class Interface
In class, you can instantiate
variable and create an object.
In an abstract class, you can
instantiate variable but
cannot create an object.
In an interface, you can't
instantiate variable and
create an object.
Class can contain non-
abstract methods.
Abstract class can have
both abstract and non-
abstract methods.
Interface can have only
abstract methods.
Class doesn't support multiple
inheritance.
Abstract class doesn't
support multiple
inheritance.
Interface supports multiple
inheritance.
The class keyword is used to
declare a class.
The abstract keyword is
used to declare abstract
class.
The interface keyword is
used to declare interface.
The access specifiers used
with classes are private,
protected and public.
The access specifiers used
with abstract classes are
private, protected and
public.
In Interface only one access
specifier used is public.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 2
Example:
class Rectangle
{
void showrect()
{
System.out.println(“Rectangle
class”);
}
}
Example:
abstract class Shape
{
abstract void draw();
}
Example:
interface Drawable
{
void draw();
}
4. How will you extend one interface by other interface?
✓ One interface can inherit another by use of the keyword extends.
✓ The syntax is the same as for inheriting classes.
Example:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
5. Which package is always imported by default?
Three packages are imported by default for each source file. First, the package with no name.
Second, the java.lang package and third, the current package (the package in which the current file is
defined).
6. What are the different ways to handle exceptions? Is it essential to catch all types of
exceptions?
There are two ways to handle Exceptions
• Wrapping the desire code in a try block followed by a catch block to catch the exception
• List the desired exception in the throws clause of the method and let the caller of the method
handle those exceptions.
Is it essential to catch all types of exceptions?
No. 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.
7. What is the difference between throw and throws?
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.
8. What is the difference between sleep and suspend?
• Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time.
• t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread.
• t.wait() Causes current thread to wait until either another thread invokes the notify() method or
the notifyAll() method for this object, or a specified amount of time has elapsed.
9. What is a thread? List out the thread states.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 3
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
10. When a thread is created and started, what is its initial state?
A thread is in “Ready” state after it has been created and started. This state signifies that the thread
is ready for execution. From here, it can be in the running state.
11. What is the importance of thread synchronization?
Synchronization is the capability to control the access of multiple threads to share resources without
synchronization, it is possible for one thread to modify a share, the object while another thread is in
the process of using of updating that object value this often leads to significant errors.
12. What is multithreading?
Multithreading in java is a process of executing multiple threads simultaneously. 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.
13. What are the two ways for creating a thread? Explain the difference in using runnable and
extends in Thread.
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
• We can use Extend Thread class only when the class is not extending another class as Java
doesn’t support multiple inheritances. In that case, we can use Runnable interface to create
Thread.
• When we extend a thread, each thread has a unique object associated with it, whereas with
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 4
Runnable, many threads share the same object instance.
14. How does java support interthread communication?
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.
15. Difference between sleep() and wait()
The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any
lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to
introduce pause on execution.
16. What is an Exception. Differentiate checked and unchecked exception?
• An exception is an abnormal condition that arises in a code sequence at run time. In other words,
an exception is a run-time error.
• A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
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.
17. How is throw exception created in exception handling?
Throw method is used to throw an exception manually. It has to declare the exceptions thrown in the
method signature and then include a throw statement in the method
throw new ExceptionName (“Value”);
18. Differentiate error from exception. How is custom exception created?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error is
a subclass of throwable is intended for drastic problem, such as OutOfMemoryError.
An exception is an event, which occurs during the execution of a program , that disrupts the normal
flow of the program. Exception is a subclass of throwable class, example of such as
ArithmeticException.
By extending the exception class or one of its subclasses, we can create custom exception.
Example
class MyException extends Exception
{
public MyException()
{super();}
public MyException(String s)
{super(s);}
}
19. What is the use of Alive() and Join()method ?
The isAlive() method returns true if the thread upon which it is called is still running otherwise it
returns false.
final boolean isAlive()
The join() method waits for a thread to die. In other words, it causes the currently running threads to
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 5
stop executing until the thread it joins with completes its task.
20. How strings are implemented in java?
Java implements strings as objects of type String. Once a String object has been created, it
is not possible to change the characters that comprise that string. For those cases in which a
modifiable string is desired, Java provides two options:
• StringBuffer and
• StringBuilder.
21. What are the constructors supported for String class?
There are several constructors supported for String class are:
• String s = new String();
• char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
• char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
• String s1 = new String(“Apple”);
String s2 = new String(s1);
22. List out some of the special string operations in java.
Special string operations in java are:
• String Literals
• String Concatenation
• String Concatenation with Other Data Types
• String Conversion and toString()
23. List out some of the character extraction operations in java.
Some of the character extraction operations in java are:
• charAt( )
• getChars( )
• getBytes( )
• toCharArray( )
24. List out the constructor supported for StringBuffer class.
There are four constructors supported for StringBuffer class:
• StringBuffer( )
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)
25. List out the methods of StringBuffer class.
The methods StringBuffer class:
• length() and capacity()
• ensureCapacity()
• setLength()
• charAt() and setCharAt()
• getChars()
• append()
• insert()
• reverse()
• delete(), deleteCharAt()
• replace()
• subString()
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 6
PART B
S.
No.
Question
1. With suitable example explain how packages are created, imported and used. Elaborate on its
package scope
A package in Java is used to group related classes, sub packages and interfaces. Think of it as a
folder in a file directory. Packages are used to avoid name conflicts, and to write a better
maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
Defining a Package
✓ To create a package simply include the package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package.
✓ The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no name.
✓ This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;
Example
//save as Simple.java
package MyPack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting Simple.class file is also in the MyPack directory. Then try executing the
Simple class, using the following command line:
java MyPack.Simple
Remember, you will need to be in the directory above MyPack when you execute this command, or
to have your CLASSPATH environmental variable set appropriately. As explained, Simple is now
part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use
this command line:
java Simple
Simple must be qualified with its package name.
Importing Packages
There are three ways to import the package from outside the package.
1. import package.*;
2. import package.Classname;
3. fully qualified name.
1) Using packagename.*
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 7
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
Example of package that import the packagename.*
//save by A.java
package pack1;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.Classname
If you import package.Classname then only declared class of this package will be accessible.
Example of package by import package.Classname
//save by A.java
package pack1;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack1.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 8
}
Output:
Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack1;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack1.A(); //using fully qualified name
obj.msg();
}
}
Output:
Hello
Built-in Packages
The Java API is a library of prewritten classes that are free to use, included in the Java Development
Environment.
The library contains components for managing input, database programming, and much more. For
example,
java.applet
java.awt
java.util
java.lang
java.net
The library is divided into packages and classes. The user can either import a single class (along
with its methods and attributes), or a whole package that contain all the classes that belong to the
specified package.
To use a class or a package from the library, use the import keyword:
Syntax
import package.name.Class; // Import a single class
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 9
import package.name.*; // Import the whole package
Example
import java.util.Scanner; // Import a single class
import java.util.*; // Import the whole package
2. What is an interface?What are the properties of Interfaces? Write java program to ilustrate
use of an interface.
INTERFACE
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.
It cannot be instantiated just like abstract class.
✓ An interface is a collection of abstract methods (i.e. methods without having definition).
✓ A class that implements an interface inherits abstract methods of the interface.
✓ An interface is not a class.
✓ If a class (provided it is not abstract) implements an interface, then all the methods of
interface need to be defined in it.
Uses Java interface:
There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
access interface name
{
final type varname1 = value;
final type varname2 = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
}
Interfaces have the following properties:
✓ An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract
keyword when declaring an interface.
✓ Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract
keyword is not needed.
✓ Methods in an interface are implicitly (i.e. by default) public.
The java compiler adds public and abstract keywords before the interface method. More, it
adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and
abstract.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 10
Implementing Interfaces
✓ A class can implement more than one interface at a time.
✓ A class can extend only one class, but can implement many interfaces.
✓ An interface itself can extend another interface.
✓ The general form of a class that includes the implements clause looks like this:
class classname extends superclass implements interface1 , interface2...
{
// class-body
}
Example:
interface Message
{
void message1( );
void message2( );
}
class A implements Message
{
void message1( )
{
System.out.println("Good Morning");
}
void message2( )
{
System.out.println("Good Evening");
}
public static void main(String args[])
{
A a=new A();
a.message1();
a.message2();
}
}
3. Write a Java program to create and use a user defined package in Java.
A package in Java is used to group related classes, sub packages and interfaces. Think of it as a
folder in a file directory. Packages are used to avoid name conflicts, and to write a better
maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 11
Defining a Package
✓ To create a package simply include the package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package.
✓ The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no name.
✓ This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;
Example
//save as Simple.java
package MyPack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting Simple.class file is also in the MyPack directory. Then try executing the
Simple class, using the following command line:
java MyPack.Simple
Remember, you will need to be in the directory above MyPack when you execute this command, or
to have your CLASSPATH environmental variable set appropriately. As explained, Simple is now
part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use
this command line:
java Simple
Simple must be qualified with its package name.
Creating Sub package in a package:
We can create sub package in a package in the format:
package packagename.subpackagename;
e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes
and interfaces of pack2, we can write import statement as: import pack1.pack2;
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{
public void show ()
{
System.out.println ("Hello Java Learners");
}
}
4. Explain multithreading, thread states and thread priority.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 12
Multithreading in java is a process of executing multiple threads simultaneously. 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.
Multiprocessing and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time
than process.
Java Multithreading is mostly used in games, animation, etc.
Thread:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Life Cycle of a Thread
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 13
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread Priority
• Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
• Priorities are represented by a number between 1 and 10.
• In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses
• Java priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
• Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependent.
• A thread’s priority is used to decide when to switch from one running thread to the next. This
is called a context switch.
The rules that determine when a context switch takes place are simple:
• A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 14
or blocking on pending I/O. In this scenario, all other threads are examined, and the highest
priority thread that is ready to run is given the CPU.
• A thread can be preempted by a higher-priority thread. In this case, a lower-priority
thread that does not yield the processor is simply preempted—no matter what it is doing—
by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it
does. This is called preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be within
the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10,
respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
These priorities are defined as static final variables within Thread. You can obtain the current
priority setting by calling the getPriority() method of Thread, shown here:
final int getPriority( )
5. How threads are created in java? Explain the two implementation methods with example java
program
The Thread Class and the Runnable Interface
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Creating Thread by extending Thread class:
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.
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
The Thread class defines several methods that help manage threads.
Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 15
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
Creating Thread by Implementing Runnable interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
• To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.
• After we create a class that implements Runnable, you will instantiate 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 and the name of the
new thread is specified by threadName.
• After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new Thread(obj);
t1.start();
}
}
Output: thread is running...
6. Explain life cycle of thread with help of a diagram. How do the wait and Notify All/ Notify
methods enable cooperation between threads?
Life Cycle of a Thread
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1. New
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 16
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Inter Thread Communication using Wait, notify and notifyAll
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
wait( ) 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( ) wakes up the first thread that called wait( ) on the
same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest
priority thread will run first. These methods are declared within Object, as shown here:
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 17
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Steps for Inter thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 18
}
}
class Samp1
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
7. What is thread synchronization? Discuss with an example Java program
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 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.
Using Synchronized Methods:
Synchronization is easy in Java, because all objects have their own implicit monitor
associated with them. 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.
Example 1:
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 19
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{ this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{ this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 20
10
15
20
25
100
200
300
400
500
Using synchronized Statement:
While creating synchronized methods within classes that you create is an easy and effective means
of achieving synchronization, it will not work in all cases. To understand why, consider the
following. Imagine that you want to synchronize access to objects of a class that was not
designed for multithreaded access. That is, the class does not use synchronized methods. Further,
this class was not created by you, but by a third party and you do not have access to the source
code. Thus, you can’t add synchronized to the appropriate methods within the class. How can
access to an object of this class be synchronized?
Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined
by this class inside a synchronized block. This is the general form of the synchronized statement:
synchronized (object)
{
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call
to a method that is a member of object occurs only after the current thread has successfully entered
object’s monitor.
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t ; int N;
MyThread1(Table t,int n)
{
this.t=t;
N=n;
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 21
}
public void run()
{
synchronized(t) //synchronized block
{
t.printTable(n);
}
}
}
public class Test
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread1 t2=new MyThread1(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Example:
class A extends Thread
{
int total;
synchronized public void run()
{
total = 0;
for(int i=1;i<=5;i++)
{
total=total + i;
}
notify();
}
}
public class Example3Thread {
public static void main(String[] args) {
A obj = new A();
try
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 22
{
obj.start();
synchronized(obj)
{
System.out.println("Waiting....");
obj.wait();
}
}
catch(Exception e)
{
}
System.out.println("Total = " + obj.total);
}
}
OUTPUT:
Waiting....
Total = 15
8. Explain searching and modifying a String value with an example program.
i) Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases, the
methods return the index at which the character or substring was found, or 1
–on failure.
To search for the first occurrence of a character, use
int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought. To search for the first or last occurrence of a
substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the sub-string. You can specify a starting point for the search using
these forms:
int indexOf(int ch, int startIndex)
intlastIndexOf(intch,intstartIndex)
intindexOf(Stringstr,intstartIndex)
int lastIndexOf(String str, int startIndex)
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the
search runs from startIndex to the end of the string. For lastIndexOf(), the search runs
from startIndex to zero. The following example shows how to use the various index
methods to search inside of Strings:
class indexOfDemo{
public static void main(String args[]){
String s = "Now is the time for all good men " + "to come to the aid of their country.";
System.out.println(s); System.out.println("indexOf(t) = " +s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +s.indexOf("the"));
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 23
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));}}
Here is the output of this program:
Now is the time for all good men to come to the aid of their country.
indexOf(t) =7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
ii) Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use one of the following String
methods, which will construct a new copy of the string with your modifications
complete.
a) substring( )
Can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a
copy of the substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending
index of the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping
point. The string returned contains all the characters from the beginning index, up to, but
not including, the ending index. The following program uses substring( ) to replace all
instances of one substring with another within a string:
class StringReplace{
public static void main(String args[]){
String org = "This is a test. This is, too."; String search = "is";
String sub = "was"; String result = ""; int i;
do
{
System.out.println(org);
i = org.indexOf(search); if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length()); org =result;
}
} while(i !=-1);}}
The output from this program is shown here:
This is a test. This is, too.
Thwas is a test. This is, too.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 24
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
b) concat( )
It is possible to concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of
str appended to the end. concat() performs the same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
c) replace( )
The replace() method has two forms. The first replaces all occurrences of one character
in the invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by
replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.The second form of replace( ) replaces one character
sequence with another. It has this general form:
String replace(CharSequence original, CharSequence replacement)
This form was added by J2SE 5.
d) trim( )
The trim() method returns a copy of the invoking string from which any leading and
trailing white space has been removed. It has this general form:
String trim( )
Here is an example:
String s=" HelloWorld ".trim();
This puts the string “Hello World” into s. The trim() method is quite useful when you
process user commands. For example, the following program prompts the user for
the name of a state and then displays that state’s capital. It uses trim() to remove any
leading or trailing white space that may have inadvertently been entered by the user.
import java.io.*;
class UseTrim{
public static void main(String args[]) throws IOException{
BufferedReader br = newBufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do
{
str = br.readLine();
str = str.trim(); // remove whitespace
if(str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 25
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
} while(!str.equals("stop"));}}
9. Explain StringBuffer class methods in java with an example program.
StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences. In contrast, StringBuffer
represents growable and writeable character sequences. StringBuffer may have characters
and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more characters
preallocated than are actually needed, to allow room for growth. Java uses both classes
heavily, but many programmers deal only with String and let Java manipulate
StringBuffers behind the scenes by using the overloaded +operator.
a) StringBuffer Constructors
StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
The default constructor reserves room for 16 characters without reallocation. The second
version accepts an integer argument that explicitly sets the size of the buffer. The third
version accepts a String argument that sets the initial contents of the StringBuffer object
and reserves room for 16 more characters without reallocation. StringBuffer allocates
room for 16 additional characters when no specific buffer length is requested, because
reallocation is a costly process in terms of time. Also, frequent reallocations can fragment
memory. By allocating room for a few extra characters, StringBuffer reduces the number
of reallocations that take place. The fourth constructor creates an object that contains the
character sequence contained inchars.
b) length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method, while the total
allocated capacity can be found through the capacity( ) method. They have the following
general forms:
int length( ) int capacity( )
Here is an example:
class StringBufferDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());}}
Here is the output of this program, which shows how StringBuffer reserves extra
spacefor additional manipulations:
buffer = Hello length = 5
capacity = 21
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 26
Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is
21 because room for 16 additional characters is automatically added.
c) ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has
been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if
you know in advance that you will be appending a large number of small strings to a
StringBuffer. ensureCapacity( ) has this general form:
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
d) setLength()
To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form
is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative.When you
increase the size of the buffer, null characters are added to the end of the existing buffer.
If you call setLength( ) with a value less than the current value returned by length(), then
the characters stored beyond the new length will be lost.
e) charAt( ) and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt( ) method.
You can set the value of a character within a StringBuffer using setCharAt( ). Their general
forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt(), where specifies the index of the character being obtained. For setCharAt(),
where specifies the index of the character being set, and ch specifies the new value of that
character. For both methods, where must be nonnegative and must not specify a location
beyond the end of the buffer. The following example demonstrates charAt( ) and
setCharAt( ):
class setCharAtDemo{
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));}}
Here is the output generated by this program:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
f) getChars()
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this
general form:
void getChars(int sourceStart,int sourceEnd,char target[], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 27
specifies an index that is one past the end of the desired substring. This means that the
substring contains the characters from sourceStart through sourceEnd–
1. The array that will
receive the characters is specified by target. The index within target at which the
substring will be copied is passed in targetStart.
g) append()
The append() method concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object. It has several overloaded versions. Here are a
few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf( ) is called for each parameter to obtain its string representation. The
result is appended to the current StringBuffer object. The buffer itself is returned by each
version of append( ). This allows subsequent calls to be chained together, as shown in the
following example:
class appendDemo{
public static void main(String args[]){
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
The output of this example is shown here:
a = 42!
h) insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the
simple types, plus Strings, Objects, and CharSequences. Like append(), it calls String.valueOf( )
to obtain the string representation of the value it is called with. This string is then inserted
into the invoking StringBuffer object. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object.
The following sample program inserts “like” between “I” and “Java”:
class insertDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);}}
The output of this example is shown here:
I like Java!
i) reverse( )
Can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reversed object on which it was called. The following
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 28
program demonstrates reverse():
class ReverseDemo{
public static void main(String args[]){
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s); s.reverse(); System.out.println(s);}}
Here is the output produced by the program:
abcdef fedcba
j) delete( ) and deleteCharAt( )
You can delete characters within a StringBuffer by using the methods delete( ) and
deleteCharAt( ). These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. Here,
startIndex specifies the index of the first character to remove, and endIndex specifies an index
one past the last character to remove. Thus, the substring deleted runs from startIndex to
endIndex–
1. The resulting StringBuffer object is returned.
The deleteCharAt() method deletes the character at the index specified by loc. It returns
the resulting StringBuffer object.
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
class deleteDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);}}
The following output is produced:
After delete: This a test.
After deleteCharAt: his atest.
k) replace( )
You can replace one set of characters with another set inside a StringBuffer object by
calling replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus,
the substring at startIndex through endIndex1
– is replaced. The replacement string is passed
in str. The resulting StringBuffer object is returned. The following program demonstrates
replace( ):
class replaceDemo {
public static void main(String args[]){
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was"); System.out.println("After replace: " + sb);}}
Here is the output:
After replace: This was a test.
l) substring( )
You can obtain a portion of a StringBuffer by calling substring( ). It has the following two
forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 29
The first form returns the substring that starts at startIndex and runs to the end of the
invoking StringBuffer object. The second form returns the substring that starts at
startIndex and runs through endIndex1
–.
10. Discuss about the Java exception handling mechanisms with suitable examples.
EXCEPTION HANDLING
Error occurred in a program can be of two types: syntax error or logical error.
• An exception is an abnormal condition that arises in a code sequence at run time. In other words,
an exception is a run-time error.
• A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
• Exception Handling is a mechanism by which exception occurred in a program is handled.
• The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
• Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
S.No Keyword/Block Meanings
1 try block The statements which are expected to throw exception are kept inside
try block.
2 catch block If an exception occurs within the try block, it is throws an exception
to the catch block which handle it in some rational manner.
3 throw To manually throw an exception, use the keyword throw.
4 throws A throws clause lists the types of exceptions that a method might
throw.
5 finally Any code that absolutely must be executed before a method returns is
put in a finally block.
The general form of an exception-handling block is:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed before try block ends
}
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top
of the exception class hierarchy.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 30
• The Throwable class has two subclasses Error and Exception.
• Error and Exception classes are used for handling errors in java.
Using try and catch
The following program includes a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero error.
Demonstration of Division by zero Exception.
class Ex
{
public static void main(String args[ ])
{
int x, y;
try
{
x = 0;
y= 1/ x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Notice that the call to println ( ) inside the try block is never executed. Once an exception is
thrown, program control transfers out of the try block into the catch block. Put differently, catch is
not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not
be printed.” is not displayed. Once the catch statement has executed, program control continues with
the next line in the program following the entire try/catch mechanism.
11. Demonstrate the implemation of Inter-thread communication using a sample java program
Inter Thread Communication using Wait, notify and notifyAll
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
wait( ) 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( ) wakes up the first thread that called wait( ) on the
same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 31
priority thread will run first. These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Steps for Inter thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 32
notify();
}
}
class Samp1
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
PART C
S.
No.
Question
1. Develop a java program to find the area of rectangle, square, and circle using interfaces.
interface Area
{
float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute (float x, float y)
{
return(x*y);
}
}
class Square implements Area
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 33
public float compute(float x, float y)
{
return(x*x);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
class Areademo
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Square sqr=new Square();
Circle cir=new Circle();
System.out.println("Area of rectangle : "+rect.compute(5,10));
System.out.println("Area of square : "+sqr.compute(5,0));
System.out.println("Area of circle : "+cir.compute(5,0));
}
}
OUTPUT:
Area of rectangle : 50.0
Area of square : 25.0
Area of circle : 78.5
2. Write java application program for generating four threads to perform following operations:
• Getting N numbers as input
• Printing even numbers
• Printing odd numbers
• Computing average
import java.util.Scanner;
class Compute
{
int num;
synchronized void getnum()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
num = scanner.nextInt();
System.out.println("Number is :"+num);
}
synchronized void odd()
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 34
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("ODD NUMBERS");
for (int i=1;i<=num;i++)
if(i%2 != 0)
System.out.println(i);
}
synchronized void even()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("EVEN NUMBERS");
for (int i=1;i<=num;i++)
if(i%2 == 0)
System.out.println(i);
}
synchronized void average()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
int sum=0;
for (int i=1;i<=num;i++)
{
sum=sum+i;
}
float avg = (float)sum / num;
System.out.println("Average of numbers upto " + num + " is " + avg);
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 35
}
}
class A extends Thread
{
Compute obj;
A(Compute c1)
{
obj=c1;
start();
}
public void run()
{
obj.getnum();
}
}
class B extends Thread
{
Compute obj;
B(Compute c1)
{
obj=c1;
start();
}
public void run()
{
obj.odd();
}
}
class C extends Thread
{
Compute obj;
C(Compute c1)
{
obj=c1;
start();
}
public void run()
{
obj.even();
}
}
class D extends Thread
{
Compute obj;
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 36
D(Compute c1)
{
obj=c1;
start();
}
public void run()
{
obj.average();
}
}
public class FourThread
{
public static void main(String[] args)
{
Compute ob=new Compute();
A obj1 = new A(ob);
B obj2 = new B(ob);
C obj3 = new C(ob);
D obj4 = new D(ob);
}
}
OUTPUT:
Enter the number:
10
Number is :10
Average of numbers upto 10 is 5.5
EVEN NUMBERS
2
4
6
8
10
ODD NUMBERS
1
3
5
7
9
3. Write a java program to find factorial of an integer given from the keyboard. Using exception
handling mechanism, display appropriate message if the input from keyboard is not a valid
integer.
import java.util.*;
class Factorial
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 37
{
public static void main(String args[])
{
try
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int num = scanner.nextInt();
int fact=1;
for(int i=1;i<=num;i++)
fact=fact*i;
System.out.println("Factorial of " + num +" is "+fact);
}
catch(InputMismatchException e)
{
System.out.println("You have entered invalid data");
}
}
}
OUTPUT 1:
Enter the number:
5
Factorial of 5 is 120
OUTPUT 2:
Enter the number:
25.64
You have entered invalid data
OUTPUT 3:
Enter the number:
ABC
You have entered invalid data
4. Write a program to find addition of two numbers given from the keyboard. Using exception
handling, display appropriate message if the inputs are not valid numbers.
import java.util.*;
class Addition
{
public static void main(String args[])
{
try
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number1:");
int num1 = scanner.nextInt();
System.out.print("Enter the number2:");
int num2 = scanner.nextInt();
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 38
int sum = num1 + num2;
System.out.println("Total is " + sum );
}
catch(InputMismatchException e)
{
System.out.println("You have entered invalid data");
}
}
}
OUTPUT 1:
Enter the number1:5
Enter the number2:10
Total is 15
OUTPUT 2:
Enter the number1:ABC
You have entered invalid data
OUTPUT 3:
Enter the number1:5
Enter the number2:23.6
You have entered invalid data
5. a) Explain the usage of nested try with an example.
b) Write a program using throw for catching an error that is not divisible by zero.
a) Explain the usage of nested try with an example.
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
try
{
statement 1;
}
catch(Exception e)
{ }
}
catch(Exception e)
{ }
Example :
class Excep6
{
public static void main(String args[])
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 39
try
{ try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{ System.out.println(e);
}
try
{ int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{ System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
OUTPUT:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
b) Write a program using throw for catching an error that is not divisible by zero.
import java.util.*;
class Addition
{
public static void main(String args[])
{
try
{
int a=100;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int b = scanner.nextInt();
if(b==0)
{
throw new ArithmeticException("Division by ZERO");
}
else
{
int c=a/b;
System.out.println ("Result: "+c);
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 40
}
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
OUTPUT 1:
Enter the number:
5
Result: 20
OUTPUT 2:
Enter the number:
0
java.lang.ArithmeticException: Division by ZERO
6. Write a thread synchronization implementation program that displays contents of text
supplied through three threads.
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 41
public void run()
{
target.call(msg);
}
}
class SyncThread
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
OUTPUT:
[Hello]
[World]
[Synchronized]
7. Write a java program to illustrate about thread priorities.
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}
public static void main(String[]args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 42
System.out.println("t1 thread priority : " + t1.getPriority());
System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());
//Main Thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : " + Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : " + Thread.currentThread().getPriority());
}
}
OUTPUT:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
mainMain thread priority : 5
Main thread priority : 10
8. Design a program using Thread class and Runnable interfaces of your choice and compare the
differences.
The Thread Class and the Runnable Interface
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Creating Thread by extending Thread class:
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.
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
The Thread class defines several methods that help manage threads.
Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 43
Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
Creating Thread by Implementing Runnable interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
• To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.
• After we create a class that implements Runnable, you will instantiate 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 and the name of the
new thread is specified by threadName.
• After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new Thread(obj);
t1.start();
}
}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 – QUESTION BANK / SMART MATERIAL Page 44
Output: thread is running...
Basis for
Comparison
Thread class Runnable interface
Basic Each thread creates a unique object and
gets associated with it.
Multiple threads share the same
objects.
Memory As each thread create a unique object,
more memory required.
As multiple threads share the same
object less memory is used.
Extending In Java, multiple inheritance not
allowed hence, after a class extends
Thread class, it can not extend any
other class.
If a class define thread implementing
the Runnable interface it has a chance
of extending one class.
Use A user must extend thread class only if
it wants to override the other methods
in Thread class.
If you only want to specialize run
method then implementing Runnable
is a better option.
Coupling Extending Thread class introduces
tight coupling as the class contains
code of Thread class and also the job
assigned to the thread
Implementing Runnable interface
introduces loose coupling as the code
of Thread is separate form the job of
Threads.

More Related Content

PDF
20 most important java programming interview questions
PDF
Java apptitude-questions-part-2
PDF
Core_Java_Interview.pdf
DOC
Core java interview questions1
PDF
Java Faqs useful for freshers and experienced
PDF
Top 371 java fa qs useful for freshers and experienced
DOC
MC0078 SMU 2013 Fall session
PPTX
Java J2EE Interview Questions Part-1
20 most important java programming interview questions
Java apptitude-questions-part-2
Core_Java_Interview.pdf
Core java interview questions1
Java Faqs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
MC0078 SMU 2013 Fall session
Java J2EE Interview Questions Part-1

Similar to Smart material - Unit 2 (1).pdf (20)

PPTX
Java J2EE Interview Questions Part-1
DOCX
Jist of Java
DOCX
JAVA CONCEPTS AND PRACTICES
DOC
Core java questions
DOC
Core java questions
PDF
Java Interview Questions
DOC
Java interview faq's
PPTX
25 java interview questions
PDF
java04
PDF
__ Java Technical round questions .pdf soo
PPTX
Java Basics
DOC
Java interview questions
PPTX
Java_Interview Qns
DOCX
Java mcq
DOCX
Java questions for viva
PDF
Programming in Java Unit 1 lesson Notes for Java
DOCX
Viva file
PDF
JAVA INTERVIEW QUESTIONS.pdf java developer engineer
PDF
JAVA TECHNICAL INTERVIEW.pdf java developer engineer
Java J2EE Interview Questions Part-1
Jist of Java
JAVA CONCEPTS AND PRACTICES
Core java questions
Core java questions
Java Interview Questions
Java interview faq's
25 java interview questions
java04
__ Java Technical round questions .pdf soo
Java Basics
Java interview questions
Java_Interview Qns
Java mcq
Java questions for viva
Programming in Java Unit 1 lesson Notes for Java
Viva file
JAVA INTERVIEW QUESTIONS.pdf java developer engineer
JAVA TECHNICAL INTERVIEW.pdf java developer engineer
Ad

More from GayathriRHICETCSESTA (20)

PPTX
introduction to neural networksintro2.pptx
PPT
introduction to data minining and unit iii
DOCX
introduction to machine learning unit iV
DOCX
introduction to machine learning unit iv
DOCX
introduction to machine learning unit III
PDF
nncollovcapaldo2013-131220052427-phpapp01.pdf
PDF
Smart material - Unit 3 (1).pdf
PDF
Unit 2 notes.pdf
PDF
CS8601-IQ.pdf
PDF
CS8601-QB.pdf
PDF
Smart material - Unit 2 (1).pdf
PDF
Smart material - Unit 3 (2).pdf
PDF
Annexure 2 .pdf
PPT
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
PPT
ann-ics320Part4.ppt
PDF
nncollovcapaldo2013-131220052427-phpapp01.pdf
PDF
alumni form.pdf
PDF
Semester VI.pdf
PPT
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
PPT
ann-ics320Part4.ppt
introduction to neural networksintro2.pptx
introduction to data minining and unit iii
introduction to machine learning unit iV
introduction to machine learning unit iv
introduction to machine learning unit III
nncollovcapaldo2013-131220052427-phpapp01.pdf
Smart material - Unit 3 (1).pdf
Unit 2 notes.pdf
CS8601-IQ.pdf
CS8601-QB.pdf
Smart material - Unit 2 (1).pdf
Smart material - Unit 3 (2).pdf
Annexure 2 .pdf
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
ann-ics320Part4.ppt
nncollovcapaldo2013-131220052427-phpapp01.pdf
alumni form.pdf
Semester VI.pdf
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
ann-ics320Part4.ppt
Ad

Recently uploaded (20)

PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPT
Project quality management in manufacturing
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
Welding lecture in detail for understanding
PDF
Well-logging-methods_new................
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
DOCX
573137875-Attendance-Management-System-original
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Project quality management in manufacturing
bas. eng. economics group 4 presentation 1.pptx
Sustainable Sites - Green Building Construction
Operating System & Kernel Study Guide-1 - converted.pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
Welding lecture in detail for understanding
Well-logging-methods_new................
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Geodesy 1.pptx...............................................
Foundation to blockchain - A guide to Blockchain Tech
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Lesson 3_Tessellation.pptx finite Mathematics
CYBER-CRIMES AND SECURITY A guide to understanding
Model Code of Practice - Construction Work - 21102022 .pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
573137875-Attendance-Management-System-original

Smart material - Unit 2 (1).pdf

  • 1. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 1 UNIT 2 – PACKAGES AND INTERFACES PART A S. No. Question 1. What is package and how is it used? A package in Java is used to group related classes, sub packages and interfaces. Think of it as a folder in a file directory. Packages are used to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: • Built-in Packages (packages from the Java API) • User-defined Packages (create your own packages) Example: package Mypack; import java.io.*; 2. What is an interface? Why do we need interface? Justify An interface in java is a blueprint of a class. It has static constants and abstract methods. 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. access interface name { final type varname1 = value; final type varname2 = value; return-type method-name1(parameter-list); return-type method-name2(parameter-list); } There are mainly three reasons to use interface. They are given below. • It is used to achieve abstraction. • By interface, we can support the functionality of multiple inheritance. • It can be used to achieve loose coupling. 3. Differentiate class, abstract class and interface. Class Abstract class Interface In class, you can instantiate variable and create an object. In an abstract class, you can instantiate variable but cannot create an object. In an interface, you can't instantiate variable and create an object. Class can contain non- abstract methods. Abstract class can have both abstract and non- abstract methods. Interface can have only abstract methods. Class doesn't support multiple inheritance. Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. The class keyword is used to declare a class. The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. The access specifiers used with classes are private, protected and public. The access specifiers used with abstract classes are private, protected and public. In Interface only one access specifier used is public.
  • 2. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 2 Example: class Rectangle { void showrect() { System.out.println(“Rectangle class”); } } Example: abstract class Shape { abstract void draw(); } Example: interface Drawable { void draw(); } 4. How will you extend one interface by other interface? ✓ One interface can inherit another by use of the keyword extends. ✓ The syntax is the same as for inheriting classes. Example: interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } 5. Which package is always imported by default? Three packages are imported by default for each source file. First, the package with no name. Second, the java.lang package and third, the current package (the package in which the current file is defined). 6. What are the different ways to handle exceptions? Is it essential to catch all types of exceptions? There are two ways to handle Exceptions • Wrapping the desire code in a try block followed by a catch block to catch the exception • List the desired exception in the throws clause of the method and let the caller of the method handle those exceptions. Is it essential to catch all types of exceptions? No. 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. 7. What is the difference between throw and throws? 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. 8. What is the difference between sleep and suspend? • Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. • t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. • t.wait() Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. 9. What is a thread? List out the thread states.
  • 3. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 3 A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area. The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated 10. When a thread is created and started, what is its initial state? A thread is in “Ready” state after it has been created and started. This state signifies that the thread is ready for execution. From here, it can be in the running state. 11. What is the importance of thread synchronization? Synchronization is the capability to control the access of multiple threads to share resources without synchronization, it is possible for one thread to modify a share, the object while another thread is in the process of using of updating that object value this often leads to significant errors. 12. What is multithreading? Multithreading in java is a process of executing multiple threads simultaneously. 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. 13. What are the two ways for creating a thread? Explain the difference in using runnable and extends in Thread. There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. • We can use Extend Thread class only when the class is not extending another class as Java doesn’t support multiple inheritances. In that case, we can use Runnable interface to create Thread. • When we extend a thread, each thread has a unique object associated with it, whereas with
  • 4. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 4 Runnable, many threads share the same object instance. 14. How does java support interthread communication? 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. 15. Difference between sleep() and wait() The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. 16. What is an Exception. Differentiate checked and unchecked exception? • An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. • A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. 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. 17. How is throw exception created in exception handling? Throw method is used to throw an exception manually. It has to declare the exceptions thrown in the method signature and then include a throw statement in the method throw new ExceptionName (“Value”); 18. Differentiate error from exception. How is custom exception created? An Error indicates that a non-recoverable condition has occurred that should not be caught. Error is a subclass of throwable is intended for drastic problem, such as OutOfMemoryError. An exception is an event, which occurs during the execution of a program , that disrupts the normal flow of the program. Exception is a subclass of throwable class, example of such as ArithmeticException. By extending the exception class or one of its subclasses, we can create custom exception. Example class MyException extends Exception { public MyException() {super();} public MyException(String s) {super(s);} } 19. What is the use of Alive() and Join()method ? The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false. final boolean isAlive() The join() method waits for a thread to die. In other words, it causes the currently running threads to
  • 5. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 5 stop executing until the thread it joins with completes its task. 20. How strings are implemented in java? Java implements strings as objects of type String. Once a String object has been created, it is not possible to change the characters that comprise that string. For those cases in which a modifiable string is desired, Java provides two options: • StringBuffer and • StringBuilder. 21. What are the constructors supported for String class? There are several constructors supported for String class are: • String s = new String(); • char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); • char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3); • String s1 = new String(“Apple”); String s2 = new String(s1); 22. List out some of the special string operations in java. Special string operations in java are: • String Literals • String Concatenation • String Concatenation with Other Data Types • String Conversion and toString() 23. List out some of the character extraction operations in java. Some of the character extraction operations in java are: • charAt( ) • getChars( ) • getBytes( ) • toCharArray( ) 24. List out the constructor supported for StringBuffer class. There are four constructors supported for StringBuffer class: • StringBuffer( ) • StringBuffer(int size) • StringBuffer(String str) • StringBuffer(CharSequence chars) 25. List out the methods of StringBuffer class. The methods StringBuffer class: • length() and capacity() • ensureCapacity() • setLength() • charAt() and setCharAt() • getChars() • append() • insert() • reverse() • delete(), deleteCharAt() • replace() • subString()
  • 6. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 6 PART B S. No. Question 1. With suitable example explain how packages are created, imported and used. Elaborate on its package scope A package in Java is used to group related classes, sub packages and interfaces. Think of it as a folder in a file directory. Packages are used to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: • Built-in Packages (packages from the Java API) • User-defined Packages (create your own packages) Defining a Package ✓ To create a package simply include the package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. ✓ The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. ✓ This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Example //save as Simple.java package MyPack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); } } Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting Simple.class file is also in the MyPack directory. Then try executing the Simple class, using the following command line: java MyPack.Simple Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, Simple is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line: java Simple Simple must be qualified with its package name. Importing Packages There are three ways to import the package from outside the package. 1. import package.*; 2. import package.Classname; 3. fully qualified name. 1) Using packagename.*
  • 7. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 7 If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. Example of package that import the packagename.* //save by A.java package pack1; public class A { public void msg() { System.out.println("Hello"); } } //save by B.java package mypack; import pack1.*; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } } Output:Hello 2) Using packagename.Classname If you import package.Classname then only declared class of this package will be accessible. Example of package by import package.Classname //save by A.java package pack1; public class A { public void msg() { System.out.println("Hello"); } } //save by B.java package mypack; import pack1.A; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); }
  • 8. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 8 } Output: Hello 3) Using fully qualified name If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. Example of package by import fully qualified name //save by A.java package pack1; public class A { public void msg() { System.out.println("Hello"); } } //save by B.java package mypack; class B { public static void main(String args[]) { pack.A obj = new pack1.A(); //using fully qualified name obj.msg(); } } Output: Hello Built-in Packages The Java API is a library of prewritten classes that are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much more. For example, java.applet java.awt java.util java.lang java.net The library is divided into packages and classes. The user can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, use the import keyword: Syntax import package.name.Class; // Import a single class
  • 9. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 9 import package.name.*; // Import the whole package Example import java.util.Scanner; // Import a single class import java.util.*; // Import the whole package 2. What is an interface?What are the properties of Interfaces? Write java program to ilustrate use of an interface. INTERFACE An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. It cannot be instantiated just like abstract class. ✓ An interface is a collection of abstract methods (i.e. methods without having definition). ✓ A class that implements an interface inherits abstract methods of the interface. ✓ An interface is not a class. ✓ If a class (provided it is not abstract) implements an interface, then all the methods of interface need to be defined in it. Uses Java interface: There are mainly three reasons to use interface. They are given below. • It is used to achieve abstraction. • By interface, we can support the functionality of multiple inheritance. • It can be used to achieve loose coupling. Declaring Interfaces The interface keyword is used to declare an interface. Here is a simple example to declare an interface: access interface name { final type varname1 = value; final type varname2 = value; return-type method-name1(parameter-list); return-type method-name2(parameter-list); } Interfaces have the following properties: ✓ An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract keyword when declaring an interface. ✓ Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract keyword is not needed. ✓ Methods in an interface are implicitly (i.e. by default) public. The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default, and methods are public and abstract.
  • 10. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 10 Implementing Interfaces ✓ A class can implement more than one interface at a time. ✓ A class can extend only one class, but can implement many interfaces. ✓ An interface itself can extend another interface. ✓ The general form of a class that includes the implements clause looks like this: class classname extends superclass implements interface1 , interface2... { // class-body } Example: interface Message { void message1( ); void message2( ); } class A implements Message { void message1( ) { System.out.println("Good Morning"); } void message2( ) { System.out.println("Good Evening"); } public static void main(String args[]) { A a=new A(); a.message1(); a.message2(); } } 3. Write a Java program to create and use a user defined package in Java. A package in Java is used to group related classes, sub packages and interfaces. Think of it as a folder in a file directory. Packages are used to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: • Built-in Packages (packages from the Java API) • User-defined Packages (create your own packages)
  • 11. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 11 Defining a Package ✓ To create a package simply include the package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. ✓ The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. ✓ This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Example //save as Simple.java package MyPack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); } } Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting Simple.class file is also in the MyPack directory. Then try executing the Simple class, using the following command line: java MyPack.Simple Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, Simple is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line: java Simple Simple must be qualified with its package name. Creating Sub package in a package: We can create sub package in a package in the format: package packagename.subpackagename; e.g.: package pack1.pack2; Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes and interfaces of pack2, we can write import statement as: import pack1.pack2; //Creating a subpackage in a package package pack1.pack2; public class Sample { public void show () { System.out.println ("Hello Java Learners"); } } 4. Explain multithreading, thread states and thread priority.
  • 12. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 12 Multithreading in java is a process of executing multiple threads simultaneously. 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. Multiprocessing and multithreading, both are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation, etc. Thread: A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area. As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) You can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread. Life Cycle of a Thread A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated
  • 13. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 13 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated A thread is in terminated or dead state when its run() method exits. Thread Priority • Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. • Priorities are represented by a number between 1 and 10. • In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses • Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). • Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent. • A thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place are simple: • A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,
  • 14. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 14 or blocking on pending I/O. In this scenario, all other threads are examined, and the highest priority thread that is ready to run is given the CPU. • A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form: final void setPriority(int level) Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread. You can obtain the current priority setting by calling the getPriority() method of Thread, shown here: final int getPriority( ) 5. How threads are created in java? Explain the two implementation methods with example java program The Thread Class and the Runnable Interface There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Creating Thread by extending Thread class: 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. Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface. The Thread class defines several methods that help manage threads. Method Meaning getName Obtain a thread’s name. getPriority Obtain a thread’s priority. isAlive Determine if a thread is still running. join Wait for a thread to terminate. run Entry point for the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method. Example: class Multi extends Thread { public void run() { System.out.println("thread is running...");
  • 15. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 15 } public static void main(String args[]) { Multi t1=new Multi(); t1.start(); } } Output: thread is running... Creating Thread by Implementing Runnable interface The easiest way to create a thread is to create a class that implements the Runnable interface. • To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) We will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can. • After we create a class that implements Runnable, you will instantiate 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 and the name of the new thread is specified by threadName. • After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here: void start( ); Here is an example that creates a new thread and starts it running: Example: class Multi implements Runnable { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi obj=new Multi(); Thread t1 =new Thread(obj); t1.start(); } } Output: thread is running... 6. Explain life cycle of thread with help of a diagram. How do the wait and Notify All/ Notify methods enable cooperation between threads? Life Cycle of a Thread A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New
  • 16. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 16 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated A thread is in terminated or dead state when its run() method exits. Inter Thread Communication using Wait, notify and notifyAll Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: • wait() • notify() • notifyAll() wait( ) 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( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. These methods are declared within Object, as shown here:
  • 17. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 17 final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( ) Steps for Inter thread communication: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock. 6. After completion of the task, thread releases the lock and exits the monitor state of the object. class Customer { int amount=10000; synchronized void withdraw(int amount) { System.out.println("going to withdraw..."); if(this.amount<amount) { System.out.println("Less balance; waiting for deposit..."); try { wait(); } catch(Exception e) {} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount) { System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify();
  • 18. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 18 } } class Samp1 { public static void main(String args[]) { final Customer c=new Customer(); new Thread() { public void run() { c.withdraw(15000); } }.start(); new Thread() { public void run() { c.deposit(10000); } }.start(); } } Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed 7. What is thread synchronization? Discuss with an example Java program 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 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. Using Synchronized Methods: Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. 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. Example 1:
  • 19. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 19 class Table { synchronized void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(400); } catch(Exception e) { System.out.println(e); } } } } class MyThread1 extends Thread { Table t; MyThread1(Table t) { this.t=t; } public void run() { t.printTable(5); } } class MyThread2 extends Thread { Table t; MyThread2(Table t) { this.t=t; } public void run() { t.printTable(100); } } public class TestSynchronization2 { public static void main(String args[]) { Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output: 5
  • 20. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 20 10 15 20 25 100 200 300 400 500 Using synchronized Statement: While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by you, but by a third party and you do not have access to the source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement: synchronized (object) { // statements to be synchronized } Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor. class Table { void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(400); } catch(Exception e) {System.out.println(e);} } } } class MyThread1 extends Thread { Table t ; int N; MyThread1(Table t,int n) { this.t=t; N=n;
  • 21. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 21 } public void run() { synchronized(t) //synchronized block { t.printTable(n); } } } public class Test { public static void main(String args[]) { Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread1 t2=new MyThread1(obj); t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200 300 400 500 Example: class A extends Thread { int total; synchronized public void run() { total = 0; for(int i=1;i<=5;i++) { total=total + i; } notify(); } } public class Example3Thread { public static void main(String[] args) { A obj = new A(); try
  • 22. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 22 { obj.start(); synchronized(obj) { System.out.println("Waiting...."); obj.wait(); } } catch(Exception e) { } System.out.println("Total = " + obj.total); } } OUTPUT: Waiting.... Total = 15 8. Explain searching and modifying a String value with an example program. i) Searching Strings The String class provides two methods that allow you to search a string for a specified character or substring: • indexOf( ) Searches for the first occurrence of a character or substring. • lastIndexOf( ) Searches for the last occurrence of a character or substring. These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or 1 –on failure. To search for the first occurrence of a character, use int indexOf(int ch) To search for the last occurrence of a character, use int lastIndexOf(int ch) Here, ch is the character being sought. To search for the first or last occurrence of a substring, use int indexOf(String str) int lastIndexOf(String str) Here, str specifies the sub-string. You can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex) intlastIndexOf(intch,intstartIndex) intindexOf(Stringstr,intstartIndex) int lastIndexOf(String str, int startIndex) Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf(), the search runs from startIndex to zero. The following example shows how to use the various index methods to search inside of Strings: class indexOfDemo{ public static void main(String args[]){ String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println(s); System.out.println("indexOf(t) = " +s.indexOf('t')); System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t')); System.out.println("indexOf(the) = " +s.indexOf("the"));
  • 23. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 23 System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the")); System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10)); System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60)); System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10)); System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));}} Here is the output of this program: Now is the time for all good men to come to the aid of their country. indexOf(t) =7 lastIndexOf(t) = 65 indexOf(the) = 7 lastIndexOf(the) = 55 indexOf(t, 10) = 11 lastIndexOf(t, 60) = 55 indexOf(the, 10) = 44 lastIndexOf(the, 60) = 55 ii) Modifying a String Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use one of the following String methods, which will construct a new copy of the string with your modifications complete. a) substring( ) Can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex) Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string: class StringReplace{ public static void main(String args[]){ String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i; do { System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org =result; } } while(i !=-1);}} The output from this program is shown here: This is a test. This is, too. Thwas is a test. This is, too.
  • 24. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 24 Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too. b) concat( ) It is possible to concatenate two strings using concat( ), shown here: String concat(String str) This method creates a new object that contains the invoking string with the contents of str appended to the end. concat() performs the same function as +. For example, String s1 = "one"; String s2 = s1.concat("two"); puts the string “onetwo” into s2. It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two"; c) replace( ) The replace() method has two forms. The first replaces all occurrences of one character in the invoking string with another character. It has the following general form: String replace(char original, char replacement) Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example, String s = "Hello".replace('l', 'w'); puts the string “Hewwo” into s.The second form of replace( ) replaces one character sequence with another. It has this general form: String replace(CharSequence original, CharSequence replacement) This form was added by J2SE 5. d) trim( ) The trim() method returns a copy of the invoking string from which any leading and trailing white space has been removed. It has this general form: String trim( ) Here is an example: String s=" HelloWorld ".trim(); This puts the string “Hello World” into s. The trim() method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state’s capital. It uses trim() to remove any leading or trailing white space that may have inadvertently been entered by the user. import java.io.*; class UseTrim{ public static void main(String args[]) throws IOException{ BufferedReader br = newBufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter State: "); do { str = br.readLine(); str = str.trim(); // remove whitespace if(str.equals("Illinois")) System.out.println("Capital is Springfield."); else if(str.equals("Missouri"))
  • 25. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 25 System.out.println("Capital is Jefferson City."); else if(str.equals("California")) System.out.println("Capital is Sacramento."); else if(str.equals("Washington")) System.out.println("Capital is Olympia."); } while(!str.equals("stop"));}} 9. Explain StringBuffer class methods in java with an example program. StringBuffer StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded +operator. a) StringBuffer Constructors StringBuffer defines these four constructors: StringBuffer( ) StringBuffer(int size) StringBuffer(String str) StringBuffer(CharSequence chars) The default constructor reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place. The fourth constructor creates an object that contains the character sequence contained inchars. b) length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms: int length( ) int capacity( ) Here is an example: class StringBufferDemo{ public static void main(String args[]){ StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity());}} Here is the output of this program, which shows how StringBuffer reserves extra spacefor additional manipulations: buffer = Hello length = 5 capacity = 21
  • 26. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 26 Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added. c) ensureCapacity( ) If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form: void ensureCapacity(int capacity) Here, capacity specifies the size of the buffer. d) setLength() To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here: void setLength(int len) Here, len specifies the length of the buffer. This value must be nonnegative.When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length(), then the characters stored beyond the new length will be lost. e) charAt( ) and setCharAt( ) The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here: char charAt(int where) void setCharAt(int where, char ch) For charAt(), where specifies the index of the character being obtained. For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer. The following example demonstrates charAt( ) and setCharAt( ): class setCharAtDemo{ public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1));}} Here is the output generated by this program: buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i f) getChars() To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: void getChars(int sourceStart,int sourceEnd,char target[], int targetStart) Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
  • 27. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 27 specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd– 1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. g) append() The append() method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has several overloaded versions. Here are a few of its forms: StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example: class appendDemo{ public static void main(String args[]){ String s; int a = 42; StringBuffer sb = new StringBuffer(40); s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); } } The output of this example is shown here: a = 42! h) insert( ) The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings, Objects, and CharSequences. Like append(), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. The following sample program inserts “like” between “I” and “Java”: class insertDemo{ public static void main(String args[]){ StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb);}} The output of this example is shown here: I like Java! i) reverse( ) Can reverse the characters within a StringBuffer object using reverse( ), shown here: StringBuffer reverse( ) This method returns the reversed object on which it was called. The following
  • 28. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 28 program demonstrates reverse(): class ReverseDemo{ public static void main(String args[]){ StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s);}} Here is the output produced by the program: abcdef fedcba j) delete( ) and deleteCharAt( ) You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ). These methods are shown here: StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex– 1. The resulting StringBuffer object is returned. The deleteCharAt() method deletes the character at the index specified by loc. It returns the resulting StringBuffer object. Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods: class deleteDemo{ public static void main(String args[]){ StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb);}} The following output is produced: After delete: This a test. After deleteCharAt: his atest. k) replace( ) You can replace one set of characters with another set inside a StringBuffer object by calling replace( ). Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str) The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex1 – is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned. The following program demonstrates replace( ): class replaceDemo { public static void main(String args[]){ StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb);}} Here is the output: After replace: This was a test. l) substring( ) You can obtain a portion of a StringBuffer by calling substring( ). It has the following two forms: String substring(int startIndex) String substring(int startIndex, int endIndex)
  • 29. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 29 The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex1 –. 10. Discuss about the Java exception handling mechanisms with suitable examples. EXCEPTION HANDLING Error occurred in a program can be of two types: syntax error or logical error. • An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. • A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. • Exception Handling is a mechanism by which exception occurred in a program is handled. • The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. S.No Keyword/Block Meanings 1 try block The statements which are expected to throw exception are kept inside try block. 2 catch block If an exception occurs within the try block, it is throws an exception to the catch block which handle it in some rational manner. 3 throw To manually throw an exception, use the keyword throw. 4 throws A throws clause lists the types of exceptions that a method might throw. 5 finally Any code that absolutely must be executed before a method returns is put in a finally block. The general form of an exception-handling block is: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } finally { // block of code to be executed before try block ends } Exception Types All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.
  • 30. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 30 • The Throwable class has two subclasses Error and Exception. • Error and Exception classes are used for handling errors in java. Using try and catch The following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error. Demonstration of Division by zero Exception. class Ex { public static void main(String args[ ]) { int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement. Notice that the call to println ( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism. 11. Demonstrate the implemation of Inter-thread communication using a sample java program Inter Thread Communication using Wait, notify and notifyAll Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: • wait() • notify() • notifyAll() wait( ) 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( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest
  • 31. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 31 priority thread will run first. These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( ) Steps for Inter thread communication: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock. 6. After completion of the task, thread releases the lock and exits the monitor state of the object. class Customer { int amount=10000; synchronized void withdraw(int amount) { System.out.println("going to withdraw..."); if(this.amount<amount) { System.out.println("Less balance; waiting for deposit..."); try { wait(); } catch(Exception e) {} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount) { System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... ");
  • 32. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 32 notify(); } } class Samp1 { public static void main(String args[]) { final Customer c=new Customer(); new Thread() { public void run() { c.withdraw(15000); } }.start(); new Thread() { public void run() { c.deposit(10000); } }.start(); } } Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed PART C S. No. Question 1. Develop a java program to find the area of rectangle, square, and circle using interfaces. interface Area { float pi=3.14F; float compute(float x, float y); } class Rectangle implements Area { public float compute (float x, float y) { return(x*y); } } class Square implements Area {
  • 33. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 33 public float compute(float x, float y) { return(x*x); } } class Circle implements Area { public float compute(float x, float y) { return(pi*x*x); } } class Areademo { public static void main(String args[]) { Rectangle rect=new Rectangle(); Square sqr=new Square(); Circle cir=new Circle(); System.out.println("Area of rectangle : "+rect.compute(5,10)); System.out.println("Area of square : "+sqr.compute(5,0)); System.out.println("Area of circle : "+cir.compute(5,0)); } } OUTPUT: Area of rectangle : 50.0 Area of square : 25.0 Area of circle : 78.5 2. Write java application program for generating four threads to perform following operations: • Getting N numbers as input • Printing even numbers • Printing odd numbers • Computing average import java.util.Scanner; class Compute { int num; synchronized void getnum() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number:"); num = scanner.nextInt(); System.out.println("Number is :"+num); } synchronized void odd() {
  • 34. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 34 try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("ODD NUMBERS"); for (int i=1;i<=num;i++) if(i%2 != 0) System.out.println(i); } synchronized void even() { try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("EVEN NUMBERS"); for (int i=1;i<=num;i++) if(i%2 == 0) System.out.println(i); } synchronized void average() { try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } int sum=0; for (int i=1;i<=num;i++) { sum=sum+i; } float avg = (float)sum / num; System.out.println("Average of numbers upto " + num + " is " + avg);
  • 35. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 35 } } class A extends Thread { Compute obj; A(Compute c1) { obj=c1; start(); } public void run() { obj.getnum(); } } class B extends Thread { Compute obj; B(Compute c1) { obj=c1; start(); } public void run() { obj.odd(); } } class C extends Thread { Compute obj; C(Compute c1) { obj=c1; start(); } public void run() { obj.even(); } } class D extends Thread { Compute obj;
  • 36. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 36 D(Compute c1) { obj=c1; start(); } public void run() { obj.average(); } } public class FourThread { public static void main(String[] args) { Compute ob=new Compute(); A obj1 = new A(ob); B obj2 = new B(ob); C obj3 = new C(ob); D obj4 = new D(ob); } } OUTPUT: Enter the number: 10 Number is :10 Average of numbers upto 10 is 5.5 EVEN NUMBERS 2 4 6 8 10 ODD NUMBERS 1 3 5 7 9 3. Write a java program to find factorial of an integer given from the keyboard. Using exception handling mechanism, display appropriate message if the input from keyboard is not a valid integer. import java.util.*; class Factorial
  • 37. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 37 { public static void main(String args[]) { try { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number:"); int num = scanner.nextInt(); int fact=1; for(int i=1;i<=num;i++) fact=fact*i; System.out.println("Factorial of " + num +" is "+fact); } catch(InputMismatchException e) { System.out.println("You have entered invalid data"); } } } OUTPUT 1: Enter the number: 5 Factorial of 5 is 120 OUTPUT 2: Enter the number: 25.64 You have entered invalid data OUTPUT 3: Enter the number: ABC You have entered invalid data 4. Write a program to find addition of two numbers given from the keyboard. Using exception handling, display appropriate message if the inputs are not valid numbers. import java.util.*; class Addition { public static void main(String args[]) { try { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number1:"); int num1 = scanner.nextInt(); System.out.print("Enter the number2:"); int num2 = scanner.nextInt();
  • 38. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 38 int sum = num1 + num2; System.out.println("Total is " + sum ); } catch(InputMismatchException e) { System.out.println("You have entered invalid data"); } } } OUTPUT 1: Enter the number1:5 Enter the number2:10 Total is 15 OUTPUT 2: Enter the number1:ABC You have entered invalid data OUTPUT 3: Enter the number1:5 Enter the number2:23.6 You have entered invalid data 5. a) Explain the usage of nested try with an example. b) Write a program using throw for catching an error that is not divisible by zero. a) Explain the usage of nested try with an example. The try block within a try block is known as nested try block in java. Why use nested try block Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntax: try { statement 1; try { statement 1; } catch(Exception e) { } } catch(Exception e) { } Example : class Excep6 { public static void main(String args[]) {
  • 39. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 39 try { try { System.out.println("going to divide"); int b =39/0; } catch(ArithmeticException e) { System.out.println(e); } try { int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement); } catch(Exception e) { System.out.println("handeled"); } System.out.println("normal flow.."); } } OUTPUT: going to divide java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5 other statement normal flow.. b) Write a program using throw for catching an error that is not divisible by zero. import java.util.*; class Addition { public static void main(String args[]) { try { int a=100; Scanner scanner = new Scanner(System.in); System.out.println("Enter the number:"); int b = scanner.nextInt(); if(b==0) { throw new ArithmeticException("Division by ZERO"); } else { int c=a/b; System.out.println ("Result: "+c);
  • 40. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 40 } } catch(ArithmeticException e) { System.out.println(e); } } } OUTPUT 1: Enter the number: 5 Result: 20 OUTPUT 2: Enter the number: 0 java.lang.ArithmeticException: Division by ZERO 6. Write a thread synchronization implementation program that displays contents of text supplied through three threads. class Callme { synchronized void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); }
  • 41. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 41 public void run() { target.call(msg); } } class SyncThread { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } } OUTPUT: [Hello] [World] [Synchronized] 7. Write a java program to illustrate about thread priorities. class ThreadDemo extends Thread { public void run() { System.out.println("Inside run method"); } public static void main(String[]args) { ThreadDemo t1 = new ThreadDemo(); ThreadDemo t2 = new ThreadDemo(); ThreadDemo t3 = new ThreadDemo(); System.out.println("t1 thread priority : " + t1.getPriority()); System.out.println("t2 thread priority : " + t2.getPriority()); System.out.println("t3 thread priority : " + t3.getPriority()); t1.setPriority(2); t2.setPriority(5); t3.setPriority(8);
  • 42. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 42 System.out.println("t1 thread priority : " + t1.getPriority()); System.out.println("t2 thread priority : " + t2.getPriority()); System.out.println("t3 thread priority : " + t3.getPriority()); //Main Thread System.out.print(Thread.currentThread().getName()); System.out.println("Main thread priority : " + Thread.currentThread().getPriority()); // Main thread priority is set to 10 Thread.currentThread().setPriority(10); System.out.println("Main thread priority : " + Thread.currentThread().getPriority()); } } OUTPUT: t1 thread priority : 5 t2 thread priority : 5 t3 thread priority : 5 t1 thread priority : 2 t2 thread priority : 5 t3 thread priority : 8 mainMain thread priority : 5 Main thread priority : 10 8. Design a program using Thread class and Runnable interfaces of your choice and compare the differences. The Thread Class and the Runnable Interface There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Creating Thread by extending Thread class: 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. Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface. The Thread class defines several methods that help manage threads. Method Meaning getName Obtain a thread’s name. getPriority Obtain a thread’s priority. isAlive Determine if a thread is still running. join Wait for a thread to terminate. run Entry point for the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method.
  • 43. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 43 Example: class Multi extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi t1=new Multi(); t1.start(); } } Output: thread is running... Creating Thread by Implementing Runnable interface The easiest way to create a thread is to create a class that implements the Runnable interface. • To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) We will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can. • After we create a class that implements Runnable, you will instantiate 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 and the name of the new thread is specified by threadName. • After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here: void start( ); Here is an example that creates a new thread and starts it running: Example: class Multi implements Runnable { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi obj=new Multi(); Thread t1 =new Thread(obj); t1.start(); } }
  • 44. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 – QUESTION BANK / SMART MATERIAL Page 44 Output: thread is running... Basis for Comparison Thread class Runnable interface Basic Each thread creates a unique object and gets associated with it. Multiple threads share the same objects. Memory As each thread create a unique object, more memory required. As multiple threads share the same object less memory is used. Extending In Java, multiple inheritance not allowed hence, after a class extends Thread class, it can not extend any other class. If a class define thread implementing the Runnable interface it has a chance of extending one class. Use A user must extend thread class only if it wants to override the other methods in Thread class. If you only want to specialize run method then implementing Runnable is a better option. Coupling Extending Thread class introduces tight coupling as the class contains code of Thread class and also the job assigned to the thread Implementing Runnable interface introduces loose coupling as the code of Thread is separate form the job of Threads.