0% found this document useful (0 votes)
21 views

Unit Ii

JAVA

Uploaded by

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

Unit Ii

JAVA

Uploaded by

Meera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

UNIT II

UNIT 2 PACKAGES AND INTERFACES

Using Packages – Importing packages – Access protection – Interfaces – Exception Handling


& I/O Streams – Exception Types – Using try, catch, throw, throws and finally – Byte and
Character Streams – Multithreading – Java Thread Model – Main thread – Creating multiple
thread – Thread priorities – Synchronization

***************************************************************************
Packages
***************************************************************************
Definition
 A package is a group of related classes and interfaces. The grouping is usually done
according to functionality. In fact, packages act as “containers” for classes.
 Java classes can be grouped together in packages. A package name is the same as the
directory (folder) name which contains the .java files.
Benefits of using packages
 The classes contained in the packages of another program can be easily reused.
 Packages also allow programmers to separate design from coding.
 In packages, classes can be declared uniquely compared with classes in other packages.
 Java Packages provide a way to ‘hide’ classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
 Packages provide access protection.
 Java package removes naming collision.
Different types of Packages
 Java packages are classified into two types. They are:
1. Java API Packages
2. User Defined Packages
Java API Packages

 Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time we use the packages available with the Java API as shown
in Figure 10.1.
Figure 10.1: Frequently used API packages

 Table 10.1 shows the classes that belong to each package.

Package Name Contents


java.lang Language support classes. These are classes that Java compiler itself uses
and therefore they are automatically imported. They include classes
for primitive types, strings, math functions, threads and exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers,
date, etc.
java.io Input / output support classes. They provide facilities for the input and
output
of data.
java.awt Set of classes for implementing graphical user interface. They include
classes for
windows, buttons, lists, menus, and so on.
java.net Classes for networking. They include classes for communicating with local
computers as well as with Internet servers.
java.applet Classes for creating and implementing applets

Table 10.1: Java System Packages and Their Classes


User Defined Packages
 Programmers can define their own packages to bundle group of classes/interfaces etc.
 It is a good practice to group related classes implemented by us so that a programmers can
easily determine that the classes, interfaces, enumerations, annotations are related.
9.4 Naming Conventions
 Packages can be named using the standard Java naming rules.
 By convention, however, packages begin with lowercase letters. This makes it easy for
users to distinguish package names from class names when looking at an explicit reference
to a class.
 We know that all class names, again by convention, begin with an uppercase letter. For
example,
 This statement uses a fully qualified class name Math to invoke the method sqrt().
 The package names must be unique. Duplicate names will cause run-time errors.

 Naming a package is therefore a very important aspect of creating a package. Since


multiple users work on Internet, duplicate package names are unavoidable.
 Java designers have recognized this problem and therefore suggested a package naming
convention that ensures uniqueness.
 This suggests the use of domain names as prefix to the preferred package names. For
example:
cbe.psg.mypackage
Here, cbe denotes city name and psg denotes the organization name.
9.5 Creating Packages
 The package statement is used to create a new package.
 The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
 The general form of the package statement is:
package packagename;
where packagename is the name of the package.
Example:
package MyPackage; // package declaration
public class FirstClass // class definition
{
………………
……………… (body of class)
………………
}

 Creating our own package involves the following steps:


1. Declare the package at the beginning of the file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
 Java also supports the concept of package hierarchy. This is done by specifying multiple
names in a package statement, separated by dots.
Example:
package firstPackage.secondPackage;
This approach allows us to group related classes into a package and then group related
packages into a larger package.
 A Java package file can have more than one class definitions. In such cases, only one of
the classes may be declared public and that classname with .java extension is the source
file name.
Set CLASSPATH System Variable
 To display the current CLASSPATH variable, use the following commands in Windows
and Unix (Bourne shell):
 In Windows -> C:\> set CLASSPATH
 In Unix -> % echo $CLASSPATH
 To delete the current contents of the CLASSPATH variable, use:
 In Windows -> C:\> set CLASSPATH=
 In Unix -> % unset CLASSPATH; export CLASSPATH
 To set the CLASSPATH variable:
 In Windows -> set CLASSPATH=C:\users\jack\java\classes
 In Unix -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH
Example:
// Java Program to create a simple package
// Palindrome.java
package mypackage;
public class Palindrome
{
public String test(String str)
{
char givenstring[];
char reverse[] = new char[str.length()];
boolean flag = true;
int i = 0, j = 0,l;
givenstring = str.toCharArray();
l=str.length();
for(i=l-1;i>=0;i--)
{
reverse[j] = givenstring[i];
j++;
}
for(i=0;i<l;i++)
{
if(reverse[i]!= givenstring[i])
flag = false;
}
if (flag==false)
return "Not Palindrome";
else
return "Palindrome";
}
}
--------------------------------------------------------------------------------------------------------------
// Java program using packages to check whether the given string is Palindrome or not
// Program to use the package created
// Palintest.java
import mypackage.*;
import java.util.*;
import java.io.*;

