0% found this document useful (0 votes)
29 views44 pages

Java Packages and Exception Handling Guide

The document provides an overview of Java packages, including built-in and user-defined packages, their advantages, and how to create and use them. It also covers exception handling in Java, detailing keywords like try, catch, finally, throw, and throws, along with the differences between checked and unchecked exceptions. Additionally, it includes examples of custom exceptions and nested try blocks, as well as a lab component for creating a custom exception and a package.

Uploaded by

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

Java Packages and Exception Handling Guide

The document provides an overview of Java packages, including built-in and user-defined packages, their advantages, and how to create and use them. It also covers exception handling in Java, detailing keywords like try, catch, finally, throw, and throws, along with the differences between checked and unchecked exceptions. Additionally, it includes examples of custom exceptions and nested try blocks, as well as a lab component for creating a custom exception and a package.

Uploaded by

Divyarani Banad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-4

Packages in Java
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can
be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Packages


❖ Packages allow related classes and interfaces to be grouped together
❖ Packages allow better organization
❖ Use of packages help in easier accessibility.
❖ Packages facilitate flexibility in adding new features
❖ Packages also allow reuse of classes and interfaces

Creating and using packages


Adding a class to a Package : We can add more classes to a created package by using package name
at the top of the program and saving it in the package directory. We need a new java file to define a
public class, otherwise we can add the new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not imported
by default, they have to imported explicitly. Also, members of a subpackage have no access privileges,
i.e., they are considered as different package for protected and default access specifiers.
Example :
import [Link].*;
util is a subpackage created inside java package.

Accessing classes inside a package


Consider following two statements :
// import the Vector class from util package.
import [Link];

// import all the classes from util package


import [Link].*;
• First Statement is used to import Vector class from util package which is contained
inside java.
• Second statement imports all the classes from util package.
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import [Link];

// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
89
// date class so using a fully qualified name to avoid conflict
import [Link];
import [Link];

Types of packages:

Built-in Packages These packages consist of a large number of classes which are a part of
Java [Link] of the commonly used built-in packages are:
1) [Link]: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) [Link]: Contains classes for creating Applets.
5) [Link]: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) [Link]: Contain classes for supporting networking operations. User-defined packages These are
the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package names.

package myPackage;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import [Link];

public class PrintName


{
90
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
[Link](name);
}
}
Note : [Link] must be saved inside the myPackage directory since it is a part of the package.

Member access and packages in Java

public keyword
If a class member is “public” then it can be accessed from anywhere. The member variable or method
is accessed globally. This is the simplest way to provide access to class members. However, we should
take care of using this keyword with class variables otherwise anybody can change the values. Usually,
class variables are kept as private and getter-setter methods are provided to work with them.
private keyword
If a class member is “private” then it will be accessible only inside the same class. This is the most
restricted access and the class member will not be visible to the outer world. Usually, we keep class
variables as private and methods that are intended to be used only inside the class as private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same package and to
the subclasses. This modifier is less restricted from private but more restricted from public access.
Usually, we use this keyword to make sure the class variables are accessible only to the subclasses.

91
default access
If a class member doesn’t have any access modifier specified, then it’s treated with default access. The
access rules are similar to classes and the class member with default access will be accessible to the
classes in the same package only. This access is more restricted than public and protected but less
restricted than private.

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained. In Java, an exception is an event that disrupts
the normal flow of the program. It is an object which is thrown at runtime. Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc. The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.

92
Top Level Exception Hierarchy in Java

When a predefined exception occurs, JVM (Java runtime system) creates an object of predefined
exception class. All exceptions are derived from [Link] class but not all exception classes
are defined in the same package. All the predefined exceptions supported by java are organized as
subclasses in a hierarchy under the Throwable class. The Throwable class is the root of exception
hierarchy and is an immediate subclass of Object class. Error class is the subclass of Throwable class
and a superclass of all the runtime error classes. It terminates the program if there is problem-related
93
to a system or resources (JVM). Exception class represents errors caused by the program and by
external factors. Exception class is a subclass of Throwable class and a superclass of all the exception
classes. RuntimeException class is a subclass of the Exception class. It is thrown by JVM or
programmatically when an arithmetic operation performed in the program is incorrect or defect/bug
occurs in the program’s code.

