SlideShare a Scribd company logo
1 of 46
JAVA UNIT 2
BY:SURBHI SAROHA
SYLLABUS
 Exception Handling
 Fundamentals exception types
 Uncaught exceptions
 Throw
 Throws
 Final
 Built in exception
 Creating your own exceptions
 Multithreaded Programming:Fundamentals
Cont…
 Java thread model:priorities
 Synchronization
 Messaging
 Thread classes
 Runable interface
 Inter thread communication
 Suspending
 Resuming and stopping threads
Exception Handling
 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.
 In Java, an exception is an event that disrupts the normal flow of the
program.
 It is an object which is thrown at runtime.
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Fundamentals exception types
 Exceptions can be categorized into two ways:
 Built-in Exceptions
 Checked Exception
 Unchecked Exception
 User-Defined Exceptions
 Exceptions that are already available in Java libraries are referred to
as built-in exception.
 These exceptions are able to define the error situation so that we can
understand the reason of getting this error.
 It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Example
 class UncheckedExceptionExample1 {
 public static void main(String args[])
 {
 int postive = 35;
 int zero = 0;
 int result = positive/zero;
 //Give Unchecked Exception here.
 System.out.println(result);
 }
 }
Uncaught exceptions
 In java, assume that, if we do not handle the exceptions in a program. In this
case, when an exception occurs in a particular function, then Java prints a
exception message with the help of uncaught exception handler.
 The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in exception
handler.
 Java programming language has a very strong exception handling mechanism.
It allow us to handle the exception use the keywords like try, catch, finally,
throw, and throws.
 When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the
exception occurs and terminates the thread.
 The Division by zero exception is one of the example for uncaught exceptions.
Throw
 The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code.
 We can throw either checked or unchecked exception.
 The throw keyword is mainly used to throw custom exceptions.
 Syntax in Java throw
 throw Instance
 Example:
 throw new ArithmeticException("/ by zero");
Example
 public class Main {
 static void checkAge(int age) {
 if (age < 18) {
 throw new ArithmeticException("Access denied - You must be at least 18 years old.");
 } else {
 System.out.println("Access granted - You are old enough!");
 }
 }

 public static void main(String[] args) {
 checkAge(15);
 }
 }
Throws
 The throws keyword indicates what exception type may be thrown by a
method.
 There are many exception types available in Java: ArithmeticException,
ClassNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc.
Example
 public class Main {
 static void checkAge(int age) throws ArithmeticException {
 if (age < 18) {
 throw new ArithmeticException("Access denied - You must be at least 18 years old.");
 }
 else {
 System.out.println("Access granted - You are old enough!");
 }
 }
 public static void main(String[] args) {
 checkAge(15); // Set age to 15 (which is below 18...)
 }
 }
Differences between throw and throws
final
 The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or
override).
 The final keyword is useful when you want a variable to always store the
same value, like PI (3.14159...).
 The final keyword is called a "modifier".
Final
 public class Main {
 final int x = 10;
 public static void main(String[] args) {
 Main myObj = new Main();
 myObj.x = 25; // will generate an error
 System.out.println(myObj.x);
 }
 }
Output
 Main.java:6: error: cannot assign a value to final variable x
myObj.x = 25;
^
1 error
Built in exception
 Exceptions that are already available in Java libraries are referred to
as built-in exception.
 These exceptions are able to define the error situation so that we can
understand the reason of getting this error.
 It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
 Checked Exception
 Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler
ensures whether the programmer handles the exception or not. The
programmer should have to handle the exception; otherwise, the system has
shown a compilation error.
Example
 import java.io.*;
 class CheckedExceptionExample {
 public static void main(String args[]) {
 FileInputStream file_data = null;
 file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt");
 int m;
 while(( m = file_data.read() ) != -1) {
 System.out.print((char)m);
 }
 file_data.close();
 }
 }
CONT……
 In the above code, we are trying to read the Hello.txt file and display its data
or content on the screen. The program throws the following exceptions:
 The FileInputStream(File filename) constructor throws
the FileNotFoundException that is checked exception.
 The read() method of the FileInputStream class throws the IOException.
 The close() method also throws the IOException.