class Palintest
{
public static void main(String args[]) throws IOException
{
Palindrome P=new Palindrome();
Scanner in=new Scanner(System.in);
String message;
System.out.println("\tJava Program using Package");
System.out.println("\t***********************");
System.out.println("Input");
System.out.println("-------");
System.out.println("Enter the String");
String str= in.nextLine();
message=P.test(str);
System.out.println("Output");
System.out.println("---------");
System.out.println("The given string is "+message);
}
}
C:\>md mypackage
C:\>cd mypackage
C:\mypackage>path="c:\program files\java\jdk1.6.0_01\bin";
C:\mypackage>javac Palindrome.java
C:\mypackage>cd\
C:\>path="c:\program files\java\jdk1.6.0_01\bin";
C:\>javac Palintest.java
C:\>java Palintest

Java Program using Package


***********************
Input
-------
Enter the String
malayalam

Output
---------
The given string is Palindrome

C:\>java Palintest
Java Program using Package
***********************
Input
-------
Enter the String
welcome

Output
---------
The given string is Not Palindrome
C:\>
9.6 Access Protection
 Java provides many levels of security that provides the visibility of members (variables
and methods) within the classes, subclasses, and packages.
 There are four types of access modifiers available in java:
1) Default – No keyword required
2) Private
3) Protected
4) Public
1) Default
 When no access modifier is specified for a class, method, or data member – It is said to
be having the default access modifier by default.
 The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.
2) private
 The private access modifier is specified using the keyword private.
 The scope of private modifier is limited to the class only.
 The methods or data members declared as private are accessible only within the
class in which they are declared.
3) protected
 The protected access modifier is specified using the keyword protected.
 The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
4) public
 The public access modifier is specified using the keyword public.
 The members, methods and classes that are declared public can
be accessed from anywhere.
 There is no restriction on the scope of public data members.
9.7 Accessing a Package
The import statement
 The import statement is used to access the package.
 The general form of import statement for searching a class is:
import package1 [.package2] [.package3].classname;

Here, package1 is the name of the top-level package. package2 is the name of the
package that is inside the 1st package i.e. package1 and so on. Programmers can use any
number of packages in the package hierarchy. At the end, the explicitly classname is
specified.
 The import statement should appear before any class definitions in a source file.
Multiple import statements are allowed. The following is an example of importing a
particular class:
import firstPackage.secondPackage.MyClass;
 After defining this statement, all members of the class MyClass can be directly accesses
using the class name or its objects directly without using the package name.
 We can also use another approach as follows:
import packagename.*;
Here, packagename may denote a single package or hierarchy of packages. The star (*)
indicates that the compiler should search this entire package hierarchy where it
encounters a class name. this implies that we can access all classes contained in the
above package directly.

**************************************************************************
Interfaces
***************************************************************************
****
10.1 Introduction
 An interface is similar to a class, but it contains abstract methods and static final
variables only.
 To access the interface methods, the interface must be "implemented" by another class
with the implements keyword.
 Like abstract classes, interfaces cannot be used to create objects.
 Interface methods do not have a body - the body is provided by the "implement" class.
 On implementation of an interface, we must override all of its methods.
 Interface methods are by default abstract and public..
 Interface attributes are by default public, static and final.
 An interface cannot contain a constructor.
10.2 Defining an Interface
 The syntax for defining an interface is very similar to that for defining a class.
 The general form of an interface definition is:
interface InterfaceName
{
//Variable declaration;
//Methods declaration;
}

Here, interface is the keyword and InterfaceName is any valid Java variable. Variables
are declared as follows:
static final type VariableName=value;
All variables are declared as constants. Methods declaration will contain only a list of
methods without any body statements. Methods are declared as follows:
return-type methodName(parameter_list);
Example 1:
interface Item
{
static final float code=1001;
static final String name=”Fan”;
void display();
}

Here, the code for the method is not included in the interface and the method declaration
simply ends with a semicolon. The class that implements this interface must define the code
for the method.

Example 2:

interface Area
{
float static float pi=3,142F;
float compute(float x, float y);
void show();
}

10.3 Extending Interfaces


 An interface can extend another interface, similarly to the way that a class can extend
another class.
 The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
interface name2 entends name1
{
//Body of name2
}

Example:

interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
display();
}
The interface Item would inherit both the constants code and name into it. The variables
name and code are declared like simple variables. It is allowed because all the variables
in an interface are created as constants although the keywords final and static are not
present.
 We can also combine several interfaces together into a single interface. Following
declarations are valid.
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}

interface ItemMethods
{
display();
}

interface Item extends ItemConstants, ItemMethods


{
………..
………..
}

 While interfaces are allowed to extend to other interfaces, subinterfaces cannot define
the methods declared in the superinterfaces, Instead, it is the responsibility of any class
that implements the derived interface to define all the methods.
 An interface cannot extend classes.
10.4 Implementing Interfaces
 A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.
 Interfaces are used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface. This is done as