Example Exception handling program:


class Exc
{
public static void main(String any[])
{
int a=5,b=0;
int arr[]={1,2,3};
try{
[Link](a/b);
[Link](arr[-1]);
}

catch(ArithmeticException e)
{
[Link]("specific");
[Link]();
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]();
}
catch(Exception e)
{
[Link]("generic");
[Link](); //Display exception details
}
[Link]("I continue");
}
}

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try block. Every
statement that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).

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.
94
Java Nested try Example
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
When any try block does not have a catch block for a particular exception, then the catch block of the
outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try
block is executed. If none of the catch block specified in the code is unable to handle the exception,
then the Java runtime system will handle the exception. Then it displays the system generated message
for that exception.

95
Java throws Keyword
The throws keyword is used to declare the list of exception that a method may throw during execution
of program. Any method that is capable of causing exceptions must list all the exceptions possible
during its execution, so that anyone calling that method gets a prior knowledge about which exceptions
are to be handled. A method can do so by using the throws keyword.
Syntax:
type method_name(parameter_list) throws exception_list
{
// definition of method
}
Example:
class Test
{
static void check() throws ArithmeticException
{
[Link]("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
[Link]("caught" + e);
}
}
}

Difference between throw and throws


throw throws
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is followed by an instance of throws keyword is followed by one or more
Throwable class or one of its sub-classes. Exception class names separated by commas.
throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using We can declare multiple exceptions (separated by
throw keyword. commas) using throws keyword.

96
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is
always executed whether an exception has occurred or not. Using a finally block, it lets you run any
cleanup type statements that you want to execute, no matter what happens in the protected code. A
finally block appears at the end of catch block.
Eg:
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
[Link]("out of try");
try
{
[Link]("Access invalid element"+ a[3]);

}
catch(Exception e){ return;}
finally
{
[Link]("finally is always executed.");
}
}
}

Checked vs Unchecked Exceptions in Java


n Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
In Java, there are two types of exceptions:
1. Checked exceptions
2. Unchecked exceptions

97
Checked Exceptions in Java
These are the exceptions that are checked at compile time. If some code within a method throws a
checked exception, then the method must either handle the exception or it must specify the
exception using the throws keyword. In checked exceptions, there are two types: fully checked and
partially checked exceptions. A fully checked exception is a checked exception where all its child
classes are also checked, like IOException, and InterruptedException. A partially checked exception
is a checked exception where some of its child classes are unchecked, like an Exception.
Eg: Java Program to Illustrate Checked Exceptions
import [Link].*;
class ET {
public static void main(String[] args)
{
FileReader file = new FileReader("[Link]");
// Creating object as one of ways of taking input
BufferedReader fileInput = new BufferedReader(file);
[Link]();
}
}

