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

Java UnitII Ppt

Uploaded by

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

Java UnitII Ppt

Uploaded by

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

UNIT-II (BCS-403)

IT1- 4th Sem (2nd year),


Monalisa Panigrahi
1. Herbert Schildt, "Java The complete reference", McGraw Hill
Education
2. Steven Holzner, “Java Black Book”, Dreamtech.
3. Balagurusamy E, “Programming in Java”, McGraw Hill
4. Java: A Beginner’s Guide by Herbert Schildt, Oracle Press
Topics (Syllabus)
 Exception Handling: The Idea behind Exception, Exceptions &
Errors, Types of Exception, Control Flow in Exceptions, JVM Reaction to
Exceptions, Use of try, catch, finally, throw, throws in Exception
Handling, In-built and User Defined Exceptions, Checked and Un-
Checked Exceptions.

 Input /Output Basics: Byte Streams and Character Streams, Reading


and Writing File in Java.

 Multithreading: Thread, Thread Life Cycle, Creating Threads,


Thread Priorities, Synchronizing Threads, Inter-thread Communication.
Exception Handling

 The Idea behind Exception


 Exceptions & Errors
 Types of Exception
 Control Flow in Exceptions
 JVM Reaction to Exceptions
 Use of try, catch, finally, throw, throws in Exception Handling
 In-built and User Defined Exceptions
 Checked and Un-Checked Exceptions
Exception Handling

 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.

 Default Exception Handling :


 Whenever inside a method, if an exception has occurred, the
method creates an Object known as Exception Object and
hands it off to the run-time system(JVM).
 The exception object contains name and description of the
exception, and current state of the program where exception
has occurred.
 Creating the Exception Object and handling it to the run-
time system is called throwing an Exception
Error vs. Exception
Error Exception

An error represents a An error


condition serious enough that which reasonable
most reasonable applications applications should
should not try to catch. catch.

Virtual Machine Error Array index out of bounds


Out of memory Arithmetic errors
Stack overflow (divide by zero)
Thread Death Null Pointer Exception
Linkage Error I/O Exceptions
Types of Java Exceptions

 There are mainly two types of exceptions: checked and


unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are
three types of exceptions:

 Checked Exception
 Unchecked Exception
 Error
Checked Exceptions
 Inherit from class Exception but not from
RuntimeException.

 Compiler enforces catch-or-declare requirement


 Compiler checks each method call and method
declaration
 Checked exceptions are checked at compile-time

 e.g. IOException, SQLException etc.


Unchecked Exceptions

 Inherit from class RuntimeException or class Error


 Compiler does not check code to see if exception
caught or declared
 If an unchecked exception occurs and not caught
 - Program terminates or runs with unexpected results
 Can typically be prevented by proper coding
Difference between Checked and
Unchecked Exceptions

 Checked Exception:
 ➢ These Exceptions are explicitly handled in the code itself with
the help of
 try-catch blocks.
 ➢ Checked Exceptions are extended from the
 import java.lang.Exception;
 UnChecked Exception:
 ➢ These Exception are not essentially handled in the program
code; instead
 the JVM handles such exceptions.
 ➢ Unchecked Exceptions are extended from the
 Import java.lang.RuntimeException;
Exception Handling Mechanism

 Find the problem (Hit the Exception)


 Inform that an error has occurred (Throw the Exception)
 Receive the error information (Catch the Exception)
 Take corrective action (Handle the Exception)
Example of Exception

public class JavaExceptionExample {


public static void main(String args[]){
int a=6;
int b=3;

//code that may raise exception


int data=a/b;
System.out.println(“Raise exception");
}
}
Methods of Exception
Handling
 Using try-catch block
 Using finally
 Using throws
 Using throw
Try catch block
 Try block
 The try block contains set of statements where an exception can occur.
 A try block is always followed by a catch block, which handles the
exception that occurs in associated try block.
 A try block must be followed by catch blocks or finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
 Catch block
 A catch block is where you handle the exceptions, this block must
follow the try block.
 A single try block can have several catch blocks associated with it.
 You can catch different exceptions in different catch blocks.
 When an exception occurs in try block, the corresponding catch block
that handles that particular exception executes.
Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example
public class JavaExceptionExample{

public static void main(String args[]){

try{

int a=Interger.parseInt(args[0]);

int b=Interger.parseInt(args[1]);

//code that may raise exception

int data=a/b;

catch(ArithmeticException e)

System.out.println(e);

//rest code of the program

System.out.println("rest of the code...");

}
catch multiple exceptions
 A try block can be followed by one or more catch blocks.

 Each catch block must contain a different exception handler.

 So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{

int a[]=new int[5];

a[5]=30/0;

catch(ArithmeticException e)

{ System.out.println("Arithmetic Exception occurs"); }

catch(ArrayIndexOutOfBoundsException e)

{ System.out.println("ArrayIndexOutOfBounds Exception occurs"); }

catch(Exception e)

{ System.out.println("Parent Exception occurs"); }

System.out.println("rest of the code");


Output:Arithmetic Exception occurs
} rest of the code
}
Finally Block
 Java finally block is a block that is
used to execute important code such as
closing connection, stream etc.
 Java finally block is always executed
whether exception is handled or not.

Java finally block follows try or catch block.


class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num); }
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero"); }
//Finally block will always execute even if there is no exception in try block
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }

Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or unchecked exception in java by throw
keyword.
 The throw keyword is mainly used to throw custom exception.
 Syntax: throw new Throwable subclass;
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote"); }
public static void main(String args[]){
validate(13);
System.out.println("rest of the code..."); } }

Output: Exception in thread main java.lang.ArithmeticException:not valid


Throws Keyword
 Throws keyword is used for handling checked exceptions .

 By using throws we can declare multiple exceptions in one go.