follows:
class classname implements Interfacename
{
//Body of classname
}
Here the class classname “implements” the interface interfacename. A more general form
of implementation may look like this:
class classname extends superclass implements Interfac1, Interface2, …
{
//Body of classname
}

This shows that a class can extend another class while implementing interfaces. When a
class implements more than one interface, they are separated by a comma.

Example:

// Java program for implementing interfaces.


// InterfaceTest.java
import java.io.*;
interface Area // Interface defined
{
final static float pi=3.14f;
float compute(float x, float y);
}
class Rectangle implements Area // Interface implemented
{
public float compute(float x, float y)
{
return (x*y) ;
}
}

class Circle implements Area // Another implementation


{
public float compute(float x, float y)
{
return (pi*x*x) ;
}
}
class InterfaceTest
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Rectangle rect=new Rectangle();
Circle cir=new Circle();
int a,b;
System.out.println("Enter the values of a & b");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
Area area; // Interface object
area=rect;
System.out.println("Area of Rectangle = "+area.compute(a,b));
area=cir;
System.out.println("Area of Circle = "+area.compute(a,0));
}
}
Output:
Enter the values of a & b
10
20
Area of Rectangle=200
Area of Circle = 314
10.5 Accessing Interface Variables
 Interfaces can be used to declare a set of constants that can be used in different classes.
Since such interfaces do not contain methods, there is no need to worry about
implementing any methods.
 The constant values will be available to any class that implements the interface.
 The values can be used in any method, as part of any variable declaration, or anywhere
we can use a final value.
interface A
{
int m=10;
int n=10;
}
class B implements A
{
int x=n;
void method B(int size)
{
…………
if (size<n)
………..
}
}
10.6 Differences between class and interface in Java
Class Interface
A class is declared by using a keyword An interface is declared by using a keyword
called class. interface.
A class can be instantiated. The keyword An interface can never be instantiated. That
new can only create an instance of a class.is an object of interface can never be
created.
Variables in a class can be declared using All variables in an interface are always
any access modifiers such as public, public, static, and final.
protected, default, and private. They can
also be static, final, or neither.
Methods declared in a class are Methods declared in an interface cannot be
implemented. i.e, methods have a body. implemented. i.e, In an interface, methods
Methods that have a body is called have no body. It contains only abstract
concrete method. method.
Note: Java 8 introduces default method,
which allows us to give the body of a
method in an interface.
The members of a class can be declared The members of an interface are always
with any access modifiers such as private, public by default.
default, protected, and public.
A class can have constructors to initialize An interface cannot have any constructors.
instance variables.
Class allows only single, multilevel and Interface supports all types of inheritance
hierarchical inheritances but do not such as multilevel, hierarchical, and
support multiple inheritance. multiple inheritance.
A class can implement any number of the Interface cannot implement any class.
interface.
A class can extend only one class at a An interface can extend multiple interfaces
time. at a time.
A class is used to define the attributes and Interface is used for defining behavior that
behaviors of an object. can be implemented by any class anywhere
in the class hierarchy.
A method in a class can be declared as The method in an interface cannot be final
final. because if we declare a method as final,the
method cannot be modified by its subclass.
A class may contain main() method. Interface cannot have main() method.

***************************************************************************
Exception Handling
***************************************************************************
11.1 Introduction
 Exception Handling is a construct in some programming languages to handle or
deal with errors automatically.
 Errors are the wrongs that can make a program go wrong. An error may produce an
incorrect output or may terminate the execution of the program abruptly or even may
cause the system to crash.
11.2 Types of Errors
 Errors may be broadly classified into two categories:
 Compile-time errors
 Run-time errors
Compile-Time Errors
 A compile-time error is an error that is detected by the compiler. Compile-time errors
occur while a program is being compiled.
 All syntax errors will be detected and displayed by the Java compiler and therefore these
errors are known as compile-time errors.
 Whenever the compiler displays an error, it will not create the .class file. It is therefore
necessary that we fix all the errors before we can successfully compile and run the
program.
Example:

// Illustration of compile-time errors


/* This program contains an error */
// Error1.java
import java.io.*;
class Error1
{
public static void main(String args[])
{
System.out.println(“Welcome to Java Programming”) // Missing Semicolon
}
}

 Most of the compile-time errors are due to typing mistakes. Typographical errors are hard
to find. The most common problems are:
 Missing semicolon
 Missing brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments / initialization
 Use of = in place of == operator

Run-Time Errors
 An error that occurs during the execution of a program is called a run-time error.
For example, running out of memory will often cause run-time error.
 Most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Using a null object reference as a legitimate object reference to access a method or a
variable
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string

Example:

// Illustration of run-time errors


class Error2
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x=a/(b-c); // Division by zero
System.out.println(“x= “+x);
int y=a/(b+c);
System.out.println(“y= “+y);
}
}

The above program is syntactically correct and therefore does not cause any problem during
compilation. However, while executing, it displays the following message and stops without
executing further statements.
Java.lang.ArithmeticException: / by zero
At Error2.main(Error2.java:10)

