SlideShare a Scribd company logo
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 1
UNIT II – PACKAGES AND INTERFACES
Packages-defining package-access protection-importing packages- interfaces- Defining an interface-
implementing an interface-applying interface-variables in interface-extended interface-Exception
Handling-exception types-uncaught exception-multiple catch-nested try-throw and finally-built-in
exceptions multithreaded programming-java thread model-thread priorities-synchronization thread class
and runnable interface-creating multiple threads- inter thread communication-string-input and output
2.1 PACKAGES
A package in Java is used to group related classes, sub packages and interfaces. Think of it as a folder in
a file directory. Packages are used to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
2.1.1 Defining a Package
 To create a package simply include the package command as the first statement in a Java source
file. Any classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored. If you omit the package
statement, the class names are put into the default package, which has no name.
 This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;
Example
//save as Simple.java
package MyPack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make sure
that the resulting Simple.class file is also in the MyPack directory. Then try executing the Simple class,
using the following command line:
java MyPack.Simple
Remember, you will need to be in the directory above MyPack when you execute this command, or to
have your CLASSPATH environmental variable set appropriately. As explained, Simple is now part of
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 2
the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this
command line:
java Simple
Simple must be qualified with its package name.
2.1.2 Access Protection
 Classes and packages both means of encapsulating and containing the name space and scope of
variables and methods.
 Packages acts as a containers for classes and other sub – ordinate packages.
 Classes act as containers for data and code.
 Java address four categories of visibility for class members:
o Sub – classes in the same package.
o Non – sub class in the same package.
o Sub – classes in the different package.
o Classes that are neither in the same package nor subclasses.
 The 3 access specifiers private, public and protected provide a variety of ways to produce the
many levels of access required by these categories.
2.1.3 Importing Packages
There are three ways to import the package from outside the package.
1. import package.*;
2. import package.Classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Example of package that import the packagename.*
//save by A.java
package pack1;
public class A
{
public void msg()
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 3
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.Classname
If you import package.Classname then only declared class of this package will be accessible.
Example of package by import package.Classname
//save by A.java
package pack1;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack1.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the class
or interface.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 4
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.
Example of package by import fully qualified name
//save by A.java
package pack1;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack1.A(); //using fully qualified name
obj.msg();
}
}
Output:
Hello
Creating Sub package in a package:
We can create sub package in a package in the format:
package packagename.subpackagename;
e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes and
interfaces of pack2, we can write import statement as: import pack1.pack2;
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{
public void show ()
{
System.out.println ("Hello Java Learners");
}
}
Built-in Packages
The Java API is a library of prewritten classes that are free to use, included in the Java Development
Environment.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 5
The library contains components for managing input, database programming, and much more. For
example,
java.applet
java.awt
java.util
java.lang
java.net
The library is divided into packages and classes. The user can either import a single class (along with its
methods and attributes), or a whole package that contain all the classes that belong to the specified
package.
To use a class or a package from the library, use the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Example
import java.util.Scanner; // Import a single class
import java.util.*; // Import the whole package
2.2 INTERFACE
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the
java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. It
cannot be instantiated just like abstract class.
 An interface is a collection of abstract methods (i.e. methods without having definition).
 A class that implements an interface inherits abstract methods of the interface.
 An interface is not a class.
 If a class (provided it is not abstract) implements an interface, then all the methods of interface