import java.io.*;

class ThrowExample {

void myMethod(int num)throws IOException, ClassNotFoundException{

if(num==1)

throw new IOException("IOException Occurred");

else

throw new ClassNotFoundException("ClassNotFoundException"); } }

public class Example1{

public static void main(String args[]){

try{

ThrowExample obj=new ThrowExample();

obj.myMethod(1);

}catch(Exception ex){

System.out.println(ex); } } }
User-defined Exceptions
 We can create your own exceptions in Java. Keep the
following points in mind when writing your own
exception classes.
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
 If you want to write a runtime exception, you need to
extend the RuntimeException class.
 We can define our own Exception class as below:
 class MyException extends Exception{ }
Example of User Defined Exception
class MyException extends Exception
{
public MyException(String s)
{ // Call constructor of parent Exception
super(s); } }
public class Main
{ // Driver Program
public static void main(String args[])
{ try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks"); }
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage()); } } }
Input /Output Basics

 Byte Streams
 Character Streams
 File Handling in Java
Reading and Writing File in Java
File Handling in Java

 File Handling is an integral part of any programming


language as file handling enables us to store the output
of any particular program in a file and allows us to
perform certain operations on it.

 File handling means reading and writing data to a file.


Streams in Java
 Stream -> Sequentially access a file

 Input Stream : The input stream is used to read data


from numerous input devices like the keyboard, network,
etc.
 // Creating an InputStream
 InputStream obj = new FileInputStream();

 Output Stream : The output stream is used to write data


to numerous output devices like the monitor, file, etc.

 // Creating an OutputStream
 OutputStream obj = new FileOutputStream();
 There are two types of java streams (based on the data
types)

 Byte Stream

 Character Stream
Byte Stream
 Byte streams are used to perform input and output of 8-
bit bytes. When we want to read/write binary data, we
can use byte streams.

 FileInputStream and FileOutputStream are common


classes for reading and writing data using byte streams.

 Byte Streams are useful to read/write data from raw


binary files.
Character Stream

 The character stream is used to perform 16-bit Unicode


input and output operations.

 Character streams are used to read and write


characters.

 FileReader and FileWriter are commonly used to read and


write data using character streams.

 Character streams are used when we want to process


text files.
File operations in Java

• Create a File
• Read from a File
• Write to a File
• Delete a File
Create a File

• In order to create a file in Java, you can use the


createNewFile() method.
• If the file is successfully created, it will return a Boolean
value true and false if the file already exists.
Read from a File

 Scanner class is used in order to read contents from a


file.
Write to a File

 FileWriter class along with its write() method is used in


order to write some text to the file.
Delete a File

 We use the delete() method in order to delete a file.


Feature FileOutputStream BufferedOutputStream

Adds a buffer to FileOutputStream for


Purpose Writes bytes directly to a file.
efficient writing.

Faster for multiple small writes (writes to


Slower for multiple small writes (each
Performance memory buffer first, then to disk in
write hits the disk).
chunks).

No buffering. Each write goes straight to Uses an internal buffer (default 8 KB) to
Buffering
the file. reduce file I/O operations.

Suitable for writing many small pieces of


Usage Suitable for writing large data in one go.
data (e.g., in loops).

BufferedOutputStream bos = new


FileOutputStream fos = new
Code Sample BufferedOutputStream(new
FileOutputStream("file.txt");
FileOutputStream("file.txt"));
Multithreading
 Thread
 Thread Life Cycle
 Creating Threads
 Thread Priorities
 Synchronizing Threads
 Inter-thread Communication
Thread
 A thread is a light-weight smallest part of a process that can run
concurrently with the other parts(other threads) of the same
process.
 Threads are independent because they all have separate path of
execution that’s the reason if an exception occurs in one thread, it
doesn’t affect the execution of other threads.
 All threads of a process share the common memory.
 The process of executing multiple threads simultaneously is
known as multithreading.
 Java Multithreading is mostly used in games, animation, etc.
 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.

Life Cycle of a Thread
Stages of the life cycle

 During the life time of a thread, there are many states it can enter.
 •They include:
 1. Newborn state
 2. Runnable state
 3. Running state
 4. Blocked state
 5. Dead state
Thread Methods
There are two ways to create
a thread:
1. By extending Thread class
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. By implementing Runnable
interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
Stopping and Blocking a
thread
 Use stop() to stop a thread

 To temporarily block/suspend a thread we can use


sleep(), suspend() and wait() maethod.
 These methods cause the thread to go into the blocked
(non runnable) state.
 The thread will return to the runnable state when the
specified time is elapsed in the case of sleep(), the
resume() method is invoked in case of suspend() and
notify() method is called in case of wait().
Thread Priority
Thread Priority
class TestMultiPriority1 extends Thread{

public void run(){

System.out.println("running thread name is:"+Thread.currentThread().getName());

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

public static void main(String args[]){

TestMultiPriority1 m1=new TestMultiPriority1();

TestMultiPriority1 m2=new TestMultiPriority1();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

Output:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:1
running thread priority is:10
Synchronization
 Synchronization in java is the capability to control the access of
multiple threads to any shared resource.

 Java Synchronization is better option where we want to allow


only one thread to access the shared resource.

 The synchronization is mainly used to :

 1. To prevent thread interference.


 2. To prevent consistency problem.
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); } }

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(); } }
Inter thread communication
 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:

1. wait() 2. notify() 3. 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.

 Method Description:

1. public final void wait()throws InterruptedException (waits until object is notified.)

2. public final void wait(long timeout)throws InterruptedException (waits for the specified amount
of time.)

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:

public final void notify()

3) notifyAll() method: Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()


Deadlock

You might also like