When Java run-time tries to execute a division by zero, it generates an error condition, which
causes the program to stop after displaying an appropriate message.
11.3 Exceptions

 An exception is an event that occurs during the execution of a program.

What is Exception Handling?

 Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.
 The purpose of exception handling mechanism is to provide a means to detect and report
an “exceptional circumstance“ so that appropriate action can be taken. The mechanism
suggests incorporation of a separate error handling code that performs the following
tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take correction actions (Handle the exception)

 The error handling code basically consists of two segments, one to detect errors and to
throw exceptions and the other to catch exceptions and to take appropriate actions.
 All exception classes are subtypes of the java.lang.Exception class. The Exception class is
a subclass of the Throwable class.
11.4 Types of Exception in Java

 Java defines several types of exceptions that relate to its various class libraries.
 Java also allows users to define their own exceptions.

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.
1. ArithmeticException

It is thrown when an exceptional condition has occurred in an


arithmetic operation.
2. 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.
3. ClassNotFoundException

This Exception is raised when we try to access a class whose


definition is not found
4. FileNotFoundException

This Exception is raised when a file is not accessible or does not


open.
5. IOException

It is thrown when an input-output operation failed or interrupted


6. InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
7. NoSuchFieldException

It is thrown when a class does not contain the field (or variable)
specified
8. NoSuchMethodException

It is thrown when accessing a method which is not found.


9. NullPointerException

This exception is raised when referring to the members of a null


object. Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a
string into a numeric format.
11. RuntimeException

This represents any exception which occurs during runtime.


12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is
either negative or greater than the size of the string
Example:
//Java program to demonstrate Arithmetic Exception
import java.io.*;
class ArithmeticException_Demo
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int c = a/b; // Cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e)
{
System.out.println ("Can't divide a number by 0");
}
}
}

1.5 Syntax of Exception Handling Code


 The basic concepts of exception handling are throwing an exception and catching it.
try and catch statements
 The try statement allows us to define a block of code to be tested for errors while it is
being executed.
 The catch statement allows us 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
{
// Statements that may cause an exception
}
catch(Exception e)
{
// Exception handling ccode
}

 The try block can have one or more statements that could generate an exception. If any
statement generates an exception, the remaining statements in the block are skipped and
execution jumps to the catch block that is placed next to the try block.
 The catch block can have one or more statements that are necessary to process the
exception.
 Every try statement should be followed by at least one catch statement; otherwise
compiler error will occur.
Example:
//Java program to demonstrate try…catch Statement
import java.io.*;
class TryCatch_Ex
{
public static void main(String args[])
{
int num1, num2;
try
{
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
}
catch (ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
}
}

Output:
You should not divide a number by zero
11.6 Multiple catch Statements
 A single try block can have multiple catch blocks.
 Each catch block must contain a different exception handler.

Syntax:
try
{
//Statements that may cause an exxception
}
catch(ExceptionType1 e1)
{
//Statements
}
catch(ExceptionType2 e2)
{
//Statements
}
catch(ExceptionType3 e3)
{
//Staatements
}
...
catch(ExceptionTypeN en)
{
//Statements
}

Example:
//Java program using multiple catch blocks
import java.util.Scanner;
public class MultiCatchEx
{
public static void main(String[] args)
{
int x, y;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter the first number");
x = Integer.parseInt(sc.nextLine());
System.out.println("Enter the second number");
y = Integer.parseInt(sc.nextLine());
int z = x / y;
System.out.println("z = " +z);
}
catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by 0");
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid data types are entered, number must be an integer.");
}
}
}
Output:
Enter the first number
40
Enter the second number
20
z=2
--------------------------------------------
Enter the first number
40
Enter the second number
0
A number cannot be divided by 0
--------------------------------------------
Enter the first number
40
Enter the second number
5.5
Invalid data types are entered, number must be an integer.
11.7 Nested try Statements
 A try block within another try block is known as nested try block.
 The try block which encloses another try block is called outer try block and the enclosed
try block is called inner try block.
Syntax:

try // Outer try block


{
//Statement(s)
try // Inner try block
{
//Statement(s)
}
catch(Exception1 e1) // Inner catch block
{
//Statement(s)
}
}
catch(Exception2 e2) // Outer catch block
{
//Statement(s)
}

Example:

//Java program to demonstrate nested try statement


