m3 java
m3 java
Note:-
Throwable, Error, and Exception, are all defined in the java.lang package. This package is automatically imported into every
class file
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:
•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.
Difference between Error and Exception
Let us discuss the most important part which is the differences between Error and
Exception that is as follows:
•Error: An Error indicates a serious problem that a reasonable application should not
try to catch.
•Exception: Exception indicates conditions that a reasonable application might try to
catch.
The "try" keyword is used to specify a block where we should place an exception
try code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
The "catch" block is used to handle the exception. It must be preceded by try block
catch which means we can't use catch block alone. It can be followed by finally block
later.
The "finally" block is used to execute the necessary code of the program. It is
finally
executed whether an exception is handled or not.
The "throws" keyword is used to declare exceptions. It specifies that there may
throws occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Syntax
try-catch Block − try - catch block in java is used to handle exceptions. The try - block contains the code which
may throw an exception. The catch block catches the exception and handles the exception.
try
{
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
Methods to print the Exception information:
1. printStackTrace()
This method prints exception information in the format of the Name of the exception: description of the
exception, stack trace.
import java.io.*;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
2. toString()
The toString() method prints exception information in the format of the Name of the exception: description of
the exception.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}
3. getMessage()
The getMessage() method prints only the description of the exception.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
// Java Program to Demonstrate How Exception Is Thrown
class GFG {
int i = arr[4];
System.out.println(
"finally : i execute always.");
}
}
}
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block, and finally block executes after the
catch block.
import java.io.*;
class GFG {
catch (ArithmeticException e) {
System.out.println(
"catch : exception handled.");
}
finally {
System.out.println("finally : i execute always.");
}
}
}
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so finally block execute after the try block
and after the execution of finally block program terminate abnormally, But finally block execute fine.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");
System.out.println(
"catch : exception not handled.");
}
finally {
System.out.println( "finally : i will execute always.");
}
System.out.println("i want to run");
}
Basis of throw throws
Differences
The throw keyword is followed by an instance of The throws keyword is followed by class
3. Syntax
Exception to be thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
class Animal{
void eatSomething(){System.out.println("eating something");}
}
class Dog extends Animal{
@Override
void eatsomething(){System.out.println("eating foods");}
}
class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
// Java Program to Demonstrate that Annotations
class Base {
public void display()
{
System.out.println("Base display()");
}
}
class Derived extends Base {
@Override public void display(int x)
{
System.out.println("Derived display(int )");
}
public static void main(String args[])
{
// Creating object of this class inside main()
Derived obj = new Derived();
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
If you remove the
@SuppressWarnings("unchecked") annotation,
}} it will show warning at compile time
because we are using non-generic
collection.
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints
warning. It informs user that it may be removed in the future versions. So, it is better
not to use such methods.
class A{
void m(){System.out.println("hello m");}
@Deprecated
void n(){System.out.println("hello n");}
}
class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}}
Java Custom Annotations
Java Custom annotations or Java User-defined annotations are easy to create and
use. The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.
Types of Annotation
There are three types of annotations.
1.Marker Annotation
2.Single-Value Annotation
3.Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is
called marker annotation. For
example:
@interface MyAnnotation{}
The @Override and @Deprecated are
marker annotations.
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
3) Multi-Value Annotation
An annotation that has more than one
method, is called Multi-Value annotation.
For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
Built-in Annotations used in custom annotations in
java
•@Target
•@Retention
•@Inherited
•@Documented
@Target
@Target tag is used to specify at which type, the annotation
is used.
//Creating annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
}
class Hello{
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello annotation");}
}
class TestCustomAnnotation1{
public static void main(String args[])throws Exception{
MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}}
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation
marks the annotation to be inherited to subclasses.
@Documented
The @Documented Marks the annotation for inclusion in the documentation.
Multithreading in Java is a process of executing multiple threads
simultaneously.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
New Thread creation: When a program calls the start() method, a new thread is created and then
the run() method is executed. But if we directly call the run() method then no new thread will be
created and run() method will be executed as a normal method call on the current calling thread itself and
no multi-threading will take place.
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "+ Thread.currentThread().getName());
System.out.println("run() method called");
}}
class Multithread3
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
}
}
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
class Multithread4{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
}
}
when we called the run() method of our MyThread class, no new thread is created and the run() method is
executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is
called as a normal function call.
In Java’s multi-threading concept, another most important difference between start() and run() method is that
we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method
can be called multiple times as it is just a normal method calling
LifeCycle of a Thread in java.
A thread goes through various stages while executing or completing task like new/born, ready, runnable and finally dead
state, these states are nothing but is life cycle of a Thread.
Below is the diagram which tells the story of Thread life cycle i.e. how a thread goes into ready state from born state and
from ready to running and finally into Dead state. Please go through this to understand the life cycle of a Thread.
1.When we write MyThread t1=new MyThread() then thread is in the New/Born state.
2.When we call t.start() method then thread enters into Ready State or Runnable State.
3.If Thread Scheduler allocates the processor to Thread then Thread enters into Running State.
4.If run() method completes successfully then thread enters into Dead State.
5. If a running thread calls the Thread.yield() method then thread enters into ready state from
running state to give chance to other waiting thread of same priority immediately.
6. If thread calls the wait() method then running thread will enters into waiting state. if this thread got any
notification by method notify()/notifyAll() then it enters into another waiting state to get lock.so when the
thread comes out of waiting state to another waiting state to get lock is-
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1.Mutual Exclusive
1. Synchronized method.
2. Synchronized block(more faster).
3. Static synchronization.
2.Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using
the following three ways:
1.By Using Synchronized Method
2.By Using Synchronized Block
3.By Using Static Synchronization
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the
thread completes its task.
//example of java synchronized method class MyThread2 extends Thread{
class Table{ Table t;
synchronized void printTable(int n){ MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
try{ public void run(){
Thread.sleep(400); t.printTable(100);
}catch(Exception e){System.out.println(e);} }
} }
}
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases, we can
use synchronized block.
• If we put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Points to Remember
• Synchronized block is used to lock an object for any shared
resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM,
to provide access control to a shared resource.
• The system performance may degrade because of the
slower working of synchronized keyword.
• Java synchronized block is more efficient than Java
synchronized method.
class Table
{ class MyThread2 extends Thread{
void printTable(int n){ Table t;
synchronized(this){//synchronized block MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
try{ public void run(){
Thread.sleep(400); t.printTable(100);
}catch(Exception e){System.out.println(e);} }
} }
}
}//end of the method public class TestSynchronizedBlock1{
} public static void main(String args[]){
Table obj = new Table();//only one object
class MyThread1 extends Thread{ MyThread1 t1=new MyThread1(obj);
Table t; MyThread2 t2=new MyThread2(obj);
MyThread1(Table t){ t1.start();
this.t=t; t2.start();
} }
public void run(){ }
t.printTable(5);
}
}
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.
Static synchronization ensures that only one thread can access a static
synchronized method or block at a time, even if multiple threads are running.
• When there are more objects of a class, It acquires only the lock of the particular instance. To maintain the
Synchronized behavior, we need a class-level lock rather than an instance-level lock which can be
achieved by Static Synchronization.
• Static Synchronized method is also a method of synchronizing a method in Java such that no two threads
can act simultaneously static upon the synchronized method. The only difference is by using Static
Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.
The Thread will acquire a class-level lock of a Java class, such that only one thread can act on the static
synchronized method.
Real life Applications of Multithreading and Synchronisation in java
Scenario1: Ticket Booking System In this example, we have a shared resource, available tickets, and multiple
users (threads) attempting to book tickets concurrently. Synchronization ensures that no two threads book the same ticket
simultaneously.
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.
java.lang: Contains language support classes(e.g classes which defines primitive data types, math operations). This
package is automatically imported.
java.io: Contains classes for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date /
Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of the package). Then create
the MyClass.java inside the directory with the first statement being the package names.and compile it
Then create new program PrintName.java in other directory and calls the package in the program
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Why Use User-Defined Packages in These Applications?
:
1.Organized Structure
Class: Addition.java
package mathoperations;