Java Unit IV
Java Unit IV
Unit – IV
PACKAGES
JAVA API PACKAGES – USING SYSTEM PACKAGES – NAMING CONVENTIONS – CREATING
PACKAGES – ACCESSING A PACKAGE – USING A PACKAGE – ADDING A CLASS TO A PACKAGE –
HIDING CLASSES.
MULTITHREADED PROGRAMMING
CREATING THREADS – EXTENDING THE THREAD CLASS – STOPPING AND BLOCKING A
THREAD – LIFE CYCLE OF A THREAD – USING THREAD METHODS – THREAD EXCEPTIONS –
THREAD PRIORITY – SYNCHRONIZATION – IMPLEMENTING THE ‘RUNNABLE’ INTERFACE
MANAGING ERRORS AND EXCEPTIONS
TYPES OF ERRORS – EXCEPTIONS – SYNTAX OF EXCEPTION HANDLING CODE – MULTIPLE
CATCH STATEMENTS – USING FINALLY STATEMENT – THROWING OUR OWN EXCEPTIONS –
USING EXCEPTIONS FOR DEBUGGING.
PACKAGES
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
3. How to run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
To Compile: javac -d . [Link]
To Run: java [Link]
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
4. How to access package from another package?
There are three ways to access the package from outside the package.
import package.*;
import [Link];
fully qualified name.
1) Using packagename.*
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 [Link] import pack.*;
package pack; class B{
public class A{ public static void main(String args[]){
public void msg(){[Link]("Hello");} A obj = new A();
} [Link]();
//save by [Link] } }
package mypack; Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Example of package by import [Link]
//save by [Link] import pack.A;
package pack; class B{
public class A{ public static void main(String args[]){
public void msg(){[Link]("Hello");} A obj = new A();
} [Link]();
//save by [Link] } }
package mypack; Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
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. [Link] and [Link] packages
contain Date class.
Example of package by import fully qualified name
//save by [Link] class B{
package pack; public static void main(String args[]){
public class A{ pack.A obj = new pack.A();//using fully qualifie
public void msg(){[Link]("Hello");} d name
[Link]();
} }
//save by [Link] }
package mypack; Output:Hello
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
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.
// Name of the package must be same as the directory, under which this file is saved
package myPackage; {
public class MyClass [Link](s);
{ }
public void getNames(String s) }
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names'
myPackage */ // with a value
import [Link]; String name = "GeeksforGeeks";
public class PrintName // Creating an instance of class MyClass in
{ // the package.
public static void main(String args[]) MyClass obj = new MyClass();
{ [Link](name);
// Initializing the String variable }
}
Note : [Link] must be saved inside the myPackage directory since it is a part of the package.
************************************************************************************
JAVA API PACKAGES
API Packages
Java APl(Application Program Interface) provides a large numbers of classes grouped into different
packages according to functionality.
Most of the time we use the packages available with the the Java API.
Following figure shows the system packages that are frequently used in the programs.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
[Link] Language utility classes such as vectors, hash tables, random numbers, data, etc.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
***********************************************************************************************
NAMING CONVENTIONS
Java naming convention is a rule to follow as you decide what to name your identifiers such as class,
package, variable, constant, method, etc.
But, it is not forced to follow. So, it is known as convention not rule.
These conventions are suggested by several Java communities such as Sun Microsystems and
Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are given
according to the Java naming convention.
If you fail to follow these conventions, it may generate confusion or erroneous code
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and other
programmers.
Readability of Java program is very important.
It indicates that less time is spent to figure out what the code does.
The following are the key rules that must be followed by every identifier:
The name must not contain any white spaces.
The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
Other rules that should be followed by identifiers.
1. Class
It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms.
Example: -
public class Employee
{
//code snippet
}
2. Interface
It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Use appropriate words, instead of acronyms.
Example: -
interface Printable
{
//code snippet
}
3. Method
It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter
such as actionPerformed().
Example:-
class Employee {
{ //code snippet
//method }
void draw() }
4. Variable
It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter
such as firstName, lastName.
Avoid using one-character variables such as x, y, z.
Example :- int id;
class Employee //code snippet
{ }
//variable
5. Package
It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as [Link], [Link].
Example :- {
package [Link]; //package //code snippet
class Employee }
6. Constant
It should be in uppercase letters such as RED, YELLOW.
If the name contains multiple words, it should be separated by an underscore(_) such as
MAX_PRIORITY.
It may contain digits but not as the first letter.
Example :- static final int MIN_AGE = 18;
class Employee //code snippet
{ }
//constant
CamelCase in java naming conventions
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Java follows camel-case syntax for naming the class, interface, method, and variable.
If the name is combined with two words, the second word will start with uppercase letter always such
as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
***************************************************************************************
CREATING PACKAGES
The package keyword is used to create a package in java.
//save as [Link] [Link]("Welcome to package");
package mypack; }
public class Simple{ }
public static void main(String args[]){
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
To Compile: javac -d . [Link]
To Run: java [Link]
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
***********************************************************************************************
ACCESSING A PACKAGE
How to access package from another package?
There are three ways to access the package from outside the package.
o import package.*;
o import [Link];
1) Using packagename.*
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 [Link] import pack.*;
package pack; class B{
public class A{ public static void main(String args[]){
public void msg(){[Link]("Hello");} } A obj = new A();
//save by [Link] [Link](); } }
package mypack; Output:Hello
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Example of package by import [Link]
//save by [Link] class B{
package pack; public static void main(String args[]){
public class A{ A obj = new A();
public void msg(){[Link]("Hello");} [Link]();
} }
//save by [Link] }
package mypack; Output:Hello
import pack.A;
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. [Link] and [Link] packages
contain Date class.
Example of package by import fully qualified name
//save by [Link] public static void main(String args[]){
package pack; pack.A obj = new pack.A();//using fully qualified
public class A{ name
public void msg(){[Link]("Hello");} [Link]();
} }
//save by [Link] }
package mypack; Output:Hello
class B{
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage.
It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named
java that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on.
So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
The standard of defining package is [Link] e.g. [Link] or
[Link].
Example of Subpackage
package [Link]; }
class Simple{ To Compile: javac -d . [Link]
public static void main(String args[]){ To Run: java [Link]
[Link]("Hello subpackage"); Output:Hello subpackage
}
***********************************************************************************************
USING A PACKAGE
Java has import statement that allows you to import an entire package (as in earlier examples), or use
only certain classes and interfaces defined in the package.
The general form of import statement is:
import [Link]; // To import a certain class only
import [Link].* // To import the whole package
For example,
import [Link]; // imports only Date class
import [Link].*; // imports everything inside [Link] package
The import statement is optional in Java.
If you want to use class/interface from a certain package, you can also use its fully qualified name,
which includes its full package hierarchy.
Here is an example to import package using import statement.
import [Link];
class MyClass implements Date
{
// body
}
The same task can be done using fully qualified name as follows:
class MyClass implements [Link]
{
//body
}
Example: Package and importing package
Suppose, you have defined a package [Link] that contains a class Helper.
package [Link]; return [Link]("$%.2f", value);
public class Helper { }
public static String getFormattedDollar (double }
value){
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
In Java, import statement is written directly after the package statement (if it exists) and before the
class definition.
For example,
package [Link]; {
import [Link]; // only import a Class // body
class MyClass }
***************************************************************************************
ADDING A CLASS TO A PACKAGE
The packages are used for categorization of the same type of classes and interface in a single unit.
There is no core or in-built classes that belong to unnamed default package.
To use any classes or interface in other class, we need to use it with their fully qualified type name.
Java supports imports statement to bring entire package, or certain classes into visibility.
It provides flexibility to the programmer to save a lot of time just by importing the classes in his/her
program, instead of rewriting them.
In a Java source file, import statements occur immediately following the package statement (if it
exists) and must be before of any class definitions.
This is the general form is as follows:
import pkg1 (.pkg2). [classname|*l;
For example
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
The star (*) increases the compilation time, if the package size is very large.
A good programming methodology says that give the fully qualified type name explicitly, i.e. import
only those classes or interface that you want to use instead of importing whole packages.
Yet the start will not increase the overhead on run-time performance of code or size of classes.
Example:
//[Link] private String name;
package student; private String address;
class Student public Student(int rno, String sname, String sadd}
{ {
private int rollno; rollno = rno;
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
name = sname; {
address = sadd; private int totalMarks;
} private float percentage;
public void show() private char grade;
{ public Result(int rno, String sname, String sadd,int
[Link]("Roll No :: " + rollno); mi, int m2, int m3, int m4)
[Link]("Name :: " + name); {
[Link]("Address :: " + address); super(rno,sname,sadd,ml,m2,m3,m4);
} totalMarks = marksSubject1 + marksSubject2 +
} marksSubject3 + marksSubject4;
// [Link] percentage = (totalMarks*100.00F/600.00F);
package student; if (percentage >=50.00F)
class Test extends Student grade='D';
{ else
protected int marksSubjecti; if(percentage >=55.00F && percentage<=60.00F)
protected int marksSubject2; grade = 'C';
protected int marksSubject3; else
protected int marksSubject4; if (percentage >=6l.00F && percentage<=70.00F)
public Test(int rno, String sname, String sadd,int grade = 'B';
mi, int m2, int m3, int m4) else
{ if(percentage >=7l.00F && percentage<=75.00F)
super(rno,sname,sadd); grade = 'A';
marksSubjecti = mi; else
marksSubject2 = m2; if (percentage >=76.00F && percentage<=85.00F)
marksSubject3 = m3; grade = 'H';
marksSubject4 = m4; else
} grade = 'S';
public void show() }
{ public void show()
[Link](); {
[Link]("Marks of Subject1 :: " + [Link]();
marksSubject1); [Link]("Total Marks :: " +
[Link]("Marks of Subject2 :: " + totalMarks);
marksSubject2); [Link]("Percentage :: " + percentage);
[Link]("Marks of Subject3 :: " + [Link]("Grade :: " + grade);
marksSubject3); }
[Link]("Marks of Subject4 :: " + }
marksSubject4); //[Link]
} import [Link];
} public class ImportPackageDemo
//[Link] {
package student; public static void main(String ar[])
public class Result ex..tends Test {
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Result ob = new Result (1001, "Alice", "New }
York",135,130,132,138); }
[Link] ();
In the source file ImportPackageDemo, import student. Result is the first statement; it will import the
class Result from the student package.
***********************************************************************************************
HIDING CLASSES
When we import a package within a program, only the classes declared as public in that package will
be made accessible within this program.
In other words, the classes not declared as public in that package will not be accessible within this
program.
Sometimes, we may wish that certain classes in a package should not be made accessible to the
importing program.
In such cases, we need not declare those classes as public.
When we do so, those classes will be hidden from being accessed by the importing class.
Here is an example :
Here, the class DataClass which is not declared public is hidden from outside of the package mypack.
This class can be seen and used only by other classes in the same package.
Note that a Java source file should contain only one public class and may include any number of non-
public classes.
Program
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Java compiler would generate an error message for the code DataClass da = new
DataClass(); because the class DataClass, which has not been declared public, is not imported and
therefore not available for creating its objects.
***************************************************************************************
MULTITHREADED PROGRAMMING
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU.
Multitasking can be achieved in two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a separate memory
area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Any application can have multiple processes (instances).
Each of this process can be assigned either as a single thread or multiple threads.
What is Single Thread?
A single thread is basically a lightweight and the smallest unit of processing.
Java uses threads by using a "Thread Class".
There are two types of thread – user thread and daemon thread (daemon threads are used when we
want to clean the application and are used in the background).
When an application first begins, user thread is created. Post that, we can create many user threads
and daemon threads.
Single Thread Example:
package demotest;
public class GuruThread
{
public static void main(String[] args) {
[Link]("Single Thread");
}
}
Advantages of single thread:
Reduces overhead in the application as single thread execute in the system
Also, it reduces the maintenance cost of the application.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
What is Multithreading?
Multithreading in java is a process of executing two or more threads simultaneously to maximum
utilization of CPU.
Multithreaded applications are where two or more threads run concurrently; hence it is also known
as Concurrency in Java.
This multitasking is done, when multiple processes share common resources like CPU, memory, etc.
Each thread runs parallel to each other. Threads don't allocate separate memory area; hence it saves
memory. Also, context switching between threads takes less time.
Example of Multi thread:
package demotest; [Link]("Thread names are
public class GuruThread1 implements Runnable following:");
{ [Link]([Link]());
public static void main(String[] args) { [Link]([Link]());
Thread guruThread1 = new Thread("Guru1"); }
Thread guruThread2 = new Thread("Guru2"); @Override
[Link](); public void run() {
[Link](); }}
Advantages of multithread:
The users are not blocked because threads are independent, and we can perform multiple operations at
times
As such the threads are independent, the other threads won't get affected if one thread meets an
exception.
***************************************************************************************
CREATING THREADS
How to create thread
There are two ways to create a thread:
o By extending Thread class
o By implementing Runnable interface.
I. Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the [Link] calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public [Link] getState(): returns the state of the thread.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public void interrupt(): interrupts the thread.
II. Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread.
Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{ Multi t1=new Multi();
public void run(){ [Link]();
[Link]("thread is running..."); }
} }
public static void main(String args[]){ Output: thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{ Thread t1 =new Thread(m1);
public void run(){ [Link]();
[Link]("thread is running..."); }
} }
public static void main(String args[]){ Output: thread is running...
Multi3 m1=new Multi3();
If you are not extending the Thread class,your class object would not be treated as a thread object.
So you need to explicitely create Thread class object.
We are passing the object of your class that implements Runnable so that your class run() method
may execute.
***********************************************************************************************
EXTENDING THE THREAD CLASS
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Each part of such program is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the [Link] class.
This class overrides the run() method available in the Thread class.
A thread begins its life inside run() method.
We create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.
// Java code for thread creation by extending the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try
{ // Displaying the thread that is running
[Link] ("Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{
[Link] ("Exception is caught"); // Throwing an exception
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
[Link]();
}
}
}
Output :
Thread 8 is running Thread 12 is running
Thread 9 is running Thread 13 is running
Thread 10 is running Thread 14 is running
Thread 11 is running Thread 15 is running
***************************************************************************************
IMPLEMENTING THE ‘RUNNABLE’ INTERFACE
We create a new class which implements [Link] interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
// Java code for thread creation by implementing the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{ // Displaying the thread that is running
[Link] ("Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{ // Throwing an exception
[Link] ("Exception is caught");
}
}
}
// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
[Link]();
}
}
}
Output :
Thread 8 is running Thread 12 is running
Thread 9 is running Thread 13 is running
Thread 10 is running Thread 14 is running
Thread 11 is running Thread 15 is running
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn‟t support
multiple inheritance.
2. But, if we implement the Runnable interface, our class can still extend other base classes.
3. We can achieve basic functionality of a thread by extending Thread class because it provides some
inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
***************************************************************************************
STOPPING AND BLOCKING A THREAD
Starting a thread:
When we create a thread by taking instance of a thread class, the thread will be in its new-bornstate.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
To move it to runnable state, we use a method named start( ).
When we invoke this method with a thread, java run-time schedules it to run by invoking it run()
method.
Now the thread will be in its running state. To start a thread we use the following syntax:
MyThread t1 = new MyThread();
[Link]();
Stopping a thread:
Whenever we want to stop a thread from running further, we may do so by calling its stop() method.
This causes a thread to stop immediately and move it to its dead state.
It forces the thread to stop abruptly before its completion i.e. it causes premature death.
To stop a thread we use the following syntax:
[Link]();
Blocking a Thread:
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods:
sleep(t) // blocked for „t‟ milliseconds
suspend() // blocked until resume() method is invoked
wait() // blocked until notify () is invoked
These methods cause the thread to go into the blocked (or not-runnable) state.
The thread will return to the runnable state when the specified time is elapsed in the case of sleep( ),
the resume() method is invoked in the case of suspend( ), and the notify( ) method is called in the case
of wait().
***************************************************************************************
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:
o New o Non-Runnable (Blocked)
o Runnable o Terminated
o Running
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
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.
Running
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method exits.
***************************************************************************************
USING THREAD METHODS
Java Thread Methods
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread
object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause
and allow other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its
subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static boolean interrupted() It tests whether the current thread has been interrupted.
22) static int activeCount() It returns the number of active threads in the current
thread's thread group.
23) void checkAccess() It determines if the currently running thread has
permission to modify the thread.
24) static boolean holdLock() It returns true if and only if the current thread holds the
monitor lock on the specified object.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
25) static void dumpStack() It is used to print a stack trace of the current thread to the
standard error stream.
26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements representing
the stack dump of the thread.
27) static int enumerate() It is used to copy every active thread's thread group and
its subgroup into the specified array.
28) [Link] getState() It is used to return the state of the thread.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread
belongs
30) String toString() It is used to return a string representation of this thread,
including the thread's name, priority, and thread group.
31) void notify() It is used to give the notification for only one thread
which is waiting for a particular object.
32) void notifyAll() It is used to give the notification to all waiting threads of
a particular object.
***************************************************************************************
THREAD EXCEPTIONS
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.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
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 use exception
handling. Let's take a scenario:
statement 1; statement 6;
statement 2; statement 7;
statement 3; statement 8;
statement 4; statement 9;
statement 5;//exception occurs statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the
rest of the code will not be executed i.e. statement 6 to 10 will not be executed.
If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error.
A hierarchy of Java Exception classes are given below:
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
try The "try" keyword is used to specify a block where we should place exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.
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 important 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 doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
***************************************************************************************
THREAD PRIORITY
Each thread has a priority.
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.
3 constants defined in Thread class:
o public static int MIN_PRIORITY
o public static int NORM_PRIORITY
o 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.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority()); }
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link](); [Link](); } }
Output:
running thread name is:Thread-0 running thread name is:Thread-1
running thread priority is:10 running thread priority is:1
***********************************************************************************************
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
SYNCHRONIZATION
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
o To prevent thread interference.
o To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1) Process Synchronization
2) Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive
o Synchronized method.
o Synchronized block.
o static synchronization.
Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
o by synchronized method
o by synchronized block
o by static synchronization
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can
use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Syntax to use synchronized block
synchronized (object reference expression)
{
//code block
}
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
***************************************************************************************
TYPES OF ERRORS
Three types of errors
There are basically three types of errors that you must contend with when writing computer
programs:
1. Syntax errors 2. Runtime errors 3. Logic errors
1. Syntax errors
In effect, syntax errors represent grammar errors in the use of the programming language. Common
examples are:
o Misspelled variable and function names
o Missing semicolons
o Improperly matches parentheses, square brackets, and curly braces
o Incorrect format in selection and loop statements
2. Runtime errors
Runtime errors occur when a program with no syntax errors asks the computer to do something that
the computer is unable to reliably do. Common examples are:
o Trying to divide by a variable that contains a value of zero
o Trying to open a file that doesn't exist
o There is no way for the compiler to know about these kinds of errors when the program is
compiled.
3. Logic errors
Logic errors occur when there is a design flaw in your program. Common examples are:
o Multiplying when you should be dividing
o Adding when you should be subtracting
o Opening and using data from the wrong file
o Displaying the wrong message
***************************************************************************************
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
EXCEPTIONS
Exceptions are events that occur during the execution of programs that disrupt the normal flow of
instructions (e.g. divide by zero, array access out of bound, etc.).
In Java, an exception is an object that wraps an error event that occurred within a method and
contains:
Information about the error including its type
The state of the program when the error occurred
Optionally, other custom information
Exception objects can be thrown and caught.
Exceptions are used to indicate many different types of error conditions.
JVM Errors:
o OutOfMemoryError o SocketTimeoutException
o StackOverflowError o Programming errors:
o LinkageError o NullPointerException
o System errors: o ArrayIndexOutOfBoundsException
o FileNotFoundException o ArithmeticException
o IOException
1. Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
ArithmeticException - It is thrown when an exceptional condition has occurred in an arithmetic
operation.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
ArrayIndexOutOfBoundsException - It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException - This Exception is raised when we try to access a class whose definition
is not found
FileNotFoundException - This Exception is raised when a file is not accessible or does not open.
IOException - It is thrown when an input-output operation failed or interrupted
InterruptedException - It is thrown when a thread is waiting , sleeping , or doing some processing ,
and it is interrupted.
NoSuchFieldException - It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException - It is thrown when accessing a method which is not found.
NullPointerException - This exception is raised when referring to the members of a null object. Null
represents nothing
NumberFormatException - This exception is raised when a method could not convert a string into a
numeric format.
RuntimeException - This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException - It is thrown by String class methods to indicate that an index
is either negative than the size of the string
2. User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases,
user can also create exceptions which are called „user-defined Exceptions‟.
Following steps are followed for the creation of user-defined Exception.
The user should create an exception class as a subclass of Exception class.
Since all the exceptions are subclasses of Exception class, the user should also make his class a
subclass of it. This is done as:
o class MyException extends Exception
We can write a default constructor in his own exception class.
o MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call super class(Exception) constructor from this
and send the string there.
MyException(String str)
{
super(str);
}
To raise exception of user-defined type, we need to create an object to his exception class and throw
it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
The following program illustrates how to create own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the form of three
arrays.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
In main() method, the details are displayed using a for-loop. At this time, check is done if in any
account the balance amount is less than the minimum balance amount to be ept in the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
***************************************************************************************
SYNTAX OF EXCEPTION HANDLING CODE
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the programmer, errors
due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical term for
this is: Java will throw an exception (throw an error).
Java try and catch
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class MyClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]); // error!
}
}
The output
Exception in thread "main" [Link]: 10
at [Link]([Link])
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example
public class MyClass { int[] myNumbers = {1, 2, 3};
public static void main(String[ ] args) { [Link](myNumbers[10]);
try { } catch (Exception e) {
[Link]("Something went wrong."); } } }
The output will be:
Something went wrong.
***************************************************************************************
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
MULTIPLE CATCH STATEMENTS
The example we seen above is having multiple catch blocks, lets see few rules about multiple catch
blocks with the help of examples.
1. A single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions.
Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or
any other type of exception, this handles all of them.
Exception Handling example programs.
catch(Exception e)
{
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle all.
This is because in generic exception handler you can display a message but you are not sure for
which type of exception it may trigger so it will display the same message for all the exceptions and
user may not be able to understand which exception occurred.
Thats the reason you should place is at the end of all the specific exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception,: user defined exception, throws keyword, throw vs throws.
Example of Multiple catch blocks
class Example2{
public static void main(String args[]){ [Link]("Warning: ArrayIndexOutOfB
try{ oundsException");
int a[]=new int[7]; }
a[4]=30/0; catch(Exception e){
[Link]("First print statement in [Link]("Warning: Some Other
try block"); exception");
} }
catch(ArithmeticException e){ [Link]("Out of try-catch
[Link]("Warning: block...");
ArithmeticException"); }
} }
catch(ArrayIndexOutOfBoundsException e){ Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block.
Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block
then in case of any exception this block will execute as it can handle all exceptions.
This catch block should be placed at the last to avoid such situations.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
***************************************************************************************
USING FINALLY STATEMENT
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}
The output
Something went wrong.
The 'try catch' is finished.
***************************************************************************************
THROWING OUR OWN EXCEPTIONS
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type.
There are many exception types available in Java:
o ArithmeticException,
o ClassNotFoundException,
o ArrayIndexOutOfBoundsException,
o SecurityException, etc.
The exception type is often used together with a custom method.
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access
granted":
public class MyClass {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
[Link]("Access granted - You are old enough!"); }}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...) } }
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
The output
Exception in thread "main" [Link]: Access denied - You must be at least 18 years
old.
at [Link]([Link])
at [Link]([Link])
If age was 20, you would not get an exception:
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
***************************************************************************************
USING EXCEPTIONS FOR DEBUGGING.
Setting Breakpoints
A breakpoint is a marker that you can set to specify where execution should pause when you are
running your application in the IDE's debugger.
Breakpoints are stored in the IDE (not in your application's code) and persist between debugging
sessions and IDE sessions.
When execution pauses on a breakpoint, the line where execution has paused is highlighted in green
in the Source Editor, and a message is printed in the Debugger Console with information on the
breakpoint that has been reached.
In their simplest form, breakpoints provide a way for you to pause the running program at a specific
point so that you can
Monitor the values of variables at that point in the program's execution.
Take control of program execution by stepping through code line by line or method by method.
However, you can also use breakpoints as a diagnostic tool to do things such as:
Detect when the value of a field or local variable is changed (which, for example, could help you
determine what part of code assigned an inappropriate value to a field).
Detect when an object is created (which might, for example, be useful when trying to track down a
memory leak).
You can set multiple breakpoints, and you can set different types of breakpoints.
The simplest kind of breakpoint is a line breakpoint, where execution of the program stops at a
specific line.
You can also set breakpoints on other situations, such as the calling of a method, the throwing of an
exception, or the changing of a variable's value.
In addition, you can set conditions in some types of breakpoints so that they suspend execution of the
program only under specific circumstances.
Breakpoint Categories
Breakpoint Description
Type
Line Set on a line of code. When the debugger reaches that line, it stops before executing the line.
The breakpoint is marked by pink background high-lighting and the icon. You can also
specify conditions for line breakpoints.
[Link] MCA.,[Link].,
Java Programming – 7BIT3C1
Class Execution is suspended when the class is referenced from another class and before any lines
of the class with the breakpoint are executed.
Exception Execution is suspended when an exception occurs. You can specify whether execution stops
on caught exceptions, uncaught exceptions, or both.
Method Execution is suspended when the method is called.
Variable Execution is suspended when the variable is accessed. You can also configure the breakpoint
to have execution suspended only when the variable is modified.
Thread Execution is suspended whenever a thread is started or terminated. You can also set the
breakpoint on the thread's death (or both the start and death of the thread).
***********************************************************************************************
[Link] MCA.,[Link].,