import java.io.*;
class NestedTry_Ex
{
public static void main(String args[])
{
try
{
int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200};
// Displaying element at index 8
System.out.println("Element at index 8 = "+a[8]);
// Another try block
try
{
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException e)
{
System.out.println("Sorry! Division by zero isnot possible");
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
Output:
Element at index 8 = 160
Division
Sorry! Division by zero isnot possible
11.8 finally Statement
 The finally block contains statements that must be executed whether an exception occurs
or not.
 The finally block follows the try-catch block.
Syntax:
try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Example:
//Java program to demonstrate finally sstatement
import java.io.*;
class Example
{
public static void main(String args[])
{
try
{
int num=101/0;
System.out.println(num);
}
catch(ArithmeticException e)
{
System.out.println("Number should not be divided by zero");
}
finally
{
System.out.println("This is finally block");
}
}
}
Output:
Number should not be divided by zero
This is finally block

11.9 Throwing our own Exceptions


throw statement
 The throw statement is used to throw an exception explicitly.
 The throw keyword is also used to throw custom exceptions.
Syntax:
throw exception;
or
throw new exception_class("Error Message");
Example:
//Java program to demonstrate throw staatement
public class throw_ex
{
static void Validate_Age(int age)
{
if(age<18)
throw new ArithmeticException("Not eligible to vote and drive");
else
System.out.println("Eligible to vote and drive");
}
public static void main(String args[])
{
Validate_Age(10);
System.out.println("rest of the code...");
}
}

Output:

Exception in thread “throw_ex” java.lang.ArithmeticException: Not eligible


to vote and drive
at throw_ex.Validate_Age(throw_ex.java:6)
at throw_ex.main(throw_ex.java:12)
throws clause

 The “throws” keyword is used to declare an exception.


 This keyword is used to indicate that an exception might occur in the program or method.
Syntax:
type MethodName(Parameter-list) throws exception-list
{
// Body of method
}

Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Example:

//Java program to demonstrate throws keyword


import java.io.*;
class Throws_Ex
{
void TestMethod(int x) throws IOException, ArithmeticException
{
if(x==1)
throw new IOException("IOException Occurred");
else
throw new ArithmeticException("ArithmeticException");
}
}
class Main
{
public static void main(String args[])
{
try
{
Throws_Exobj=new Throws_Ex();
obj.TestMethod(1);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

Output:
java.io.IOException: IOException occurred

11.10 Creating our own Exception Subclasses


 Java allows us to create our own exception class to provide own exception
implementation.
 These type of exceptions are called user-defined exceptions or custom exceptions.
 We can create our own exception simply by extending java Exception class.
Syntax:
class MyException extends Exception
{
}

 The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable.
 Thus, all exceptions, including those that we create, have the methods defined by
Throwable available to them.
Methods Defined by Throwable
Sl. No. Method Description

1. Throwable fillInStackTrace() Returns a Throwable object that contains a


completed stack trace. This object can be
rethrown.
2. String getLocalizedMessage() Returns a localized description of the
exception.
3. String getMessage() Returns a description of the exception.
4. void printStackTrace() Displays the stack trace.
5. void printStackTrace(PrintStream stream) Sends the stack trace to the specified
stream.
6. void printStackTrace(PrintWriter stream) Sends the stack trace to the specified
stream
7. String toString() Returns a String object containing a
description of the exception. This method
is called by println() when outputting a
Throwable object.

Example:

// A Class that represents use-defined expception


import java.io.*;
class MyException extends Exception
{
}
public class setText
{
public static void main(String args[])
{
try
{
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Exception Caught");
System.out.println(ex.getMessage());
}
}
}

****************************************************************************
Multithreading
***************************************************************************
***
12.1 Definition

 The process of executing multiple threads simultaneously is called multithreading.


 The primary purpose of multithreading is to provide simultaneous execution of two or
more parts of a program to make maximum use of CPU time.
 A multithreaded program contains two or more parts that can run concurrently.
 It enables programmers to write in a way where multiple activities can proceed
simultaneously within a single application.
12.2 Advantages of Multithreading

 The benefits of multithreaded programming are:


 Economical: It is economical as they share the same processor resources. It takes lesser
time to create threads.
 Resource Sharing: It allows the threads to share resources like data, memory, files, etc.
Therefore, an application can have multiple threads within the same address space
 Responsiveness: It increases the responsiveness to the user as it allows the program to
continue running even if a part of it is performing a lengthy operation or is blocked.
 Scalability: It increases parallelism on multiple CPU machines. It enhances the
performance of multi-processor machines.
12.3 Thread

 A thread is a lightweight process.


 A thread is similar to a program that has a single flow of control. It has a beginning, a
body, and an end, and executes commands sequentially.
 In fact, all main programs can be called single-threaded programs. Every program will
have at least one thread.
 Threads are extensively used in Java-enabled browsers such as HOTJAVA. These
browsers can download a file to the local computer, display a Web page in the window,
outputs another Web page to a printer and so on.

12.4 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.
Thread Constructors
 Thread(): Allocates a new Thread object
 Thread(Runnable target): Allocates a new Thread object
 Thread(Runnable target, String name): Allocates a new Thread object
 Thread(String name): Allocates a new Thread object
 Thread(ThreadGroup group, Runnable target): Allocates a new Thread object
 Thread(ThreadGroup group, Runnable target, String name): Allocates a new
Thread object so that it has target as its run object, has the specified name as its name,
and belongs to the thread group referred to by group
 Thread(ThreadGroup group, Runnable target, String name, long stackSize):
Allocates a new Thread object so that it has target as its run object, has the specified
name as its name, and belongs to the thread group referred to by group, and has the
specified stack size
 Thread(ThreadGroup group, String name): CAllocates a new Thread object

Methods of Thread class


1. activeCount()
 This method returns an estimate of the number of active threads in the current thread’s
thread group and its subgroups.
Syntax:
public static int activeCount()
2. checkAccess()
 This method determines if the currently running thread has permission to modify this
thread.
Syntax:
public final void checkAccess()
3. clone()
 This method returns a clone if the class of this object is Cloneable.
Syntax:
protected Object clone() throws CloneNotSupportedException
4. currentThread()
 This method returns a reference to the currently executing thread object.
Syntax:
public static Thread currentThread()
5. getId()
 This method returns the id of the thread.
Syntax:
public long getId()
6. getName()
 This method returns the name of the thread.
Syntax:
public final String getName()
7. getPriority()
 This method returns the priority of the thread.
Syntax:
public final int getPriority()
8. getStackTrace()
 This method returns an array of stack trace elements representing the stack dump of
this thread.
Syntax:
public StackTraceElement[] getStackTrace()
9. getState()
 This method returns the state of the thread.
Syntax:
public Thread.State getState()
10. interrupt()
 This method interrupts the thread.
Syntax:
public void interrupt()
11. interrupted()

 This method tests whether the current thread has been interrupted.
Syntax:
public static boolean interrupted()
12. isAlive()
 This method tests if the thread is alive.
Syntax:
public final boolean isAlive()
13. isInterrupted()
 This method tests whether the thread has been interrupted.
Syntax:
public boolean isInterrupted()
14. join()
 This method waits for a thread to die.
Syntax:
public final void join() throws InterruptedException

1. join(long millis)
 This method waits at most millis milliseconds for a thread to die.
Syntax:
public final void join(long millis) throws InterruptedException
Parameters:
millis - the time to wait in milliseconds

16. resume()
 This method is used to resume the suspended thread.
public void resume()
17. run()
 This method is used to perform action for a thread.
Syntax:
public void run()
18. start()
 This method causes the thread to begin execution; the Java Virtual Machine calls the
run method of the thread.
Syntax:
public void start()
19. sleep(long millis)
 This method causes the currently executing thread to sleep (temporarily cease execution)
for the specified number of milliseconds.
Syntax:
public static void sleep(long millis) throws InterruptedException
Parameters:
millis - the length of time to sleep in milliseconds
20. setPriority(int newPriority)
 This method changes the priority of the thread.
Syntax:
public final void setPriority(int newPriority)
Parameters:
newPriority - priority to set this thread to
21. setName(String name)
 This method changes the name of the thread.
Syntax:
public final void setName(String name)
Parameters:
name - the new name for this thread.
22. stop()
This method is used to stop the thread.
Syntax:
public void stop()
23. suspend()
 This method is used to suspend the thread.
Syntax:
public void suspend()
24. toString()
 This method returns a string representation of the thread, including the thread’s name,
priority, and thread group.
Syntax:
public String toString()
25. yield()
 This method causes the currently executing thread object to temporarily pause and allow
other threads to execute.
Syntax:
public static void yield()
12.5 Creating a Thread
 There are two ways to create a thread:
i) Extending the Thread class
ii) Implementing the Runnable interface
i) Extending the Thread class
 The first way to create a thread is to create a new class that extends Thread class using
the following steps.
1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start() method to initiate the thread execution.
Declaring the Class
 The Thread class can be extended as follows:

class MyThread extends Thread


{
……………..
……………..
……………..
}
Example:
//Java program to create a Thread by extending the Thread class
import java.io.*;
class Multi extends Thread
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:
Thread is running…is running...

ii) Implementing the Runnable interface


 A thread can be created by implementing the Runnable interface.
 The Runnable interface declares the run() method that is required for implementing
threads in our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from this “ runnable” class as the
target of the thread.
4. Call the thread’s start() method to run the thread.

 The run() method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic
implementation of run() will look like this:
public void run()
{
……………….
………………. // Thread code here
……………….
}
When we start the new thread, Java calls the thread’s run() method, so it is the run() where
all of the action takes place.
Example:
// Java program to implement the Runnable interface
import java.io.*;
class Multi implements Runnable
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi m1=new Multi();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:
Thread is running...
12.6 Starting New Thread

 The start() method of thread class is used to begin the execution of thread. The result of
this method is two threads that are running concurrently: the current thread (which
returns from the call to the start method) and the other thread (which executes its run
method).
 The start thread performs the following tasks:
 It stats a new thread
 The thread moves from New State to Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
 To actually create and run an instance of our thread class, we must write the following:
MyThread Th=new MyThread();
Th.start();
The first line instantiates a new object of class MyThread.
The second line calls the start() method causing the thread to move into a runnable state.
Example:
// Creating threads using the Thread class
// File Name : ThreadClassDemo.java
import java.io.*;
public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage();
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}

Output:
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
12.7 Stopping and Blocking a Thread
Stopping a Thread
 The stop() method is used to stop the thread from running further.
Example:

MyThread.stop()

This method causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of its method. The stop() method may be used
when the premature death of the thread is desired.
Blocking a Thread
 A thread can be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods:
sleep() // blocked for a specified time
suspend() // blocked until further orders
wait() // blocked until certain condition occurs
These methods cause the thread to go into the blocked (or non-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().
12.8 Life Cycle of a Thread

 A thread moves through several states from its creation to termination. During the
lifetime of a thread, there are many states it can enter. They include:

 New
 Runnable
 Running
 Blocked (Waiting)
 Dead (Terminated)
 A thread is always in one of these five states. It can move from one state to another via a
variety of ways as shown in Figure 12.1.

Figure 12.1: State transition diagram of a thread


1) New (Newborn) State