Unchecked Exceptions
 The unchecked exceptions are just opposite to the checked exceptions.
 The compiler will not check these exceptions at compile time.
 In simple words, if a program throws an unchecked exception, and even if we
didn't handle or declare it, the program would not give a compilation error.
 Usually, it occurs when the user provides bad data during the interaction with
the program.
Creating your own exceptions
 In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom exception or
user-defined exception. Basically, Java custom exceptions are used to
customize the exception according to user need.
 Consider the example 1 in which InvalidAgeException class extends the
Exception class.
 public class WrongFileNameException extends Exception {
 public WrongFileNameException(String errorMessage) {
 super(errorMessage);
 }
 }
Multithreaded
Programming:Fundamentals
 Multithreading in Java is a process of executing multiple threads
simultaneously.
 A thread is a lightweight sub-process, the smallest unit of processing.
 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.
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.
Java thread model:priorities
 As we already know java being completely object-oriented works within
a multithreading environment in which thread scheduler assigns the processor
to a thread based on the priority of thread. Whenever we create a thread in
Java, it always has some priority assigned to it. Priority can either be given by
JVM while creating the thread or it can be given by the programmer
explicitly.
 Priorities in threads is a concept where each thread is having a priority
which in layman’s language one can say every object is having priority here
which is represented by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 1.
 Maximum priority is set to 10.
Cont….
 Here 3 constants are defined in it namely as follows:
 public static int NORM_PRIORITY
 public static int MIN_PRIORITY
 public static int MAX_PRIORITY
 Let us do discuss how to get and set priority of a thread in java.
 public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
 public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority. This method
throws IllegalArgumentException if value of parameter newPriority goes
beyond minimum(1) and maximum(10) limit.
Synchronization
 Synchronization in java is the capability to control the access of multiple
threads to any shared resource.
 In the Multithreading concept, multiple threads try to access the shared
resources at a time to produce inconsistent results.
 The synchronization is necessary for reliable communication between
threads.
 Why we use Synchronization
 Synchronization helps in preventing thread interference.
 Synchronization helps to prevent concurrency problems.
Types of Synchronization
 Synchronization is classified into two types
 Process Synchronization
 Thread Synchronization
 Process Synchronization:
 The process is nothing but a program under execution. It runs independently
isolated from another process. The resources like memory and CPU time, etc.
are allocated to the process by the operation System.
 Thread Synchronization:
 Thread synchronization is two types, they are:
Cont…..
 1.Mutual Exclusive:
 A Mutex or Mutual Exclusive helps only one thread to access the shared
resources. It won’t allow the accessing of shared resources at a time. It can
be achieved in the following ways.
 Synchronized Method
 Synchronized block
 Static Synchronization
 2. Cooperation (Inter Thread Communication in java)
Messaging
 JMS (Java Message Service) is an API that provides the facility to create, send
and read messages. It provides loosely coupled, reliable and asynchronous
communication.
 JMS is also known as a messaging service.
 Messaging is a technique to communicate applications or software
components.
 JMS is mainly used to send and receive message from one application to
another.
Requirement of JMS
 Generally, user sends message to application. But, if we want to send
message from one application to another, we need to use JMS API.
 Consider a scenario, one application A is running in INDIA and another
application B is running in USA. To send message from A application to B, we
need to use JMS.
 Advantage of JMS
 1) Asynchronous: To receive the message, client is not required to send
request. Message will arrive automatically to the client.
 2) Reliable: It provides assurance that message is delivered.
Thread classes
 Thread a line of execution within a program.
 Each program can have multiple associated threads.
 Each thread has a priority which is used by the thread scheduler to determine
which thread must run first.
 Java provides a thread class that has various method calls in order to manage
the behavior of threads by providing constructors and methods to perform
operations on threads.
 There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.
Thread class:
 Thread class provide constructors and methods to create and perform
operations on a thread.
 Thread class extends Object class and implements Runnable interface.
 Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread
class:
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run() method
on the thread.
 public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
Runnable interface:
 The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread.
 Runnable interface have only one method named run().
 public void run(): is used to perform action for a thread.
 Starting a thread:
 The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
 A new thread starts(with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
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();
 }
 }
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:
 wait()
 notify()
 notifyAll()
 1) wait() method
 The 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.
Cont…..
2) notify() method
 The 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()