98
Unchecked Exceptions in Java
These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked,
so it is not forced by the compiler’s to either handle or specify the exception. It is up to the
programmers to be civilized and specify or catch the exceptions. In Java, exceptions
under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
Eg: Java Program to Illustrate Un-checked Exceptions
class UET{
public static void main(String args[])
{
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}

Chained Exceptions in Java


In Java, a chained exception is a technique that enables programmers to associate one Exception with
another. By providing additional information about a specific exception, debugging can be made easier.
A chained exception is created by wrapping an existing exception in a new exception, which becomes
the root cause of the new Exception. The new Exception can provide additional information, while the
original Exception contains the actual error message and stack trace. It makes it easier to determine
and fix the problem's source. Chained exceptions are especially useful when an exception is thrown
due to another exception. In Java, a chained exception is created using one of the constructors of the
exception class.

Example Java program to demonstrate chained exceptions:


class Chain
{
static void generate()
{
NullPointerException e1=new NullPointerException("nnn");
ArithmeticException e2=new ArithmeticException("aaa");
[Link](e2);
throw e1;
}
public static void main(String any[])
{
try{
generate();
}
99
catch(NullPointerException e)
{
[Link](e);
[Link]([Link]());
}
}
}

LABCOMPONENT:
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

class DivideByZero extends Exception


{
String message;
DivideByZero(String message)
{
[Link]=message;
}
public String toString()
{
return "USer attempted "+message;
}
}
class DZ
{
static int compute(int a,int b) throws DivideByZero
{
if(b==0)
throw new DivideByZero("Divide By Zero...");
return a/b;
}
public static void main(String args[])
{
int a=[Link](args[0]);
int b=[Link](args[1]);
try{
[Link](compute(a,b));
}
catch(DivideByZero z)
{
[Link](z);
}
finally{
[Link]("I am always der...");
100
}
}
}

10. Develop a JAVA program to create a package named mypack and


import & implement it in a suitable class

Create a subfolder mypack and inside it create following class:


package mypack;
public class Account
{
double bal;
String name;
String accno;
public Account(String accno, String name,double bal)
{
[Link]=accno;
[Link]=bal;
[Link]=name;
}
public void show()
{
[Link](“Account Number=”+accno+"Account Name="+name+",
Balance="+bal);
}
}

In the folder above this, create following main class:


import mypack.*;
class AC
{
public static void main(String any[])
{
Account a1=new Account(“101”,"James",20000);
[Link]();
}
}

101
Module-5
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a
lightweight sub-process, the smallest unit of processing. 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.

Single Thread Model


A single threaded Java application model is depicted in Figure 1. According to the model, when
processes request for a shared resource like CPU, memory, database or files it is registered in a queue.
The processes keeps waiting. Then the scheduler checks whether resource is free and if free allots the
resource to the waiting process. It is a slow model as resources cannot be concurrently accessed and
processes need to synchronously wait until the resource becomes available.

The Java Thread Model


The Java run-time system depends on threads for many things. Threads reduce inefficiency by
preventing the waste of CPU cycles.
Threads exist in several states. Following are those states:
• New — When we create an instance of Thread class, a thread is in a new state.
• Runnable — The Java thread is in running state. Start() method is called to move to run
state from new state.
• Suspended/Blocked — A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it left off.
Thread can be suspended using suspend() until notify() occurs or sleep() for specific
milliseconds. Once their suspension is over, they come back to Runnable state.
• Dead — A thread can be terminated, which halts its execution immediately at any given
time. Once a thread is terminated, it cannot be resumed.
102
Figure: Life Cycle of a thread in Java

Thread Priority
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases,
the thread scheduler 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. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly
in a Java program.

Methods of Thread Priority


public final int getPriority(): The [Link]() method returns the priority of the given
thread.
public final void setPriority(int newPriority): The [Link]() method updates or
assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Need of Thread priority:
When high priority threads request, low priority threads need to relinquish control.
Thread pre-emption is done based on priority and context switch among thread occur.

103
Thread Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Monitors and Thread Synchronization


Java's monitor supports two kinds of thread synchronization: mutual
exclusion and cooperation. Mutual exclusion, which is supported in the Java virtual machine via
object locks, enables multiple threads to independently work on shared data without
interfering with each other. Cooperation, which is supported in the Java virtual machine via the
wait and notify methods of class Object, enables threads to work together towards a common
goal.
A monitor is like a building that contains one special room that can be occupied by only one
thread at a time. The room usually contains some data. From the time a thread enters this room
to the time it leaves, it has exclusive access to any data in the room. Entering the monitor
building is called "entering the monitor." Entering the special room inside the building is called
"acquiring the monitor." Occupying the room is called "owning the monitor," and leaving the
room is called "releasing the monitor." Leaving the entire building is called "exiting the
monitor."
One thread must be able to execute a monitor region from beginning to end without another
thread concurrently executing a monitor region of the same monitor. A monitor enforces this
one-thread-at-a-time execution of its monitor regions. The only way a thread can enter a
monitor is by arriving at the beginning of one of the monitor regions associated with that
monitor. The only way a thread can move forward and execute the monitor region is by
acquiring the monitor.
When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the
associated monitor. The entry set is like the front hallway of the monitor building. If no other
thread is waiting in the entry set and no other thread currently owns the monitor, the thread
acquires the monitor and continues executing the monitor region. When the thread finishes
executing the monitor region, it exits (and releases) the monitor.
If a thread arrives at the beginning of a monitor region that is protected by a monitor already
owned by another thread, the newly arrived thread must wait in the entry set. When the
current owner exits the monitor, the newly arrived thread must compete with any other threads
also waiting in the entry set. Only one thread will win the competition and acquire the monitor.
104
The first kind of synchronization listed above, mutual exclusion, refers to the mutually exclusive
execution of monitor regions by multiple threads. At any one time, only one thread can be
executing a monitor region of a particular monitor. In general, mutual exclusion is important
only when multiple threads are sharing data or some other resource. If two threads are not
working with any common data or resource, they usually can't interfere with each other and
needn't execute in a mutually exclusive way.
The other kind of synchronization listed above as supported by monitors is cooperation.
Whereas mutual exclusion helps keep threads from interfering with one another while sharing
data, cooperation helps threads to work together towards some common goal.
Cooperation is important when one thread needs some data to be in a particular state and
another thread is responsible for getting the data into that state. For example, one thread, a
"read thread," may be reading data from a buffer that another thread, a "write thread," is filling.
The read thread needs the buffer to be in a "not empty" state before it can read any data out
of the buffer. If the read thread discovers that the buffer is empty, it must wait. The write thread
is responsible for filling the buffer with data. Once the write thread has done some more
writing, the read thread can do some more reading.
The form of monitor used by the Java virtual machine is called a "Wait and Notify" monitor. (It
is also sometimes called a "Signal and Continue" monitor.) In this kind of monitor, a thread that
currently owns the monitor can suspend itself inside the monitor by executing a wait command.
When a thread executes a wait, it releases the monitor and enters a wait set. The thread will
stay suspended in the wait set until some time after another thread executes a notify
command inside the monitor. When a thread executes a notify, it continues to own the monitor
until it releases the monitor of its own accord, either by executing a wait or by completing the
monitor region. After the notifying thread has released the monitor, the waiting thread will be
resurrected and will reacquire the monitor.

Implementing Threads in Java

Two ways to implement Thread in Java is to use (i) Inheritance channel where extends Thread class is
used and (ii) Interface channel where implements Runnable interface is used.

Java Thread Methods


Method Description
start() It is used to start the execution of the thread.
run() It is used to do an action for a thread.

105
sleep() It sleeps a thread for the specified amount of time.
currentThread() It returns a reference to the currently executing thread object.

join() It waits for a thread to die.


getPriority() It returns the priority of the thread.
setPriority() It changes the priority of the thread.
getName() It returns the name of the thread.
setName() It changes the name of the thread.
getId() It returns the id of the thread.
isAlive() It tests if the thread is alive.
suspend() It is used to suspend the thread.
resume() It is used to resume the suspended thread.
stop() It is used to stop the thread.
getState() It is used to return the state of the thread.
toString() It is used to return a string representation of this thread, including
the thread's name, priority, and thread group.
notify() It is used to give the notification for only one thread which is
waiting for a particular object.
notifyAll() It is used to give the notification to all waiting threads of a
particular object.

Java program to illustrate Thread methods for Main Thread


class Thr
{
public static void main(String any[]) throws InterruptedException
{
Thread t=[Link]();
[Link]([Link]());
[Link]("My Thread");
[Link](3000);
[Link]([Link]());

}
}

Java program to illustrate Thread creation using Runnable Interface


class NT1 implements Runnable
{
Thread t;
NT1()
{
t=new Thread(this,"my thread");
}
public void run()

106
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
107
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](1000);
}
}
}