 A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.

2) Runnable State

 The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution. If all threads have equal priority, then they are given time slots for
execution in round robin fashion i.e., first-come, first-serve manner. This process of
assigning time to threads is known as time-slicing.

3) Running State

 Running state means that the processor has given its time to the thread for its execution.
A thread can come into running state only from runnable state.

4) Blocked (Waiting) State

 A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleeping,
or waiting in order to satisfy certain requirements.

5) Dead (Terminated) State

 A runnable thread enters the terminated state when it completes its task or otherwise
terminates.

12.9 Thread Priority


 Priority means the number of resources allocated to the particular thread.
 Every thread created in JVM is assigned with a priority.
 The priority range is between 1 and 10.
1. 1 is called minimum priority
2. 5 is called normal priority
3. 10 is called maximum priority

 The default priority of the main thread is 5, child thread will take the priority that is
equal to its parent thread priority.
 We can change the priority of any thread that it may be the main thread or user-defined
thread.
 It is recommended to change the priority by using constants available in the Thread class
like follows:
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
 Threads are assigned priorities, based on that the thread scheduler can use to determine
how the thread will be scheduled.
 The thread scheduler can use thread priorities to determine which thread gets to run.

setPriority() method
 The setPriority() method is used to set the thread’s priority.
 The general form is:
