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

MODULE III MR-22 Java Intefaces Exceptiona Handling and Multithearding-1

Uploaded by

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

MODULE III MR-22 Java Intefaces Exceptiona Handling and Multithearding-1

Uploaded by

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

MODULE-III

Interfaces and Exception Handlings in Java

Part-A

Interfaces using Java Programming Language


Defining an Interface:- An Interface in the java programming language
is an abstract type that is used to declare a behaviour that classes must be
implement.

An Interlace in java is a blueprint a class.

 Interfaces are declared using the interface key word.


 It is a static constant and abstract methods declarations.
 Once declared Interface don’t changes or modifications interfaces
classes and methods.
 It is using data abstraction, polymorphism and multiple inheritance
are supported through java language.

How to declare or create a interface?

Syntax :

interface <interface-name> {
void method-name();
}
public class <interface-name> implements <user-defined variable
name>
{
void method-name()
{
// inputs and outputs statements;
}
public static void main (String args[])
{
class-name objec-name = new class-name();
// call or display to method
}
}
Example 1: Write a java program how to implement interface and
display message are “Hello? How are U?”.

import java.util.*;
inteface mrec { // To create or applying a intefaces
void cse(); // user defined method declarations
}
public class mrec implements csedept // To implementing Interface
{
public static void print()
{
System.out.println (“ Hello? How are U?”);
}
public static void main (String args[])
{
mrec m=new mrec(); // To create a object
m.cse();
}
}

Output:

Hello! How are U?


Example 2: Write a java program how to create a interface and
draw a rectangle and circle.

import java.util.*;
interface Drawable { // To create or applying Interface
void draw();
}
class Drawable implements rect { // To create rectangle class
Implementing Intefaces
void draw()
{
System.out.println (“ Drawing a Rectangle”);
}
}
class Drawable implements cir { // To create circle class implementing
Interfaces
void draw()
{
System.out.println (“Drawing a Circle”);
}
}
public class cse {
Public static void main(String args[])
{
Drawable d = new Drawable(); // To create a object
d.draw();
}
}
Multiple Interfaces in Java
Multiple Interfaces support to java in place of Multiple Inheritance.

Example 1 : Write a java program how to implement multiple


interfaces.

import java.util.*;
interface Flyable { // To Create/applying a Interfac1 1
void fly();
}
interface Eatable { // To Create /applying Interface 2
void eat();
}
class Bird implements Flyable, Eatable // To implementing Interfaces
1 and 2
{
public void fly()
{
System.out.println("Bird flying");
}
public void eat()
{
System.out.println("Bird eats");
}
}
public class cse
{
public static void main(String[] args)
{
Bird b = new Bird();
b.eat();
b.fly();
}
}

Output:

Bird eats
Bird flying
Difference between abstract class and interface :

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.

7) An abstract class can be extended An interface can be implemented


using keyword "extends". using keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.

9) Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }
Example 3 : Write a java program how to create interfaces using a
abstract class.

1. interface A{ // To create or applying Interfaces


2. void a(); //bydefault, public and abstract
3. void b();
4. void c();
5. void d();
6. }
//Creating abstract class that provides the implementation of one
method of A interface
7. abstract class B implements A { // To create abstract class with
implementing Interface
8. public void c()
9. {
10. System.out.println("CSE C");
11. }
12. }
13. //Creating subclass of abstract class, now we need to provide
the implementation of rest of the methods
14. class M extends B{
15. public void a()
16. {
17. System.out.println("CSE A");
18. }
19. public void b()
20. {
21. System.out.println("CSE B");
22. }
23. public void d()
24. {
25. System.out.println("CSE D");
26. }
27. }
28. //Creating a test class that calls the methods of A interface
29.
30. public class mrec
31. {
32. public static void main(String args[])
33. {
34. A a=new M();
35. a.a();
36. a.b();
37. a.c();
38. a.d();
39. }
40. }

Variables in Interface

Rules in variables using Interfaces :


 An interface is a container of abstract methods and static, final
default variables.

 The interface contains the static, final, and default variables the
automatically adds as a public.

 The variables defined in an interface can not be modified by the class


that implements the interface.

 No access modifier is allowed except the public for interface


variables.

 Every variable of an interface must be initialized in the interface