Suspending
 The suspend() method of thread class puts the thread from running to waiting
state.
 This method is used if you want to stop the thread execution and start it
again when a certain event occurs.
 This method allows a thread to temporarily cease execution.
 The suspended thread can be resumed using the resume() method.
 Syntax
 public final void suspend()
Example
 public class JavaSuspendExp extends Thread
 {
 public void run()
 {
 for(int i=1; i<5; i++)
 {
 try
 {
 // thread to sleep for 500 milliseconds
 sleep(500);

Cont….
 System.out.println(Thread.currentThread().getName());
 }catch(InterruptedException e){System.out.println(e);}
 System.out.println(i);
 }
 }
 public static void main(String args[])
 {
 // creating three threads
 JavaSuspendExp t1=new JavaSuspendExp ();
 JavaSuspendExp t2=new JavaSuspendExp ();
 JavaSuspendExp t3=new JavaSuspendExp ();
 // call run() method
Cont….
 t1.start();
 t2.start();
 // suspend t2 thread
 t2.suspend();
 // call run() method
 t3.start();
 }
 }
Resuming and stopping threads
 Object lock = new Object();
 Thread myThread = new Thread(() {
 synchronized(lock) {
 try {
 lock.wait();
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 });
 myThread.start(); // start thread
 synchronized(lock) {
 lock.notify(); // resume thread
 }
Stopping Threads in Java
 class MyThread extends Thread {
 private volatile boolean running = true;
 public void stopThread() {
 running = false;
 }
 public void run() {
 while(running) {
 // do some work
 }
 }
 }
Thank you

More Related Content

Similar to JAVA UNIT 2

Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming languageushakiranv110
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 

Similar to JAVA UNIT 2 (20)

Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Exception handling
Exception handlingException handling
Exception handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

More from SURBHI SAROHA

Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2SURBHI SAROHA
 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptxSURBHI SAROHA
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)SURBHI SAROHA
 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxSURBHI SAROHA
 
Introduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptxIntroduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptxSURBHI SAROHA
 
Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)SURBHI SAROHA
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)SURBHI SAROHA
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1SURBHI SAROHA
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)SURBHI SAROHA
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)SURBHI SAROHA
 

More from SURBHI SAROHA (20)

Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2
 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptx
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)
 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptx
 
Introduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptxIntroduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptx
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
DBMS (UNIT 5)
DBMS (UNIT 5)DBMS (UNIT 5)
DBMS (UNIT 5)
 
DBMS UNIT 4
DBMS UNIT 4DBMS UNIT 4
DBMS UNIT 4
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
 
Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)
 
DBMS (UNIT 2)
DBMS (UNIT 2)DBMS (UNIT 2)
DBMS (UNIT 2)
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 

Recently uploaded

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