ThreadName.setPriority(int newPriority);
Note: The newPriority value range should between 1 to 10 else it leads to exception
java.lang.illegalArgumentException.
Example:

t.setPriority(7); //Valid
t.setPriority(Thread.NORM_PRIORITY+2); //Valid(recommended)
getPriority() method
 The getPriority() method is used to obtain the current priority setting.
 The general form is:
ThreadName.getPriority();
Example:
// Java program using priority in threads
import java.io.*;
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("Running thread name is:"+Thread.currentThread().getName());

System.out.println("Running thread priority is:"+Thread.currentThread().getPriority());


}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
Running thread name is : Thread-0
Running thread priority is: 10
Running thread name is : Thread-1
Running thread priority is: 1
12.10 Synchronization
 The process of allowing multiple threads to modify an object in a sequence is called
synchronization.
 Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.
 Thread Synchronization is a process of allowing only one thread to use the object
when multiple threads are trying to use the particular object at the same time.
 A thread can be synchronized by using the synchronized keyword as a modifier in the
method declaration.
 The general form of the synchronized statement is
synchronized(object)
{
//Statements to be synchronized
}

Here, object is a reference to the objet being synchronized. If we want to synchronize


only a single statement, then the curly braces are not needed. A synchronized block
ensures that a call to a method that is a member of object occurs only after the current
thread has successfully entered object’s monitor.
Example:
// Java program for synchronization
// SyncDemo.java
import java.io.*;
import java.lang.*;
class ThreadX extends Thread
{
Thread s;
public void call(Thread name) throws IOException
{
s=name;
s.start();
}
public void run()
{
try
{
caller(s);
}
catch (Exception obj)
{
}
}
synchronized void caller(Thread r) throws Exception
{
System.out.println("Good Morning");
System.out.println("Good Afternoon");
r.sleep(2000);
System.out.println("Good Evening");
}
}

class SyncDemo
{
public static void main(String args[]) throws Exception
{
ThreadX one=new ThreadX();
Thread x= new Thread(one);
Thread y=new Thread(one);
Thread z=new Thread(one);
one.call(x);
one.call(y);
one.call(z);
}
}
Output:
Good Morning
Good Afternoon
Gooed Evening
Good Morning
Good Afternoon
Gooed Evening
Good Morning
Good Afternoon
Gooed Evening
12.11 Interthread Communication
 Interthread communication in Java is a technique through which multiple threads
communicate with each other.
 It provides an efficient way through which more than one thread communicate with each
other by reducing CPU idle time.
 When more than one threads are executing simultaneously, sometimes they need to
communicate with each other by exchanging information with each other. A thread
exchanges information before or after it changes its state.
 Interthread communication in Java can be achieved by using three methods provided by
Object class of java.lang package. They are:
1. wait()
2. notify()
3. notifyAll()
 These methods can be called only from within a synchronized method or synchronized
block of code otherwise, an exception named IllegalMonitorStateException is thrown.
 wait(): This method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).
 notify(): This method wakes up the first thread that called wait( ) on the same object.
 notifyAll(): This method wakes up all the threads that called wait( ) on the same object