itself.

Extending Interfaces

Rules for Extending Interfaces :


 In java, an interface can extend another interface.

 When an interface wants to extend another interface, it uses the


keyword is extend.

 The interface that extends another interface has its own members and
all the members defined in its parent interface.

 The class which implements a child interface needs to provide code


for the different methods defined in both child and parent interfaces,
otherwise, it needs to be defined as abstract class.

 An interfaces can not extended multiple interfaces

 An Interface can implemented to use extend key word in define a


class.

Example : Write a java program how to create extending


Interfaces

interface PI{ // To create Interface for super class


void PM();
}
interface CI extends PI // To create another Interface using extend
{
void CM();
}

class cse implements CI{ // To implementing Interface

public void CM()


{
System.out.println("Child Interface method!!");
}
public void PM()
{
System.out.println("Parent Interface mehtod!");
}
}
public class mrec {

public static void main(String[] args)


{
cse c = new cse();
c.CM();
C.PM();

}
}

Exploring java.io or Java Input and Output stream


methods or functions
 In java, the IO (Input and Output) operations are performed using the
concept of streams.

 a stream means a continuous flow of data.

 In java, a stream is a logical container of data that allows us to read


from and write to it.

 A stream can be linked to a data source, or data destination, like a


console, file or network connection by java IO system.

 The stream-based IO operations are faster than normal IO operations.

 The Stream is defined in the java.io package.

How to work java io stream

Types of io stream :

In Java, every program creates 3 streams automatically. They are


 A). System.out: standard output stream for console output
operations.
 B). System.in: standard input stream for console input operations.
 C). System.err:standard error stream for console error output
operations.

Java provides another predefined two types of streams. They are

 Byte Stream
 Character Stream
1. Byte Streams
Byte stream is used to read and write a single byte (8 bits) of data.

A). Input Stream class


The InputStream class has defined as an abstract class, and it has the
following methods which have implemented by its concrete classes.

S.No. Method with Description

1 int available()
It returns the number of bytes that can be read from the input stream.

2 int read()
It reads the next byte from the input stream.

3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte
array, b.

4 void close()
It closes the input stream and also frees any resources connected with this
input stream.
B. Output Stream class
The OutputStream class has defined as an abstract class, and it has the
following methods which have implemented by its concrete classes.

S.No
. Method with Description

1 void write(int n)
It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.

3 void flush()
It flushes the output steam by forcing out buffered bytes to be written
out.

4 void close()
It closes the output stream and also frees any resources connected with
this output stream.

 Reading data using BufferedInputStream :


We can use the BufferedInputStream class to read data from the console.
The BufferedInputStream class use a method read( ) to read a value from
the console, or file, or socket.
Example : Write a java program how to create a reading
file.

import java.io.*;
public class ReadingDemo {

public static void main(String[] args) throws IOException


{

FileInputStream fileInputStream = new FileInputStream(new File("C:\\


cse\\dataFile.txt"));
BufferedInputStream input = new BufferedInputStream(fileInputStream);
try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
input.close();
}
}
}

 Writing data using BufferedOutputStream


We can use the BufferedOutputStream class to write data into the
console, file, socket. The BufferedOutputStream class use a method
write( ) to write data.
Example : Write a java program how to writing a file.
import java.io.*;
public class WritingDemo {
public static void main(String[] args) throws IOException
{
String data = "Java tutorials by BTech CSE Class";
BufferedOutputStream out = null;
try
{
FileOutputStream fileOutputStream = new FileOutputStream(new
File("C:\\cse\\dataFile.txt"));
out = new BufferedOutputStream(fileOutputStream);
out.write(data.getBytes());
System.out.println("Writing data into a file is success!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
out.close();
}
}
}

2. Character Streams

Character stream is used to read and write a single character of data.


There are two different types of character streams classes. They are

A). reader class B). writer class

A. Reader Class :

The Reader class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.
S.No. Method with Description

1 int read()
It reads the next character from the input stream.

2 int read(char[] cbuffer)


It reads a chunk of charaters from the input stream and store them in its byte

3 int read(char[] cbuf, int off, int len)


It reads charaters into a portion of an array.

4 int read(CharBuffer target)


It reads charaters into into the specified character buffer.

5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a lin
a carriage return ('\r').