Java program to illustrate multiple threading


class NT1 implements Runnable
{
Thread t;
String tname;
NT1(String tname)
{
[Link]=tname;
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link](tname+":"+i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class MThread
{
public static void main(String any[]) throws InterruptedException
{
108
NT1 n1=new NT1("Thread1");
NT1 n2=new NT1("Thread2");
NT1 n3=new NT1("Thread3");

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}

Race Condition in Java


Java is a multi-threaded programming language and there is a higher risk to occur race conditions.
Because the same resource may be accessed by multiple threads at the same time and may change the
data. We can say that race condition is a concurrency bug. It is closely related to deadlock in Java. It is
a condition in which the critical section (a part of the program where shared memory is accessed) is
concurrently executed by two or more threads. It leads to incorrect behavior of a program. In layman
terms, a race condition can be defined as, a condition in which two or more threads compete together
to get certain shared [Link] example, if thread A is reading data from the linked list and another
thread B is trying to delete the same data. This process leads to a race condition that may result in run
time error. Java Program to illustrate race conditions

class Callme{
public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
109
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output depends on thread who wins race in getting processor and a Thread synchronization is required.

Java program to illustrate Thread synchronization


(i) Using synchronized methods
class Callme
{
synchronized public void callme(String mesg) //Synchronized method
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
110
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);

}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
111
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
[Link](msg);
}
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Inter-thread Communication in Java


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()
112
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed. The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Producer-Consumer problem
In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a
classic example of a multi-process synchronization problem. The problem describes two processes,
the producer and the consumer, which share a common, fixed-size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece
at a time.

Solution program for Producer-Consumer problem using Multi-threading


class Item
{
int data;
boolean lock=false;
synchronized void put(int data)
{
while(lock){
try{ wait();}
catch(InterruptedException e){ };
}
lock=true;
notify();
[Link]=data;

}
synchronized void get()
{
while(!lock)
{
try{ wait();}
catch(InterruptedException e){ };
}
lock=false;
notify();
113
[Link](data);
}
}
class Producer implements Runnable
{
Item i;
Thread t;
Producer(Item i)
{
this.i=i;
t=new Thread(this,"Producer");
}
public void run()
{
int j=0;
while(true)
{
[Link](j);
j++;
}
}
}
class Consumer implements Runnable
{
Item i;
Thread t;
Consumer(Item i)
{
this.i=i;
t=new Thread(this,"Consumer");
}
public void run()
{
while(true)
{
[Link]();
}
}
}
class PCS
{
public static void main(String any[]) throws InterruptedException
{
Item i=new Item();
Producer p=new Producer(i);
114
Consumer c= new Consumer(i);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting
for an object lock, that is acquired by another thread and second thread is waiting for an object lock
that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.

Program to illustrate deadlocking among Threads in Java:


class A
{
}
class B
{
}
class T1 implements Runnable
{
String name;
Thread t;
A a;
B b;
T1(String name,A a,B b)
{
t=new Thread(this,name);
this.a=a;
this.b=b;
}
public void run()
{
synchronized(a)
{
[Link]("Thread 1 locked a");
try{[Link](1000);}
catch(InterruptedException e){ };
115
synchronized(b)
{
[Link]("Thread 1 locked b");
}
}
}
}
class T2 implements Runnable
{
String name;
Thread t;
A a;
B b;
T2(String name,A a,B b)
{
t=new Thread(this,name);
this.a=a;
this.b=b;
}
public void run()
{
synchronized(b)
{
[Link]("Thread 2 locked b");
try{ [Link](1000);}
catch(InterruptedException e){ };
synchronized(a)
{
[Link]("Thread 2 locked a");
}
}
}
}
class Deadlock
{
public static void main(String args[]) throws InterruptedException
{
A a=new A();
B b=new B();
T1 t1=new T1("first",a,b);
T2 t2=new T2("second",a,b);
[Link]();
[Link]();
[Link]();
[Link]();
116
}
}

Suspending, resuming, and stopping threads in Java


Java's threads allow for concurrent processing of multiple requests. Java includes functionality to
pause, resume, and terminate running threads. Using these functions, you can manage thread
execution and guarantee that it proceeds normally. However, modern Java does not support suspend()
and resume() methods. We need to implement them using synchronization and inter-thread
communication.
Java program to demonstrate suspending and resuming of threads
class T implements Runnable
{
Thread t;
String name;
boolean sf;
T(String name)
{
t=new Thread(this,name);
}
public void run()
{
for(int i=10;i>=0;i--)
{
[Link]([Link]()+":"+i);
try{[Link](500);}
catch(InterruptedException e){ };
synchronized(this)
{
while(sf)
{
try{ wait();}
catch(InterruptedException e){ };
}
}
}
}
synchronized void mysuspend()
{
sf=true;

}
synchronized void myresume()
{
sf=false;
notify();
117
}
}
class SRT
{
public static void main(String any[]) throws InterruptedException
{
T t1=new T("first");
T t2=new T("second");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Java Enumerations
The Enum in Java is a data type which contains a fixed set of constants. It can be used for days
of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY)
, directions (NORTH, SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc. According to
the Java naming conventions, we should have all constants in capital letters. So, we have enum
constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available since
JDK 1.5. Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java
is more powerful. Here, we can define an enum either inside the class or outside the class.

118
Java program to demonstrate Enumeration constants and their usage
import [Link].*;
enum Apple
{
Jonathan,GoldenDel,RedDel,Winesap,Cortland
}
class Enum1
{
public static void main(String any[])
{
Apple ap=[Link];
[Link](ap);
Apple a[]=[Link]();
for(Apple x:a)
[Link](x);
[Link]("Enter the apple breed");
Scanner s=new Scanner([Link]);
String applebreed=[Link]();
[Link]([Link](applebreed));
}
}

Java program to demonstrate the class based approach of Enum and use of valueOf and values static
methods:
import [Link].*;
enum Apple
{
Jonathan(200),GoldenDel(150),RedDel(180),Winesap(300),Cortland(100);
private int price;
Apple(int price){ [Link]=price;}
int getPrice(){ return price;}
}
class Enum2
{
public static void main(String any[])
{
Apple ap=[Link];
[Link](ap);
Apple a[]=[Link]();
for(Apple x:a)
[Link](x+","+[Link]());
[Link]("Enter the apple breed");
Scanner s=new Scanner([Link]);
String applebreed=[Link]();
[Link]([Link](applebreed));
119
}
}

Java program to illustrate the months in the year as Enum and finding number of days given month
name
import [Link].*;
enum Month
{
Jan(31),Feb(28),Mar(31),Apr(30),May(31),
Jun(30),Jul(31),Aug(31),Sep(30),Oct(31),Nov(30),Dec(31);
private int nod;
Month(int nod){ [Link]=nod;}
int getDays(){ return nod;}
}
class Months
{
public static void main(String any[])
{
[Link]("Enter the month name");
Scanner s=new Scanner([Link]);
String monthname=[Link]();
Month m=[Link](monthname);
[Link]([Link]());
}
}

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
[Link] package: The [Link] package provides the utility classes to deal with objects.

120
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

Primitive Types and their Wrapper classes


Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Character wrapper class methods

Hence it has a constructor to convert from primitive character to Character object. The same can also
be done through static method valueOf. One can get primitive value from Character object using
charValue method

Boolean wrapper class methods

121
It has a 2 constructors to convert from primitive boolean to Boolean object. The constructor takes
primitive Boolean and string Boolean. The same can also be done through static method valueOf.
One can get primitive value from Boolean object using booleanValue method.
Numeric wrapper class methods

Any numeric Wrapper can be converted to its primitive equivalent using typeValue() method where
type can be any primitive.

Similarly any numeric primitive can be converted to its numeric wrapper using valueOf.

Autoboxing and Unboxing:


The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing
and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer
doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding is required.

Autboxing and methods example


class ABU
{
static int m(Integer i)
{
return i;
}
public static void main(String any[])
{
Integer iob;
int i=10;
iob=i; //Autoboxing
Integer iob1=m(30); //1. Autboxing, [Link] and 3. Autoboxing
[Link](i+iob);
[Link](iob1);
122
}
}

Autoboxing/Unboxing Occurs in Expressions


In general, autoboxing and unboxing take place whenever a conversion into an object or from an object
is required. This applies to expressions. Within an expression, a numeric object is automatically
unboxed. The outcome of the expression is reboxed, if necessary. For example, consider the following
program:

Autoboxing/unboxing Boolean and character values


public class MainClass {
public static void main(String args[]) {
Boolean booleanObject = true;

if (booleanObject){ //Autounboxing of Boolean value


[Link]("b is true");
}

123
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char

[Link]("ch2 is " + ch2);


}
}

LabComponent:
11. Write a program to illustrate creation of threads using runnable class. (start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).

class Thread1 implements Runnable


{
String name;
Thread t;
Thread1(String name)
{
t=new Thread(this,name);
}
public void run()
{
[Link]([Link]()+" started");
try{[Link](500);}
catch(InterruptedException e){ };
[Link]([Link]()+" ended");
}
}

public class MyClass {


public static void main(String args[]) throws InterruptedException{
Thread1 t1=new Thread1("first");
[Link]();
[Link]("Main started..");
[Link]();
[Link]("Main ended..");
}
}

12. Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It can be
observed that both main thread and created child thread are executed concurrently

public class Thread2 extends Thread


{
124
String name;
Thread2(String name)
{
super(name);
}
public void run()
{
[Link](getName()+" started");
try{[Link](500);}
catch(InterruptedException e){ };
[Link](getName()+" ended");
}
public static void main(String args[]) throws InterruptedException{
Thread2 t1=new Thread2("first");
[Link]();
[Link]("Main started..");
[Link]();
[Link]("Main ended..");
}
}

125
CONTENT BEYOND SYLLABUS-HackerRank program solving
1. Java Output Formatting

Input Format
Every line of input will contain a String followed by an integer.
Each String will have a maximum of 10 alphabetic characters, and each integer will be in the
inclusive range from to 0 to 999.
Output Format
In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less
than three digits, you must pad your output's leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50
Sample Output
================================
java 100
cpp 065
python 050

Program:
import [Link];

public class Solution {


public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("================================");
for(int i=0;i<3;i++){
String s1=[Link]();
[Link](s1);
for(int j=0;j<[Link]();j++)
[Link](" ");
int x=[Link]();
if(x<10)
{
[Link]("00"+x);
}
else if(x<100)
{
[Link]("0"+x);
}
else
[Link](x);
126
//Complete this line
}
[Link]("================================");
}
}

2. Java Loops

Input Format
The first line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains three space-separated integers describing the
respective ai,bi and ni values for that query.
Output Format
For each query, print the corresponding series on a new line. Each series must be printed in order
as a single line of n space-separated integers.
Sample Input
2
0 2 10
535
Sample Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98

Program:
import [Link].*;
import [Link].*;

class Solution{
public static void main(String []argh){
Scanner in = new Scanner([Link]);
int t=[Link]();
for(int i=0;i<t;i++){
int a = [Link]();
int b = [Link]();
int n = [Link]();

127
int s=a+b;
[Link](s+" ");
for(int j=1;j<n;j++)
{
s+=b*[Link](2,j);
[Link](s+" ");
}
[Link]();
}
[Link]();
}
}

Java Static Initializer Block


You are given a class Solution with a main method. Complete the given code so that it outputs the
area of a parallelogram with breadth B and height H . You should read the variables from the
standard input.
If B<=0 or H<=0 , the output should be "[Link]: Breadth and height must be
positive" without quotes.
Input Format
There are two lines of input. The first line contains B : the breadth of the parallelogram. The next
line contains H: the height of the parallelogram.
Output Format
If both values are greater than zero, then the main method must output the area of
the parallelogram. Otherwise, print "[Link]: Breadth and height must be
positive" without quotes.

Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class Solution {


static int B,H;
static boolean flag;
static{
Scanner s=new Scanner([Link]);
B=[Link]();
H=[Link]();
try{
if(B<=0 || H<=0)
{
flag=false;
throw new Exception("Breadth and height must be positive");
}
128
else
flag=true;
}
catch(Exception e)
{
[Link](e);
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
[Link](area);
}

}//end of main

}//end of class

Java Subarray
Given an array of integers, find and print its number of negative subarrays on a new line.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class Solution {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should
be named Solution. */
Scanner s=new Scanner([Link]);
int N =[Link]();
int cnt=0;
int a[]=new int[N];
for(int i=0;i<N;i++)
a[i]=[Link]();
for(int i=0;i<N;i++)
{
int sum=0;
for(int j=i;j<N;j++)
{
sum+=a[j];
if(sum<0)
cnt++;
}
}
129
[Link](cnt);

}
}

Java Inheritance
Write the following code in your editor below:
1. A class named Arithmetic with a method named add that takes 2 integers as parameters
and returns an integer denoting their sum.
2. A class named Adder that inherits from a superclass named Arithmetic.
Your classes should not be be public
Program:
class Arithmetic
{
int add(int a,int b)
{
return a+b;
}
}
class Adder extends Arithmetic
{

}
public class Solution{
public static void main(String []args){
// Create a new Adder object
Adder a = new Adder();

// Print the name of the superclass on a new line


[Link]("My superclass is: " + [Link]().getSuperclass().getName());

// Print the result of 3 calls to Adder's `add(int,int)` method as 3 space-separated integers:


[Link]([Link](10,32) + " " + [Link](10,3) + " " + [Link](10,10) + "\n");
}
}

Java Interfaces
You are given an interface AdvancedArithmetic which contains a method signature int
divisor_sum(int n). You need to write a class called MyCalculator which implements the interface.
divisorSum function just takes an integer as input and return the sum of all its divisors. For example
divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will be at most 1000.
Read the partially completed code in the editor and complete it. You just need to write the
MyCalculator class only. Your class shouldn't be public.
Program
import [Link].*;
interface AdvancedArithmetic{

130
int divisor_sum(int n);
}

//Write your code here


class MyCalculator implements AdvancedArithmetic
{
public int divisor_sum(int n)
{
int sum=0;
for(int i=1;i<=n;i++)
{
if(n%i==0) sum+=i;
}
return sum;
}
}

class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
[Link]("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link](my_calculator.divisor_sum(n) + "\n");
[Link]();
}
/*
* ImplementedInterfaceNames method takes an object and prints the name of the interfaces it
implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = [Link]().getInterfaces();
for (int i = 0; i < [Link]; i++){
String interfaceName = theInterfaces[i].getName();
[Link](interfaceName);
}
}
}

Java Exception Handling


You will be given two integers x and y as input, you have to compute x/y. If x and y are not bit
signed integers or if y is zero, exception will occur and you have to report it. Read sample
Input/Output to know what to report in case of exceptions.
import [Link].*;
import [Link].*;
import [Link].*;
131
import [Link].*;
import [Link].*;

public class Solution {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should
be named Solution. */
Scanner s=new Scanner([Link]);
try{
int x=[Link]();
int y=[Link]();
int z=x/y;
[Link](z);
}
catch(InputMismatchException i)
{
[Link]("[Link]");
}
catch(ArithmeticException e)
{
[Link]("[Link]: / by zero");
}

}
}

132

You might also like