The highest priority thread will run first.
 These methods are declared within Object, as shown here:
final void wait() throws InterruptedException
final void notify()
final void notifyAll()

Example:

// Java program to implement Interthread Communication


import java.io.*;
class Chat
{
boolean flag = false;
public synchronized void Question(String msg)
{
if (flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg)
{
if (!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(msg);
flag = false;
notify();
}
}
class T1 implements Runnable
{
char m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
public T1(Chat m1)
{
this.m = m1;
new Thread(this, "Question").start();
}
public void run()
{
for (int i = 0; i < s1.length; i++)
{
m.Question(s1[i]);
}
}
}
class T2 implements Runnable
{
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2)
{
this.m = m2;
new Thread(this, "Answer").start();
}
public void run()
{
for (int i = 0; i < s2.length; i++)
{
m.Answer(s2[i]);
}
}
}
public class TestThread
{
public static void main(String args[])
{
Chat m = new Chat();
new T1(m);
new T2(m);
}
}

Output:
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
12.12 Deadlock
 Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other.
 Deadlock occurs when multiple threads need the same locks but obtain them in different
order.
 A Java multithreaded program may suffer from the deadlock condition because the
synchronized keyword causes the executing thread to block while waiting for the lock, or
monitor, associated with the specified object.
Example:

// Java program using Deadlock concept


// TestThread.java
import java.io.*;
public class TestThread
{
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[])
{
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread
{
public void run()
{
synchronized (Lock1)
{
System.out.println("Thread 1: Holding lock 1...");
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2)
{
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread
{
public void run()
{
synchronized (Lock2)
{
System.out.println("Thread 2: Holding lock 2...");
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1)
{
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Output:
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
12.13 Thread Control
Suspending, Resuming, and Stopping Threads
 The suspend( ), resume( ), and stop( ) methods defined by the Thread class are used
to pause, restart, and stop the execution of a thread.
 The functions of Suspend, Resume and Stop a thread is performed using Boolean-type
flags in a multithreading program. These flags are used to store the current status of the
thread.
1. If the suspend flag is set to true then run() will suspend the execution of the
currently running thread.
2. If the resume flag is set to true then run() will resume the execution of the
suspended thread.
3. If the stop flag is set to true then a thread will get terminated.
 There are various static methods which we can use on thread objects to control their
behavior. Following table lists down those methods –
Sl. No Method Description
public void suspend()
This method puts a thread in the suspended state and can
1
be resumed using resume() method.

2 public void stop() This method stops a thread completely.


This method resumes a thread, which was suspended
3 public void resume()
using suspend() method.
Causes the current thread to wait until another thread
4 public void wait()
invokes the notify().
Wakes up a single thread that is waiting on this object's
5 public void notify()
monitor.
Example:
//Java program to implement suspend, resume and stop operations
import java.io.*;
class temp implements Runnable
{
Thread Th;
boolean suspend_flag, stop_flag;
temp(String tN)
{
Th=new Thread(this, tN);
suspend_flag=false;
stop_flag=false;
Th.start();
}
public void run()
{
try
{
int j=1;
while(++j<20)
{
synchronized(this)
{
while(suspend_flag)
{
wait();
}
if(stop_flag)
{
break;
}
}
}
}
catch(InterruptedException IE)
{
System.out.println("Thread Interrupted");
}
}
synchronized void my_suspend()
{
suspend_flag=true;
}
synchronized void my_resume()
{
suspend_flag=false;
notify();
}
synchronized void my_stop()
{
suspend_flag=false;
stop_flag=true;
notify();
}
}
public class SRS
{
public static void main(String args[])
{
try
{
temp t1=new temp("SRS");
System.out.println("Thread SRS is Created and Started");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_stop();
System.out.println("Thread SRS is Stopped");
}
catch(InterruptedException IE)
{
System.out.println("Generated interrupted exception");
}
}
}
Output:
Thread SRS is Created and Started
Thread SRS is Suspended
Thread SRS is Resumed
Thread SRS is Suspended
Thread SRS is Resumed
Thread SRS is Stopped
12.14 Differences between a process and a thread

Sl. No. Process Thread


1. Process means any program in Thread means segment of a process.
execution.
2. Process takes more time for creation. Thread takes less time for creation.
3. Process takes more time to terminate. Thread takes less time to terminate.
4. Processes require more time for Threads require less time for context
context switching. switching.
5. Communication between processes Communication between threads
requires more time than between requires less time than between
threads. processes.
6. Process consumes more resources. Thread consumes less resources.
7. Process is called heavy weight Thread is called light weight process.
process.
8. Processes have independent data and A thread shares the data segment, code
code segments. segment, files etc. with its peer threads.
9. If one process is blocked then it will If a user level thread gets blocked, all of
not affect the execution of other its peer threads also get blocked.
processes.
10. Process has its own Process Control Thread has Parents’ PCB, its own
Block, Stack and Address Space. Thread Control Block and Stack and
common Address Space.

You might also like