6 boolean ready()
It tells whether the stream is ready to be read.

7 void close()
It closes the input stream and also frees any resources connected with this inp

Example : Write a java program how to reading a file using in


charter stream.

import java.io.*;
public class ReadingDemo {

public static void main(String[] args) throws IOException


{
Reader in = new FileReader();
try
{
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
input.close();
}
}
}

B. Writer class :

The Writer class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.
S.No. Method with Description

1 void flush()
It flushes the output steam by forcing out buffered bytes to be
written out.

2 void write(char[] cbuf)


It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)


It writes a portion of an array of characters.

4 void write(int c)
It writes single character.

5 void write(String str)


It writes a string.

6 void write(String str, int off, int len)


It writes a portion of a string.

7 Writer append(char c)
It appends the specified character to the writer.

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)


It appends a subsequence of the specified character sequence to the writer.

10 void close()
It closes the output stream and also frees any resources connected
with this output stream.

Example : Write a java program how to writing a data into a file


using character steam.

import java.io.*;
public class WritingDemo {
public static void main(String[] args) throws IOException
{

Writer out = new FileWriter("C:\\cse\\dataFile.txt");

String msg = "The sample data";

try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
out.close();
}
}
}

MODULE-III
Part-B
Exceptions Handling & Multi Threading in Java
 The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.

 Exception is an abnormal condition or runtime errors.

Hierarchy of Java Exception classes


 The java.lang. Throwable class is the root class of Java Exception
hierarchy inherited by two sub classes: Exception and Error.

 The hierarchy of Java Exception classes is given below:

Types of Java Exceptions:


There are mainly two types of exceptions: checked and unchecked. An
error is considered as the unchecked exception.
1. Checked Exception
2. Unchecked Exception or Error

1) Checked Exception:
 The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.

Examples:- IOException, SQLException, etc.

 Checked exceptions are checked at compile-time.

2) Unchecked Exception:
 The classes that inherit the RuntimeException are known as
unchecked exceptions.

Example:-

 ArithmeticException,NullPointerException,OutofMemory,ArrayInde
xOutOfBoundsException, VirtualMachineError, etc.

 Unchecked exceptions are not checked at compile-time, but they are


checked at runtime.

Java Exception Handling keywords :


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

Keywords Description

try The "try" keyword is used to specify a block where we should


place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block
alone.

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

throws The "throws" keyword is used to declare exceptions. It specifies


that here may occur an exception in the method. It is multiple
Throws exceptions.

Syntax for Expectation Handling:

1. try // try block


2. {
3. //code that may throw an exception
4. }catch(Exception_class_Name ref) // catch block
5. {
6. // input and output statements;
7. }
8. finally // finally block
9. (
10. // Input and output statements;
11. }

Example 1:- Write a java program how to create simple


exceptions handling.

import java.lang.*;
public class TCatchCse {

1. public static void main(String[] args) throw IOExcption


2. {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. catch(ArithmeticException e) // handling the exception
8. {
9. System.out.println (e);
10. }
11. System.out.println ("rest of the code");
12. }
13. finally
14. {
15. System.out.println (“ Have a Nice Day!”);
16. }
17. }

OUTPUT

java.lang.ArithmeticException: / by zero
rest of the code Hava Nice Day!
Example 2: Write a java program how to create exception handling

import java.lang.*;
public class csed {
public static void main(String[] args) throw IOExcption
{
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e)
{
System.out.println("Something went wrong.");
}
finally
{
System.out.println("The 'try catch' is finished.");
}
}
}

Nested or Multiple try-catch block Exception Handling

 In Java, using a try block inside another try-catch block is permitted.


It is called as nested try-catch block.

 Every statement that we enter a statement in try-catch block, context


of that exception is pushed onto the stack.
Example:-
The inner try block can be handle
ArrayIndexOutOfBoundsException

while the outer try block can handle the ArithemeticException (division
by zero).

Syntax for Nested or Multiple try-catch block :

1. ....
2. //main or outer try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch inner block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch inner another block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2) ;
19. {
20. //exception message-1
21. }
22. }
23. catch(Exception e1)
24. {
25. //exception message-2 ;
26. }
27. }
28. //catch block of parent (outer) try block
29. catch(Exception e3)
30. {
31. //exception message-3 ;
32. }
33. ....

