Java Unit 2 Complete
Java Unit 2 Complete
, MJCET
Unit 2
2.1 Interfaces
An interface in Java is a blueprint of a class. It has static constants and abstract methods. It is
used to achieve abstraction.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default.
• A class that implements an interface must implement all the methods declared in the
interface.
• If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
Example
interface Student
{
public static final total=750;
public static void studentRollNo(int id);
public void percentage(int total);
}
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
Syntax:
interface Animal {
public void eat();
public void travel();
}
1
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
2
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.
2.2 Packages
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management. Package in java can be
categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
To create a package is quite easy: simply include a 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.
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
3
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
Remember that case is significant, and the directory name must match the package name
exactly. More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong.
You can create a hierarchy of packages. To do so, simply separate each package name from
the one above it by use of a period. The general form of a multileveled package statement is
shown here:
package pkg1[.pkg2[.pkg3]];
Example:
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
4
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
5
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
//save by A.java
package pack;
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 pack.A();//using fully qualified name
obj.msg();
}
}
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
to handle the exception itself or pass it on. Either way, at some point, the exception is caught
and processed. Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
6
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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 after try block ends
}
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.
7
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
For example, if you have declared an array of size 5 in your program, and trying to call the 6th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
If you compile and execute the above program, you will get the following exception
Exception Hierarchy
8
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. To guard against and handle
a run-time error, simply enclose the code that you want to monitor inside a try block.
Immediately following the try block, include a catch clause that specifies the exception type
that you wish to catch.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
catch(Exception e)
System.out.println(e);
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you 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:
9
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
10
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
2.3.5 throw
It is possible for your program to throw an exception explicitly, using the throw statement. The
general form of throw is shown here:
throw ThrowableInstance;
The flow of execution stops immediately after the throw statement; any subsequent statements
are not executed. The nearest enclosing try block is inspected to see if it has a catch statement
that matches the type of exception. If it does find a match, control is transferred to that
statement. If not, then the next enclosing try statement is inspected, and so on. If no matching
catch is found, then the default exception handler halts the program and prints the stack trace.
11
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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. You do this
by including a 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:
// body of method
Example:
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
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. 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. The finally clause is optional.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
12
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
13
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
Inside the standard package java.lang, Java defines several exception classes. A few have been
used by the preceding examples. The most general of these exceptions are subclasses of the
standard type RuntimeException. As previously explained, 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.
The above table lists 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. Java defines several other types of exceptions that relate
to its various class libraries.
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
14
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
2.4 Multithreading
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.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
15
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
16
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
17
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 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
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.
18
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
Syntax:
19
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
20
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
5. }
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. }
14. }
21
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive
when the start() method of thread class has been called and the thread is not yet dead. This
method returns true if the thread is still running and not finished.
Syntax
Return
This method will return true if the thread is alive otherwise returns false.
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive: Mutual Exclusive helps keep threads from interfering with one
another while sharing data. This can be done by three ways in java:
• Synchronized method.
• Synchronized block.
• static synchronization.
2. Cooperation (Inter-thread communication in java)
22
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
class Table
{
synchronized void printTable(int n)
{
//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
23
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
Synchronized Block
Synchronized block can be used to perform synchronization on any specific resource of the
method. Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
//code block
class Table
{
void printTable(int n)
{
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);
}
}
}
}//end of the method
}
24
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
class Table{
25
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
26
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
27
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
• wait()
• notify()
• notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
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();
28
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
}
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 Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run(){c.deposit(10000);
}
}.start();
}
}
29