JAVA UNIT 2

  • 2. SYLLABUS  Exception Handling  Fundamentals exception types  Uncaught exceptions  Throw  Throws  Final  Built in exception  Creating your own exceptions  Multithreaded Programming:Fundamentals
  • 3. Cont…  Java thread model:priorities  Synchronization  Messaging  Thread classes  Runable interface  Inter thread communication  Suspending  Resuming and stopping threads
  • 4. Exception Handling  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.  In Java, an exception is an event that disrupts the normal flow of the program.  It is an object which is thrown at runtime.  Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
  • 5. Fundamentals exception types  Exceptions can be categorized into two ways:  Built-in Exceptions  Checked Exception  Unchecked Exception  User-Defined Exceptions  Exceptions that are already available in Java libraries are referred to as built-in exception.  These exceptions are able to define the error situation so that we can understand the reason of getting this error.  It can be categorized into two broad categories, i.e., checked exceptions and unchecked exception.
  • 6.
  • 7. Example  class UncheckedExceptionExample1 {  public static void main(String args[])  {  int postive = 35;  int zero = 0;  int result = positive/zero;  //Give Unchecked Exception here.  System.out.println(result);  }  }
  • 8. Uncaught exceptions  In java, assume that, if we do not handle the exceptions in a program. In this case, when an exception occurs in a particular function, then Java prints a exception message with the help of uncaught exception handler.  The uncaught exceptions are the exceptions that are not caught by the compiler but automatically caught and handled by the Java built-in exception handler.  Java programming language has a very strong exception handling mechanism. It allow us to handle the exception use the keywords like try, catch, finally, throw, and throws.  When an uncaught exception occurs, the JVM calls a special private method known dispatchUncaughtException( ), on the Thread class in which the exception occurs and terminates the thread.  The Division by zero exception is one of the example for uncaught exceptions.
  • 9. Throw  The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.  We can throw either checked or unchecked exception.  The throw keyword is mainly used to throw custom exceptions.  Syntax in Java throw  throw Instance  Example:  throw new ArithmeticException("/ by zero");
  • 10. Example  public class Main {  static void checkAge(int age) {  if (age < 18) {  throw new ArithmeticException("Access denied - You must be at least 18 years old.");  } else {  System.out.println("Access granted - You are old enough!");  }  }   public static void main(String[] args) {  checkAge(15);  }  }
  • 11. Throws  The throws keyword indicates what exception type may be thrown by a method.  There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
  • 12. Example  public class Main {  static void checkAge(int age) throws ArithmeticException {  if (age < 18) {  throw new ArithmeticException("Access denied - You must be at least 18 years old.");  }  else {  System.out.println("Access granted - You are old enough!");  }  }  public static void main(String[] args) {  checkAge(15); // Set age to 15 (which is below 18...)  }  }
  • 14. final  The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override).  The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...).  The final keyword is called a "modifier".
  • 15. Final  public class Main {  final int x = 10;  public static void main(String[] args) {  Main myObj = new Main();  myObj.x = 25; // will generate an error  System.out.println(myObj.x);  }  }
  • 16. Output  Main.java:6: error: cannot assign a value to final variable x myObj.x = 25; ^ 1 error
  • 17. Built in exception  Exceptions that are already available in Java libraries are referred to as built-in exception.  These exceptions are able to define the error situation so that we can understand the reason of getting this error.  It can be categorized into two broad categories, i.e., checked exceptions and unchecked exception.  Checked Exception  Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. The compiler ensures whether the programmer handles the exception or not. The programmer should have to handle the exception; otherwise, the system has shown a compilation error.
  • 18. Example  import java.io.*;  class CheckedExceptionExample {  public static void main(String args[]) {  FileInputStream file_data = null;  file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt");  int m;  while(( m = file_data.read() ) != -1) {  System.out.print((char)m);  }  file_data.close();  }  }
  • 19. CONT……  In the above code, we are trying to read the Hello.txt file and display its data or content on the screen. The program throws the following exceptions:  The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked exception.  The read() method of the FileInputStream class throws the IOException.  The close() method also throws the IOException.
  • 20. Unchecked Exceptions  The unchecked exceptions are just opposite to the checked exceptions.  The compiler will not check these exceptions at compile time.  In simple words, if a program throws an unchecked exception, and even if we didn't handle or declare it, the program would not give a compilation error.  Usually, it occurs when the user provides bad data during the interaction with the program.
  • 21. Creating your own exceptions  In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.  Consider the example 1 in which InvalidAgeException class extends the Exception class.  public class WrongFileNameException extends Exception {  public WrongFileNameException(String errorMessage) {  super(errorMessage);  }  }
  • 22. Multithreaded Programming:Fundamentals  Multithreading in Java is a process of executing multiple threads simultaneously.  A thread is a lightweight sub-process, the smallest unit of processing.  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.
  • 23. 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.
  • 24. Java thread model:priorities  As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by the programmer explicitly.  Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10.  The default priority is set to 5 as excepted.  Minimum priority is set to 1.  Maximum priority is set to 10.
  • 25. Cont….  Here 3 constants are defined in it namely as follows:  public static int NORM_PRIORITY  public static int MIN_PRIORITY  public static int MAX_PRIORITY  Let us do discuss how to get and set priority of a thread in java.  public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.  public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and maximum(10) limit.
  • 26. Synchronization  Synchronization in java is the capability to control the access of multiple threads to any shared resource.  In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results.  The synchronization is necessary for reliable communication between threads.  Why we use Synchronization  Synchronization helps in preventing thread interference.  Synchronization helps to prevent concurrency problems.
  • 27. Types of Synchronization  Synchronization is classified into two types  Process Synchronization  Thread Synchronization  Process Synchronization:  The process is nothing but a program under execution. It runs independently isolated from another process. The resources like memory and CPU time, etc. are allocated to the process by the operation System.  Thread Synchronization:  Thread synchronization is two types, they are:
  • 28. Cont…..  1.Mutual Exclusive:  A Mutex or Mutual Exclusive helps only one thread to access the shared resources. It won’t allow the accessing of shared resources at a time. It can be achieved in the following ways.  Synchronized Method  Synchronized block  Static Synchronization  2. Cooperation (Inter Thread Communication in java)
  • 29. Messaging  JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It provides loosely coupled, reliable and asynchronous communication.  JMS is also known as a messaging service.  Messaging is a technique to communicate applications or software components.  JMS is mainly used to send and receive message from one application to another.
  • 30. Requirement of JMS  Generally, user sends message to application. But, if we want to send message from one application to another, we need to use JMS API.  Consider a scenario, one application A is running in INDIA and another application B is running in USA. To send message from A application to B, we need to use JMS.  Advantage of JMS  1) Asynchronous: To receive the message, client is not required to send request. Message will arrive automatically to the client.  2) Reliable: It provides assurance that message is delivered.
  • 31. Thread classes  Thread a line of execution within a program.  Each program can have multiple associated threads.  Each thread has a priority which is used by the thread scheduler to determine which thread must run first.  Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to perform operations on threads.  There are two ways to create a thread:  By extending Thread class  By implementing Runnable interface.
  • 32. Thread class:  Thread class provide constructors and methods to create and perform operations on a thread.  Thread class extends Object class and implements Runnable interface.  Commonly used Constructors of Thread class:  Thread()  Thread(String name)  Thread(Runnable r)  Thread(Runnable r,String name)
  • 33. Commonly used methods of Thread class:  public void run(): is used to perform action for a thread.  public void start(): starts the execution of the thread.JVM calls the run() method on the thread.  public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.  public void join(): waits for a thread to die.  public void join(long miliseconds): waits for a thread to die for the specified miliseconds.  public int getPriority(): returns the priority of the thread.  public int setPriority(int priority): changes the priority of the thread.  public String getName(): returns the name of the thread.
  • 34. Runnable interface:  The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.  Runnable interface have only one method named run().  public void run(): is used to perform action for a thread.  Starting a thread:  The start() method of Thread class is used to start a newly created thread. It performs the following tasks:  A new thread starts(with new callstack).  The thread moves from New state to the Runnable state.  When the thread gets a chance to execute, its target run() method will run.
  • 35. 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();  }  }
  • 36. 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:  wait()  notify()  notifyAll()  1) wait() method  The 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.
  • 38. 2) notify() method  The 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()
  • 39. Suspending  The suspend() method of thread class puts the thread from running to waiting state.  This method is used if you want to stop the thread execution and start it again when a certain event occurs.  This method allows a thread to temporarily cease execution.  The suspended thread can be resumed using the resume() method.  Syntax  public final void suspend()
  • 40. Example  public class JavaSuspendExp extends Thread  {  public void run()  {  for(int i=1; i<5; i++)  {  try  {  // thread to sleep for 500 milliseconds  sleep(500); 
  • 41. Cont….  System.out.println(Thread.currentThread().getName());  }catch(InterruptedException e){System.out.println(e);}  System.out.println(i);  }  }  public static void main(String args[])  {  // creating three threads  JavaSuspendExp t1=new JavaSuspendExp ();  JavaSuspendExp t2=new JavaSuspendExp ();  JavaSuspendExp t3=new JavaSuspendExp ();  // call run() method
  • 42. Cont….  t1.start();  t2.start();  // suspend t2 thread  t2.suspend();  // call run() method  t3.start();  }  }
  • 43. Resuming and stopping threads  Object lock = new Object();  Thread myThread = new Thread(() {  synchronized(lock) {  try {  lock.wait();  } catch (InterruptedException e) {  e.printStackTrace();  }  }  });
  • 44.  myThread.start(); // start thread  synchronized(lock) {  lock.notify(); // resume thread  }
  • 45. Stopping Threads in Java  class MyThread extends Thread {  private volatile boolean running = true;  public void stopThread() {  running = false;  }  public void run() {  while(running) {  // do some work  }  }  }