Example : Write a java program how to create nested/multiple try


catch statements.
import java,lang.*;
1. public class NestedTryBlock{
2. public static void main(String args[]) throws IOExcption
3. {
4. //outer try block
5. try{
6. //inner try block 1
7. try{
8. System.out.println("going to divide by 0");
9. int b =39/0;
10. }
11. //catch block of inner try block 1
12. catch(ArithmeticException e)
13. {
14. System.out.println(e);
15. }
16. //inner try block 2
17. try{
18. int a[]=new int[5];
19. //assigning the value out of array bounds
20. a[5]=4;
21. }
22. //catch block of inner try block 2
23. catch(ArrayIndexOutOfBoundsException e)
24. {
25. System.out.println(e);
26. }
27. System.out.println("other statement");
28. }
29. //catch block of outer try block
30. catch(Exception e)
31. {
32. System.out.println("handled the exception (outer catch)");
33. }
34. System.out.println("normal flow..");
35. }
36. }

Example : Write a java program how to use throw keyword.

public class ExceptionDemo

static void canVote(int age)

if(age<18)

try

throw new Exception();

catch(Exception e)

{
System.out.println ("you are not an adult!");

else

System.out.println("you can vote!");

public static void main (String[] args)

canVote(20);

canVote(10);

Multi threading in Java


 Multithreading in Java is a process of executing multiple threads
simultaneously.
 Multitasking is when multiple processes share common processing
resources such as a CPU.
 Multi-threading extends the idea of multitasking into applications
where you can subdivide specific operations within a single
application into individual threads.
 Each of the threads can run in parallel.
 The OS divides processing time not only among different
applications, but also among each thread within an application.
 Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.

Thread Life Cycle


Following are the stages of the life cycle −
 New − A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is also
referred to as a born thread.
 Runnable − After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.

 Waiting − Sometimes, a thread transitions to the waiting state


while the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.

 Timed Waiting − A runnable thread can enter the timed waiting


state for a specified interval of time. A thread in this state transition
back to the runnable state when that time interval expires or when
the event it is waiting for occurs.

 Terminated (Dead) − A runnable thread enters the terminated state


when it completes its task or otherwise terminates.

Create a Thread by Implementing a Runnable Interface :


If your class is intended to be executed as a thread then you can achieve
this by implementing a Runnable interface. You will need to follow
three basic steps −
Step 1 : As a first step, you need to implement a run() method provided
by a Runnable interface. This method provides an entry point for the
thread and you will put your complete business logic inside this method.
Following is a simple syntax of the run() method −
public void run( )
Step 2 : As a second step, you will instantiate a Thread object using the
following constructor

Thread(Runnable threadObj, String threadName);


Where, threadObj is an instance of a class that implements
the Runnable interface and threadName is the name given to the new
thread.
Step 3 : Once a Thread object is created, you can start it by
calling start() method, which executes a call to run( ) method. Following
is a simple syntax of start() method

void start();

Example 1 : Write a java program how to create a thread java


program
import java.io.*;
import java.lang.*;
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();
}
}

(OR)

import java.io.*;
import java.lang.*;
public class Main extends Thread {
public static void main(String[] args)
{
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run()
{
System.out.println("This code is running in a thread");
}
}

Example 2 : Write a java program how to implement thread


using Simple Runnable Interface.

import java.io.*;
import java.lang.*;
public class cse implements Runnable
{
public void run()
{
System.out.println("Thread has ended");
}

public static void main(String[] args)


{
cse c = new ExampleClass();
Thread t1= new Thread(c);
t1.start();
System.out.println("Hi! How are You?");
}
}

OUTPUT :

Hi! How are You?


Thread has ended
Example 3 : Write a java program how to implement
multiple threads using Runnable Interface.

import java.io.*;
import java.lang.*;
Public class RunnableDemo implements Runnable {
public Thread t;
public String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}

public void run()


{
System.out.println("Running " + threadName );
try
{
for(int i = 4; i > 0; i--)
{
System.out.println("Thread: " + threadName + ", " + i);

Thread.sleep(50); // Let the thread sleep for a while.


}
} catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread
{
public static void main(String args[])
{
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}

You might also like