need to be defined in it.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
2.2.1 Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
access interface name
{
final type varname1 = value;
final type varname2 = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 6
Interfaces have the following properties:
 An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract keyword
when declaring an interface.
 Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract keyword is
not needed.
 Methods in an interface are implicitly (i.e. by default) public.
The java compiler adds public and abstract keywords before the interface method. More, it adds
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and abstract.
2.2.2 Implementing Interfaces
 A class can implement more than one interface at a time.
 A class can extend only one class, but can implement many interfaces.
 An interface itself can extend another interface.
 The general form of a class that includes the implements clause looks like this:
class classname extends superclass implements interface1 , interface2...
{
// class-body
}
Example:
interface Message
{
void message1( );
void message2( );
}
class A implements Message
{
void message1( )
{
System.out.println("Good Morning");
}
void message2( )
{
System.out.println("Good Evening");
}
public static void main(String args[])
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 7
A a=new A();
a.message1();
a.message2();
}
}
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface
but a class implements an interface.
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank interface.
File: TestInterface2.java
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{ return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{ return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Output:
ROI: 9.15
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 8
Multiple Inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
Example:
interface Printable
{
void print( );
}
interface Showable
{
void show( );
}
class A implements Printable,Showable
{
public void print( )
{ System.out.println("Hello");
}
public void show( )
{ System.out.println("Welcome");
}
public static void main(String args[])
{
A obj = new A();
obj.print( );
obj.show( );
}
}
Output:
Hello
Welcome
Similarities between class and interface
 Both class and interface can contain any number of methods.
 Both class and interface are written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of both class and interface appears in a .class file.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 9
Dissimilarities between class and interface
 We cannot instantiate (i.e. create object) an interface but we can instantiate a class.
 An interface does not contain any constructors but a class may contain any constructors.
 All the methods in an interface are abstract (i.e. without definitions) but in a class method may or
may not be abstract.
 An interface cannot contain variables. The only variable that can appear in an interface must be
declared both static and final. But a class can contain any variable.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces (i.e. multiple inheritances can be achieved through it).
But a class cannot extend multiple classes (i.e multiple inheritance can not be achieved).
Difference between Class and Interface
Class Interface
In class, you can instantiate variable and create
an object.
In an interface, you can't instantiate variable and
create an object.
Class can contain concrete(with
implementation) methods
The interface cannot contain concrete(with
implementation) methods
The access specifiers used with classes are
private, protected and public.
In Interface only one specifier used is public.
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non-abstract
methods.
Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and
non-static variables.
Interface has only static and final variables.
4) Abstract class can provide the implementation of
interface.
Interface can't provide the implementation of
abstract class.
5) The abstract keyword is used to declare abstract
class.
The interface keyword is used to declare
interface.
6) Example:
public abstract class Shape
{
public abstract void draw();
}
Example:
public interface Drawable
{
void draw();
}
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Advantages of interface in java:
Advantages of using interfaces are as follows:
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 10
1. Without bothering about the implementation part, we can achieve the security of implementation
2. In java, multiple inheritance is not allowed, however you can use interface to make use of it as
you can implement more than one interface.
2.2.3 Variables in Interfaces
We can declare variables in Java interfaces. By default, these are public, final and static. That is they are
available at all places of the program, we cannot change these values and lastly only one instance of these
variables is created, it means all classes which implement this interface have only one copy of these
variables in the memory.
interface X
{
int max = 10;
}
class Example implements X
{
public void getMax()
{
System.out.println(max);
}
}
class Demo
{
public static void main(String args[])
{
Example ob = new Example();
ob.getMax();
}
}
OUTPUT:
10
2.2.4 Extended Interface
 One interface can inherit another by use of the keyword extends.
 The syntax is the same as for inheriting classes.
 When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 11
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main(String args[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
2.3 EXCEPTION HANDLING
Error occurred in a program can be of two types: syntax error or logical error.
 An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error.
 A Java exception is an object that describes an exceptional (that is, error) condition that has occurred
in a piece of code.
 Exception Handling is a mechanism by which exception occurred in a program is handled.
 The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
S.No Keyword/Block Meanings
1 try block The statements which are expected to throw exception are kept
inside try block.
2 catch block If an exception occurs within the try block, it is throws an exception
to the catch block which handle it in some rational manner.
3 throw To manually throw an exception, use the keyword throw.
4 throws A throws clause lists the types of exceptions that a method might
throw.
5 finally Any code that absolutely must be executed before a method returns
is put in a finally block.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 12
The general form of an exception-handling block is:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed before try block ends
}
2.3.1 Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top
of the exception class hierarchy.
 The Throwable class has two subclasses Error and Exception.
 Error and Exception classes are used for handling errors in java.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 13
2.3.2 Uncaught exceptions
Before we learn how to handle exceptions in our program, it is useful to see what happens when we don’t
handle them. This small program includes an expression that intentionally causes a divide-by-zero error.
class E
{
public static void main(String args[])
{
int x = 0;
int y = 1 / x;
System.out.println("This will not be printed.");
}
}
Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero
at E.main(E.java:6)
Using try and catch
The following program includes a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero error.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 14
Demonstration of Division by zero Exception.
class Ex
{
public static void main(String args[ ])
{
int x, y;
try
{
x = 0;
y= 1/ x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Notice that the call to println ( ) inside the try block is never executed. Once an exception is
thrown, program control transfers out of the try block into the catch block. Put differently, catch is not
“called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be
printed.” is not displayed. Once the catch statement has executed, program control continues with the
next line in the program following the entire try/catch mechanism.
2.3.3 Multiple Catch:
In some cases, more than one exception could be raised by a single piece of code. To handle this type
of situation, we can specify two or more catch clauses, each catching a different type of exception. When
an exception is thrown, each catch statement is inspected in order, and the first one whose type matches
that of the exception is executed. After one catch statement executes, the others are bypassed, and
execution continues after the try/catch block. The following example traps two different exception types:
Solution:
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 1 / a;
int c[ ] = { 1 };
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 15
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no command line parameters,
since a will equal zero. It will survive the division if you provide a command-line argument, setting a to
something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array
c has a length of 1, yet the program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
2.3.4 Nested try
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
try
{
statement 1;
}
catch(Exception e)
{ }
}
catch(Exception e)
{ }
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 16
Example :
class Excep6
{
public static void main(String args[])
{
try
{ try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{ System.out.println(e);
}
try
{ int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{ System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
OUTPUT:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
2.3.5 throw
Instead of exceptions thrown by the Java run-time system, throw keyword helps to throw an exception
explicitly. The general form of throw is shown here:
throw new ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. throw is a
keyword. This keyword is mainly used in user defined exception were we throw an exception manually
and terminate the execution abnormally.
The function of throw keyword and default exceptional handling is same.
Example:
class ThrowDemo
{
public static void main(String args[])
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 17
{
int x=2, y=0;
try
{
if(y==0)
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("Exception Occurred: Division by 0 " + e);
}
}
}
User Defined Exceptions
Although Java’s built-in exceptions handle most common errors, we will probably want to create our
own exception types to handle situations specific to your applications. This is quite easy to do: just define
a subclass of Exception (which is, of course, a subclass of Throwable).
Example:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class Samp1
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 18
{
System.out.println("Caught " + e);
}
}
}
OUTPUT:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
2.3.6 throws
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that
callers of the method can guard themselves against that exception. We do this by including throws clause
in the method's declaration. A throws clause lists the types of exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:
return_type method-name (parameter-list) throws exception-list
{
// body of method
}
Example:
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
OUTPUT:
Inside throwOne.
Caught java.lang.IllegalAccessException: demo
2.3.7 finally
 finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 19
 The finally block will execute whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no catch statement matches the
exception.
Example 1:
class Ex
{
public static void main(String args[])
{
int x, y;
try
{
x = 0;
y= 1/ x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("End of Try/Catch Block");
}
System.out.println("End of program");
}
}
Output:
Division by zero.
End of Try/Catch Block
End of program
Example 2:
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{ System.out.println(e);
}
finally
{ System.out.println("finally block is always executed");
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 20
}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...
2.3.8 Built-in Exceptions
 Inside the standard package java.lang, Java defines several exception classes.
 The most general of these exceptions are subclasses of the standard type RuntimeException.
 Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
 These exceptions need not be included in any method’s throws list. In the language of Java, these
are called unchecked exceptions because the compiler does not check to see if a method handles
or throws these exceptions.
Unchecked Exceptions
 Those exceptions defined by java.lang that must be included in a method’s throws list if that
method can generate one of these exceptions and does not handle it itself. These are called
checked exceptions.
Checked Exceptions
Exception Meaning
ClassNotFoundException Class not found.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Below is the list of important built-in exceptions in Java.
1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
class ArithmeticException_Demo
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 21
{
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");
}
}
}
Output: Can't divide a number by 0
2. ArrayIndexOutOfBoundException
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.
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{ int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println ("Array Index is Out Of Bounds");
}
}
}
Output: Array Index is Out Of Bounds
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.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
try
{ // Following file does not exist
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 22
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{ System.out.println("File does not exist");
}
}
}
Output: File does not exist
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
class NullPointer_Demo
{
public static void main(String args[])
{
try
{ String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{ System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
class NumberFormat_Demo
{
public static void main(String args[])
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 23
try
{ // "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
}
catch(NumberFormatException e)
{ System.out.println("Number format exception");
}
}
}
Output: Number format exception
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 than the
size of the string
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{ String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{ System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output: StringIndexOutOfBoundsException
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between final, finally
and finalize are given below:
S.No. final finally finalize
1) final is used to apply restrictions
on class, method and variable.
Final class can't be inherited, final
method can't be overridden and
final variable value can't be
changed.
finally is used to place
important code, it will be
executed whether
exception is handled or
not.
finalize is used to
perform clean up
processing just before
object is garbage
collected.
2) final is a keyword. finally is a block. finalize is a method.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 24
2.4 MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of
multitasking.
Multiprocessing and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time than
process.
Java Multithreading is mostly used in games, animation, etc.
What is a Thread?
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS, and one process can have multiple threads.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at
the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 25
 A process-based multitasking is the feature that allows our computer to run two or more
programs concurrently. For example, process-based multitasking enables us to run the Java
compiler at the same time that we are using a music player.
 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)
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
This means that a single program can perform two or more tasks simultaneously.
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.
2.4.1 Java Thread Model
One thread can pause without stopping other parts of your program. For example, the idle time created
when a thread reads data from a network or waits for user input can be utilized elsewhere.When a thread
blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.
Life Cycle of a Thread
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The
java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 26
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
2.4.2 Thread Priority
 Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
 Priorities are represented by a number between 1 and 10.
 In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses
 Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY
(a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
 Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and very much platform dependent.
 A thread’s priority is used to decide when to switch from one running thread to the next. This is
called a context switch.
The rules that determine when a context switch takes place are simple:
 A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the highest priority
thread that is ready to run is given the CPU.
 A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread
that does not yield the processor is simply preempted—no matter what it is doing— by a higher-
priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called
preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general
form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be within the
range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To
return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are
defined as static final variables within Thread. You can obtain the current priority setting by calling the
getPriority() method of Thread, shown here:
final int getPriority( )
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 27
2.4.3 The Thread Class and the Runnable Interface
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
2.4.3.1 Creating Thread by extending Thread class:
To create a thread is to create a new class that extends Thread, and then to create an instance of that
class. The extending class must override the run ( ) method, which is the entry point for the new thread.
It must also call start ( ) to begin execution of the new thread.
Thread class provide constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
The Thread class defines several methods that help manage threads.
Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
2.4.3.2 Creating Thread by Implementing Runnable interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
 To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to understand
that run() can call other methods, use other classes, and declare variables, just like the main thread can.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 28
 After we create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new
thread is specified by threadName.
 After the new thread is created, it will not start running until you call its start( ) method, which is
declared within Thread. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new Thread(obj);
t1.start();
}
}
Output: thread is running...
2.4.3 Creating Multiple Threads
We have been using only two threads: the main thread and one child thread. However, our program can
spawn as many threads as it needs. For example, the following program creates three child threads:
If you have to perform single task by many threads, have only one run() method. For example:
Program of performing single task by multiple threads
class TestMultitasking1 extends Thread
{
public void run()
{
System.out.println("task one");
}
public static void main(String args[])
{
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();
t1.start();
t2.start();
t3.start();
}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 29
}
Output:
task one
task one
task one
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
Program of performing two tasks by two threads
class Simple1 extends Thread
{
public void run()
{
System.out.println("task one");
}
}
class Simple2 extends Thread
{
public void run()
{
System.out.println("task two");
}
}
class TestMultitasking3
{
public static void main(String args[])
{
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Output:
task one
task two
Example:
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("A = "+i);
}
}
}
class B implements Runnable
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 30
{
synchronized public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("B = "+i);
}
}
}
class C implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("C = "+i);
}
}
}
class ExampleThread
{
public static void main(String[] args)
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
Thread t3 = new Thread(obj3);
t3.setPriority(7);
t2.setPriority(Thread.MAX_PRIORITY);
int n = t3.getPriority();
System.out.println("Priority of Thread t3 is " + n);
t1.start();
t2.start();
t3.start();
}
}
OUTPUT:
Priority of Thread t3 is 7
A = 1
B = 1
A = 2
B = 2
B = 3
A = 3
B = 4
C = 1
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 31
B = 5
A = 4
C = 2
A = 5
C = 3
C = 4
C = 5
Using isAlive( ) and join( )
Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to wait
for a thread to finish is called join( ), shown here:
final void join ( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes from the concept of
the calling thread waiting until the specified thread joins it. Additional forms of join ( ) allow you to
specify a maximum amount of time that you want to wait for the specified thread to terminate.
class TestJoinMethod1 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(500);
}
catch(Exception e)
{ System.out.println(e); }
System.out.println(i);
}
}
public static void main(String args[])
{
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try
{
t1.join();
}
catch(Exception e)
{System.out.println(e);}
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 32
t2.start();
t3.start();
}
}
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
2.4.4 Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object
that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter
the locked monitor will be suspended until the first thread exits the monitor. These other threads are said
to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.
2.4.4.1 Using Synchronized Methods:
Synchronization is easy in Java, because all objects have their own implicit monitor associated
with them. To enter an object’s monitor, just call a method that has been modified with the synchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of
the object to the next waiting thread, the owner of the monitor simply returns from the synchronized
method.
Example 1:
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 33
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{ this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{ this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 34
300
400
500
2.4.4.2 Using synchronized Statement:
While creating synchronized methods within classes that you create is an easy and effective means of
achieving synchronization, it will not work in all cases. To understand why, consider the following.
Imagine that you want to synchronize access to objects of a class that was not designed for
multithreaded access. That is, the class does not use synchronized methods. Further, this class was not
created by you, but by a third party and you do not have access to the source code. Thus, you can’t
add synchronized to the appropriate methods within the class. How can access to an object of this class
be synchronized?
Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by
this class inside a synchronized block. This is the general form of the synchronized statement:
synchronized (object)
{
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a
method that is a member of object occurs only after the current thread has successfully entered object’s
monitor.
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t ; int N;
MyThread1(Table t,int n)
{
this.t=t;
N=n;
}
public void run()
{
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 35
synchronized(t) //synchronized block
{
t.printTable(n);
}
}
}
public class Test
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread1 t2=new MyThread1(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Example:
class A extends Thread
{
int total;
synchronized public void run()
{
total = 0;
for(int i=1;i<=5;i++)
{
total=total + i;
}
notify();
}
}
public class Example3Thread {
public static void main(String[] args) {
A obj = new A();
try
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 36
{
obj.start();
synchronized(obj)
{
System.out.println("Waiting....");
obj.wait();
}
}
catch(Exception e)
{
}
System.out.println("Total = " + obj.total);
}
}
OUTPUT:
Waiting....
Total = 15
2.4.5 Inter Thread Communication using Wait, notify and notifyAll
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread
will run first. These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Steps for Inter thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 37
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Samp1
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM
UNIT 2 - NOTES Page 38
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

More Related Content

What's hot

Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Java packages
Java packagesJava packages
Java packages
Raja Sekhar
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Producer consumer problem operating system
Producer consumer problem operating systemProducer consumer problem operating system
Producer consumer problem operating system
Al Mamun
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Multi level inheritence
Multi level inheritenceMulti level inheritence
Multi level inheritence
RanaMOIN1
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
MD SALEEM QAISAR
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
Margaret Mary
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
Mavoori Soshmitha
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 

What's hot (20)

Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java packages
Java packagesJava packages
Java packages
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Producer consumer problem operating system
Producer consumer problem operating systemProducer consumer problem operating system
Producer consumer problem operating system
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Multi level inheritence
Multi level inheritenceMulti level inheritence
Multi level inheritence
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Java program structure
Java program structureJava program structure
Java program structure
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 

Similar to Unit 2 notes.pdf

Packages
PackagesPackages
Packages
Monika Mishra
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
Narayana Swamy
 
Packages in java
Packages in javaPackages in java
Packages in java
Kavitha713564
 
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Kavitha713564
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
talha ijaz
 
Unit4 java
Unit4 javaUnit4 java
Unit4 javamrecedu
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
Andhra University
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
7.Packages and Interfaces(MB).ppt .
7.Packages and Interfaces(MB).ppt             .7.Packages and Interfaces(MB).ppt             .
7.Packages and Interfaces(MB).ppt .
happycocoman
 
Java packages oop
Java packages oopJava packages oop
Java packages oop
Kawsar Hamid Sumon
 
packages in java & c++
packages in java & c++packages in java & c++
packages in java & c++
pankaj chelak
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
Victer Paul
 
Packages in java
Packages in javaPackages in java
Packages in java
SahithiReddyEtikala
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
Packages in java
Packages in javaPackages in java
Packages in java
Jerlin Sundari
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
manish kumar
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 
Packages
PackagesPackages
Packages access protection, importing packages
Packages   access protection, importing packagesPackages   access protection, importing packages
Packages access protection, importing packages
TharuniDiddekunta
 

Similar to Unit 2 notes.pdf (20)

Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Packages
PackagesPackages
Packages
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
Packages in java
Packages in javaPackages in java
Packages in java
 
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
 
Unit4 java
Unit4 javaUnit4 java
Unit4 java
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
7.Packages and Interfaces(MB).ppt .
7.Packages and Interfaces(MB).ppt             .7.Packages and Interfaces(MB).ppt             .
7.Packages and Interfaces(MB).ppt .
 
Java packages oop
Java packages oopJava packages oop
Java packages oop
 
packages in java & c++
packages in java & c++packages in java & c++
packages in java & c++
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
 
Packages
PackagesPackages
Packages
 
Packages access protection, importing packages
Packages   access protection, importing packagesPackages   access protection, importing packages
Packages access protection, importing packages
 

More from GayathriRHICETCSESTA

nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
GayathriRHICETCSESTA
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
GayathriRHICETCSESTA
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
GayathriRHICETCSESTA
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
GayathriRHICETCSESTA
 
Annexure 2 .pdf
Annexure 2  .pdfAnnexure 2  .pdf
Annexure 2 .pdf
GayathriRHICETCSESTA
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
GayathriRHICETCSESTA
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
GayathriRHICETCSESTA
 
nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
GayathriRHICETCSESTA
 
alumni form.pdf
alumni form.pdfalumni form.pdf
alumni form.pdf
GayathriRHICETCSESTA
 
Semester VI.pdf
Semester VI.pdfSemester VI.pdf
Semester VI.pdf
GayathriRHICETCSESTA
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
GayathriRHICETCSESTA
 
Semester V-converted.pdf
Semester V-converted.pdfSemester V-converted.pdf
Semester V-converted.pdf
GayathriRHICETCSESTA
 
Elective II.pdf
Elective II.pdfElective II.pdf
Elective II.pdf
GayathriRHICETCSESTA
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
GayathriRHICETCSESTA
 
unit 1 and 2 qb.docx
unit 1 and 2 qb.docxunit 1 and 2 qb.docx
unit 1 and 2 qb.docx
GayathriRHICETCSESTA
 
CS8601-IQ.pdf
CS8601-IQ.pdfCS8601-IQ.pdf
CS8601-IQ.pdf
GayathriRHICETCSESTA
 

More from GayathriRHICETCSESTA (20)

nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
 
CS8601-IQ.pdf
CS8601-IQ.pdfCS8601-IQ.pdf
CS8601-IQ.pdf
 
CS8601-QB.pdf
CS8601-QB.pdfCS8601-QB.pdf
CS8601-QB.pdf
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
 
Annexure 2 .pdf
Annexure 2  .pdfAnnexure 2  .pdf
Annexure 2 .pdf
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
 
ann-ics320Part4.ppt
ann-ics320Part4.pptann-ics320Part4.ppt
ann-ics320Part4.ppt
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
 
alumni form.pdf
alumni form.pdfalumni form.pdf
alumni form.pdf
 
Semester VI.pdf
Semester VI.pdfSemester VI.pdf
Semester VI.pdf
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
 
ann-ics320Part4.ppt
ann-ics320Part4.pptann-ics320Part4.ppt
ann-ics320Part4.ppt
 
Semester V-converted.pdf
Semester V-converted.pdfSemester V-converted.pdf
Semester V-converted.pdf
 
Elective II.pdf
Elective II.pdfElective II.pdf
Elective II.pdf
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
unit 1 and 2 qb.docx
unit 1 and 2 qb.docxunit 1 and 2 qb.docx
unit 1 and 2 qb.docx
 
CS8601-IQ.pdf
CS8601-IQ.pdfCS8601-IQ.pdf
CS8601-IQ.pdf
 

Recently uploaded

ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 

Recently uploaded (20)

ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 

Unit 2 notes.pdf

  • 1. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 1 UNIT II – PACKAGES AND INTERFACES Packages-defining package-access protection-importing packages- interfaces- Defining an interface- implementing an interface-applying interface-variables in interface-extended interface-Exception Handling-exception types-uncaught exception-multiple catch-nested try-throw and finally-built-in exceptions multithreaded programming-java thread model-thread priorities-synchronization thread class and runnable interface-creating multiple threads- inter thread communication-string-input and output 2.1 PACKAGES A package in Java is used to group related classes, sub packages and interfaces. Think of it as a folder in a file directory. Packages are used to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:  Built-in Packages (packages from the Java API)  User-defined Packages (create your own packages) Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. 2.1.1 Defining a Package  To create a package simply include the package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package.  The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name.  This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Example //save as Simple.java package MyPack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); } } Save this file Simple.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting Simple.class file is also in the MyPack directory. Then try executing the Simple class, using the following command line: java MyPack.Simple Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, Simple is now part of
  • 2. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 2 the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line: java Simple Simple must be qualified with its package name. 2.1.2 Access Protection  Classes and packages both means of encapsulating and containing the name space and scope of variables and methods.  Packages acts as a containers for classes and other sub – ordinate packages.  Classes act as containers for data and code.  Java address four categories of visibility for class members: o Sub – classes in the same package. o Non – sub class in the same package. o Sub – classes in the different package. o Classes that are neither in the same package nor subclasses.  The 3 access specifiers private, public and protected provide a variety of ways to produce the many levels of access required by these categories. 2.1.3 Importing Packages There are three ways to import the package from outside the package. 1. import package.*; 2. import package.Classname; 3. fully qualified name. 1) Using packagename.* If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. Example of package that import the packagename.* //save by A.java package pack1; public class A { public void msg() {
  • 3. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 3 System.out.println("Hello"); } } //save by B.java package mypack; import pack1.*; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } } Output:Hello 2) Using packagename.Classname If you import package.Classname then only declared class of this package will be accessible. Example of package by import package.Classname //save by A.java package pack1; public class A { public void msg() { System.out.println("Hello"); } } //save by B.java package mypack; import pack1.A; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } } Output: Hello 3) Using fully qualified name If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
  • 4. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 4 It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. Example of package by import fully qualified name //save by A.java package pack1; public class A { public void msg() { System.out.println("Hello"); } } //save by B.java package mypack; class B { public static void main(String args[]) { pack.A obj = new pack1.A(); //using fully qualified name obj.msg(); } } Output: Hello Creating Sub package in a package: We can create sub package in a package in the format: package packagename.subpackagename; e.g.: package pack1.pack2; Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes and interfaces of pack2, we can write import statement as: import pack1.pack2; //Creating a subpackage in a package package pack1.pack2; public class Sample { public void show () { System.out.println ("Hello Java Learners"); } } Built-in Packages The Java API is a library of prewritten classes that are free to use, included in the Java Development Environment.
  • 5. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 5 The library contains components for managing input, database programming, and much more. For example, java.applet java.awt java.util java.lang java.net The library is divided into packages and classes. The user can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, use the import keyword: Syntax import package.name.Class; // Import a single class import package.name.*; // Import the whole package Example import java.util.Scanner; // Import a single class import java.util.*; // Import the whole package 2.2 INTERFACE An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. It cannot be instantiated just like abstract class.  An interface is a collection of abstract methods (i.e. methods without having definition).  A class that implements an interface inherits abstract methods of the interface.  An interface is not a class.  If a class (provided it is not abstract) implements an interface, then all the methods of interface need to be defined in it. Why use Java interface? There are mainly three reasons to use interface. They are given below.  It is used to achieve abstraction.  By interface, we can support the functionality of multiple inheritance.  It can be used to achieve loose coupling. 2.2.1 Declaring Interfaces The interface keyword is used to declare an interface. Here is a simple example to declare an interface: access interface name { final type varname1 = value; final type varname2 = value; return-type method-name1(parameter-list); return-type method-name2(parameter-list); }
  • 6. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 6 Interfaces have the following properties:  An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract keyword when declaring an interface.  Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract keyword is not needed.  Methods in an interface are implicitly (i.e. by default) public. The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default, and methods are public and abstract. 2.2.2 Implementing Interfaces  A class can implement more than one interface at a time.  A class can extend only one class, but can implement many interfaces.  An interface itself can extend another interface.  The general form of a class that includes the implements clause looks like this: class classname extends superclass implements interface1 , interface2... { // class-body } Example: interface Message { void message1( ); void message2( ); } class A implements Message { void message1( ) { System.out.println("Good Morning"); } void message2( ) { System.out.println("Good Evening"); } public static void main(String args[]) {
  • 7. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 7 A a=new A(); a.message1(); a.message2(); } } Understanding relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. Java Interface Example: Bank Let's see another example of java interface which provides the implementation of Bank interface. File: TestInterface2.java interface Bank { float rateOfInterest(); } class SBI implements Bank { public float rateOfInterest() { return 9.15f; } } class PNB implements Bank { public float rateOfInterest() { return 9.7f; } } class TestInterface2 { public static void main(String[] args) { Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); } } Output: ROI: 9.15
  • 8. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 8 Multiple Inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance. Example: interface Printable { void print( ); } interface Showable { void show( ); } class A implements Printable,Showable { public void print( ) { System.out.println("Hello"); } public void show( ) { System.out.println("Welcome"); } public static void main(String args[]) { A obj = new A(); obj.print( ); obj.show( ); } } Output: Hello Welcome Similarities between class and interface  Both class and interface can contain any number of methods.  Both class and interface are written in a file with a .java extension, with the name of the interface matching the name of the file.  The bytecode of both class and interface appears in a .class file.
  • 9. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 9 Dissimilarities between class and interface  We cannot instantiate (i.e. create object) an interface but we can instantiate a class.  An interface does not contain any constructors but a class may contain any constructors.  All the methods in an interface are abstract (i.e. without definitions) but in a class method may or may not be abstract.  An interface cannot contain variables. The only variable that can appear in an interface must be declared both static and final. But a class can contain any variable.  An interface is not extended by a class; it is implemented by a class.  An interface can extend multiple interfaces (i.e. multiple inheritances can be achieved through it). But a class cannot extend multiple classes (i.e multiple inheritance can not be achieved). Difference between Class and Interface Class Interface In class, you can instantiate variable and create an object. In an interface, you can't instantiate variable and create an object. Class can contain concrete(with implementation) methods The interface cannot contain concrete(with implementation) methods The access specifiers used with classes are private, protected and public. In Interface only one specifier used is public. Difference between abstract class and interface Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below. Abstract class Interface 1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) Example: public abstract class Shape { public abstract void draw(); } Example: public interface Drawable { void draw(); } Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%). Advantages of interface in java: Advantages of using interfaces are as follows:
  • 10. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 10 1. Without bothering about the implementation part, we can achieve the security of implementation 2. In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement more than one interface. 2.2.3 Variables in Interfaces We can declare variables in Java interfaces. By default, these are public, final and static. That is they are available at all places of the program, we cannot change these values and lastly only one instance of these variables is created, it means all classes which implement this interface have only one copy of these variables in the memory. interface X { int max = 10; } class Example implements X { public void getMax() { System.out.println(max); } } class Demo { public static void main(String args[]) { Example ob = new Example(); ob.getMax(); } } OUTPUT: 10 2.2.4 Extended Interface  One interface can inherit another by use of the keyword extends.  The syntax is the same as for inheriting classes.  When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class MyClass implements B {
  • 11. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 11 public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } class IFExtend { public static void main(String args[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } } 2.3 EXCEPTION HANDLING Error occurred in a program can be of two types: syntax error or logical error.  An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  Exception Handling is a mechanism by which exception occurred in a program is handled.  The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. S.No Keyword/Block Meanings 1 try block The statements which are expected to throw exception are kept inside try block. 2 catch block If an exception occurs within the try block, it is throws an exception to the catch block which handle it in some rational manner. 3 throw To manually throw an exception, use the keyword throw. 4 throws A throws clause lists the types of exceptions that a method might throw. 5 finally Any code that absolutely must be executed before a method returns is put in a finally block.
  • 12. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 12 The general form of an exception-handling block is: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } finally { // block of code to be executed before try block ends } 2.3.1 Exception Types All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.  The Throwable class has two subclasses Error and Exception.  Error and Exception classes are used for handling errors in java.
  • 13. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 13 2.3.2 Uncaught exceptions Before we learn how to handle exceptions in our program, it is useful to see what happens when we don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error. class E { public static void main(String args[]) { int x = 0; int y = 1 / x; System.out.println("This will not be printed."); } } Here is the output generated when this example is executed. java.lang.ArithmeticException: / by zero at E.main(E.java:6) Using try and catch The following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error.
  • 14. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 14 Demonstration of Division by zero Exception. class Ex { public static void main(String args[ ]) { int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement. Notice that the call to println ( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism. 2.3.3 Multiple Catch: In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types: Solution: class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 1 / a; int c[ ] = { 1 };
  • 15. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 15 c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } } This program will cause a division-by-zero exception if it is started with no command line parameters, since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42]. Here is the output generated by running it both ways: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks. 2.3.4 Nested try The try block within a try block is known as nested try block in java. Why use nested try block Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntax: try { statement 1; try { statement 1; } catch(Exception e) { } } catch(Exception e) { }
  • 16. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 16 Example : class Excep6 { public static void main(String args[]) { try { try { System.out.println("going to divide"); int b =39/0; } catch(ArithmeticException e) { System.out.println(e); } try { int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement); } catch(Exception e) { System.out.println("handeled"); } System.out.println("normal flow.."); } } OUTPUT: going to divide java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5 other statement normal flow.. 2.3.5 throw Instead of exceptions thrown by the Java run-time system, throw keyword helps to throw an exception explicitly. The general form of throw is shown here: throw new ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. throw is a keyword. This keyword is mainly used in user defined exception were we throw an exception manually and terminate the execution abnormally. The function of throw keyword and default exceptional handling is same. Example: class ThrowDemo { public static void main(String args[])
  • 17. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 17 { int x=2, y=0; try { if(y==0) throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("Exception Occurred: Division by 0 " + e); } } } User Defined Exceptions Although Java’s built-in exceptions handle most common errors, we will probably want to create our own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Example: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } class Samp1 { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e)
  • 18. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 18 { System.out.println("Caught " + e); } } } OUTPUT: Called compute(1) Normal exit Called compute(20) Caught MyException[20] 2.3.6 throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. We do this by including throws clause in the method's declaration. A throws clause lists the types of exceptions that a method might throw. This is the general form of a method declaration that includes a throws clause: return_type method-name (parameter-list) throws exception-list { // body of method } Example: class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } OUTPUT: Inside throwOne. Caught java.lang.IllegalAccessException: demo 2.3.7 finally  finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.
  • 19. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 19  The finally block will execute whether or not an exception is thrown.  If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Example 1: class Ex { public static void main(String args[]) { int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } finally { System.out.println("End of Try/Catch Block"); } System.out.println("End of program"); } } Output: Division by zero. End of Try/Catch Block End of program Example 2: Let's see the java finally example where exception doesn't occur. class TestFinallyBlock { public static void main(String args[]) { try { int data=25/5; System.out.println(data); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed");
  • 20. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 20 } System.out.println("rest of the code..."); } } Output: 5 finally block is always executed rest of the code... 2.3.8 Built-in Exceptions  Inside the standard package java.lang, Java defines several exception classes.  The most general of these exceptions are subclasses of the standard type RuntimeException.  Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available.  These exceptions need not be included in any method’s throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. Unchecked Exceptions  Those exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. Checked Exceptions Exception Meaning ClassNotFoundException Class not found. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. Below is the list of important built-in exceptions in Java. 1. Arithmetic Exception It is thrown when an exceptional condition has occurred in an arithmetic operation. class ArithmeticException_Demo
  • 21. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 21 { 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"); } } } Output: Can't divide a number by 0 2. ArrayIndexOutOfBoundException 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. class ArrayIndexOutOfBound_Demo { public static void main(String args[]) { try { int a[] = new int[5]; a[6] = 9; // accessing 7th element in an array of // size 5 } catch(ArrayIndexOutOfBoundsException e) { System.out.println ("Array Index is Out Of Bounds"); } } } Output: Array Index is Out Of Bounds 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. import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; class File_notFound_Demo { public static void main(String args[]) { try { // Following file does not exist
  • 22. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 22 File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println("File does not exist"); } } } Output: File does not exist 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 class NullPointer_Demo { public static void main(String args[]) { try { String a = null; //null value System.out.println(a.charAt(0)); } catch(NullPointerException e) { System.out.println("NullPointerException.."); } } } Output: NullPointerException.. 10. NumberFormatException This exception is raised when a method could not convert a string into a numeric format. class NumberFormat_Demo { public static void main(String args[]) {
  • 23. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 23 try { // "akki" is not a number int num = Integer.parseInt ("akki") ; System.out.println(num); } catch(NumberFormatException e) { System.out.println("Number format exception"); } } } Output: Number format exception 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 than the size of the string class StringIndexOutOfBound_Demo { public static void main(String args[]) { try { String a = "This is like chipping "; // length is 22 char c = a.charAt(24); // accessing 25th element System.out.println(c); } catch(StringIndexOutOfBoundsException e) { System.out.println("StringIndexOutOfBoundsException"); } } } Output: StringIndexOutOfBoundsException Difference between final, finally and finalize There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below: S.No. final finally finalize 1) final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed. finally is used to place important code, it will be executed whether exception is handled or not. finalize is used to perform clean up processing just before object is garbage collected. 2) final is a keyword. finally is a block. finalize is a method.
  • 24. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 24 2.4 MULTITHREADING Multithreading in java is a process of executing multiple threads simultaneously. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Multiprocessing and multithreading, both are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation, etc. What is a Thread? A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area. As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) You can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:  Process-based Multitasking (Multiprocessing)  Thread-based Multitasking (Multithreading) 1) Process-based Multitasking (Multiprocessing)
  • 25. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 25  A process-based multitasking is the feature that allows our computer to run two or more programs concurrently. For example, process-based multitasking enables us to run the Java compiler at the same time that we are using a music player.  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)  In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously.  Threads share the same address space.  A thread is lightweight.  Cost of communication between the thread is low. 2.4.1 Java Thread Model One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere.When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run. Life Cycle of a Thread A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated
  • 26. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 26 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3) Running The thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. 5) Terminated A thread is in terminated or dead state when its run() method exits. 2.4.2 Thread Priority  Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.  Priorities are represented by a number between 1 and 10.  In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses  Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).  Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.  A thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place are simple:  A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest priority thread that is ready to run is given the CPU.  A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher- priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form: final void setPriority(int level) Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread. You can obtain the current priority setting by calling the getPriority() method of Thread, shown here: final int getPriority( )
  • 27. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 27 2.4.3 The Thread Class and the Runnable Interface There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. 2.4.3.1 Creating Thread by extending Thread class: To create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run ( ) method, which is the entry point for the new thread. It must also call start ( ) to begin execution of the new thread. Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface. The Thread class defines several methods that help manage threads. Method Meaning getName Obtain a thread’s name. getPriority Obtain a thread’s priority. isAlive Determine if a thread is still running. join Wait for a thread to terminate. run Entry point for the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method. Example: class Multi extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi t1=new Multi(); t1.start(); } } Output: thread is running... 2.4.3.2 Creating Thread by Implementing Runnable interface The easiest way to create a thread is to create a class that implements the Runnable interface.  To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) We will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
  • 28. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 28  After we create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here: Thread(Runnable threadOb, String threadName); Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.  After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here: void start( ); Here is an example that creates a new thread and starts it running: Example: class Multi implements Runnable { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi obj=new Multi(); Thread t1 =new Thread(obj); t1.start(); } } Output: thread is running... 2.4.3 Creating Multiple Threads We have been using only two threads: the main thread and one child thread. However, our program can spawn as many threads as it needs. For example, the following program creates three child threads: If you have to perform single task by many threads, have only one run() method. For example: Program of performing single task by multiple threads class TestMultitasking1 extends Thread { public void run() { System.out.println("task one"); } public static void main(String args[]) { TestMultitasking1 t1=new TestMultitasking1(); TestMultitasking1 t2=new TestMultitasking1(); TestMultitasking1 t3=new TestMultitasking1(); t1.start(); t2.start(); t3.start(); }
  • 29. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 29 } Output: task one task one task one If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example: Program of performing two tasks by two threads class Simple1 extends Thread { public void run() { System.out.println("task one"); } } class Simple2 extends Thread { public void run() { System.out.println("task two"); } } class TestMultitasking3 { public static void main(String args[]) { Simple1 t1=new Simple1(); Simple2 t2=new Simple2(); t1.start(); t2.start(); } } Output: task one task two Example: class A implements Runnable { public void run() { for(int i=1;i<=5;i++) { System.out.println("A = "+i); } } } class B implements Runnable
  • 30. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 30 { synchronized public void run() { for(int i=1;i<=5;i++) { System.out.println("B = "+i); } } } class C implements Runnable { public void run() { for(int i=1;i<=5;i++) { System.out.println("C = "+i); } } } class ExampleThread { public static void main(String[] args) { A obj1 = new A(); B obj2 = new B(); C obj3 = new C(); Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); Thread t3 = new Thread(obj3); t3.setPriority(7); t2.setPriority(Thread.MAX_PRIORITY); int n = t3.getPriority(); System.out.println("Priority of Thread t3 is " + n); t1.start(); t2.start(); t3.start(); } } OUTPUT: Priority of Thread t3 is 7 A = 1 B = 1 A = 2 B = 2 B = 3 A = 3 B = 4 C = 1
  • 31. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 31 B = 5 A = 4 C = 2 A = 5 C = 3 C = 4 C = 5 Using isAlive( ) and join( ) Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here: final boolean isAlive( ) The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ), shown here: final void join ( ) throws InterruptedException This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join ( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. class TestJoinMethod1 extends Thread { public void run() { for(int i=1;i<=5;i++) { try { Thread.sleep(500); } catch(Exception e) { System.out.println(e); } System.out.println(i); } } public static void main(String args[]) { TestJoinMethod1 t1=new TestJoinMethod1(); TestJoinMethod1 t2=new TestJoinMethod1(); TestJoinMethod1 t3=new TestJoinMethod1(); t1.start(); try { t1.join(); } catch(Exception e) {System.out.println(e);}
  • 32. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 32 t2.start(); t3.start(); } } Output: 1 2 3 4 5 1 1 2 2 3 3 4 4 5 5 2.4.4 Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires. 2.4.4.1 Using Synchronized Methods: Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method. Example 1: class Table { synchronized void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try {
  • 33. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 33 Thread.sleep(400); } catch(Exception e) { System.out.println(e); } } } } class MyThread1 extends Thread { Table t; MyThread1(Table t) { this.t=t; } public void run() { t.printTable(5); } } class MyThread2 extends Thread { Table t; MyThread2(Table t) { this.t=t; } public void run() { t.printTable(100); } } public class TestSynchronization2 { public static void main(String args[]) { Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200
  • 34. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 34 300 400 500 2.4.4.2 Using synchronized Statement: While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by you, but by a third party and you do not have access to the source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement: synchronized (object) { // statements to be synchronized } Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor. class Table { void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(400); } catch(Exception e) {System.out.println(e);} } } } class MyThread1 extends Thread { Table t ; int N; MyThread1(Table t,int n) { this.t=t; N=n; } public void run() {
  • 35. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 35 synchronized(t) //synchronized block { t.printTable(n); } } } public class Test { public static void main(String args[]) { Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread1 t2=new MyThread1(obj); t1.start(); t2.start(); } } Output: 5 10 15 20 25 100 200 300 400 500 Example: class A extends Thread { int total; synchronized public void run() { total = 0; for(int i=1;i<=5;i++) { total=total + i; } notify(); } } public class Example3Thread { public static void main(String[] args) { A obj = new A(); try
  • 36. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 36 { obj.start(); synchronized(obj) { System.out.println("Waiting...."); obj.wait(); } } catch(Exception e) { } System.out.println("Total = " + obj.total); } } OUTPUT: Waiting.... Total = 15 2.4.5 Inter Thread Communication using Wait, notify and notifyAll Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:  wait()  notify()  notifyAll() wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( ) Steps for Inter thread communication: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock. 6. After completion of the task, thread releases the lock and exits the monitor state of the object.
  • 37. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 37 class Customer { int amount=10000; synchronized void withdraw(int amount) { System.out.println("going to withdraw..."); if(this.amount<amount) { System.out.println("Less balance; waiting for deposit..."); try { wait(); } catch(Exception e) {} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount) { System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } class Samp1 { public static void main(String args[]) { final Customer c=new Customer(); new Thread() { public void run()
  • 38. 16CS4201 – JAVA PROGRAMMING II YEAR / IV SEM UNIT 2 - NOTES Page 38 { c.withdraw(15000); } }.start(); new Thread() { public void run() { c.deposit(10000); } }.start(); } } Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed