Java Unit-III Notes
Java Unit-III Notes
Exception handling and Multithreading - Concepts of exception handling, benefits of exception handling,
Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws and finally,
built in exceptions, creating own exception subclasses. String handling, Exploring java.util. Differences
between multithreading and multitasking, thread life cycle, creating threads, thread priorities,
synchronizing threads, inter thread communication, thread groups, daemon threads. Enumerations,
autoboxing, annotations, generics.
CONCEPTS OF EXCEPTION HANDLING
EXCEPTION
An Exception is a run time error, which occurs during the execution of a program, that distrupts the
normal flow of the program's instructions.
It is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run
time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object.
This object is called the exception object.
It contains information about the exception, such as the name and description of the exception and
the state of the program when the exception occurred.
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
EXCEPTION HANDLING IN JAVA
The Exception Handling in Java is one of the powerful feature to handle the runtime errors so that
normal flow of the application can be maintained.
Exception Handling is used to convert system error message into user friendly error message.
Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //Exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the
rest of the code will not be executed i.e. statement 6 to 10 will not be executed.
If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
UNCAUGHT EXCEPTIONS(WITH OUT USING TRY & CATCH)
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
int c=a/b;
System.out.println("Denominator should not be zero");
}
}
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:7)
Explanation:
Abnormally terminate program and give a message like below,
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:7)
This error message is not understandable by user so we convert this error message into user
friendly error message, like "denominator should not be zero".
BENEFITS OF EXCEPTIONHANDLING
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
TERMINATION OR RESUMPTIVE MODELS
In java, there are two exception models. Java programming language has two models of exception
handling. The exception models that java supports are as follows.
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the type
of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model.
In resumptive model, the exception handler is expected to do something to stable the situation, and
then the faulting method is retried.
In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior.
We may also place the try block in a while loop that keeps re-entering the try block until the result
is satisfactory.
EXCEPTION HIERARCHY
HOW TO HANDLE THE EXCEPTION
Use Five keywords for Handling the Exception
1. try
2. catch
3. throw
4. throws
5. finally
1. try block
The try block contains set of statements where an exception can occur.
In other words try block always contains problematic statements.
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
try
{
//statements that may cause an exception
}
2. catch block
A catch block is where we handle the exceptions, this block must follow the try block.
A single try block can have multiple catch blocks associated with it. We 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.
For example if an arithmetic exception occurs in try block then the statements enclosed in catch
block for arithmetic exception executes.
Syntax of try-catch in java
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
Example1: ArithmeticException
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
}
catch (ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
}
}
Example2: NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
Output: NullPointerException..
Example3: FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
try
{ // Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch(FileNotFoundException e)
{
System.out.println("File does not exist");
}
}
}
Output: File does not exist
MULTIPLE CATCH BLOCKS
We can write multiple catch blocks for generating multiple user friendly error messages to make our
application strong.
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
System.out.println("Result: "+c);
}
catch(NullPointerException e)
{
System.out.println("Enter valid number");
}
catch(ArithmeticException e)
{
System.out.println("Denominator not be zero");
}
}
}
NESTED TRY STATEMENTS
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
…………
}
}
catch(Exception e)
{
………..
}
Example
class NestedTry
{
public static void main(String args[])
{
try
{
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
3. 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
throw Instance
Example
throw new ArithmeticException("/ by zero");
Example
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output: Caught inside fun().
Caught in main.
4. throws
throws is a keyword in java language which is used to throw the exception which is raised in the called
method to it's calling method throws keyword always followed by method signature.
Syntax
returnType methodName(parameter) throws Exception_class....
{
.....
}
Example
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
Output:
Inside fun().
caught in main.
5.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.
Example
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
RE-THROWING EXCEPTIONS
Sometimes we may need to rethrow an exception in Java.
If a catch block cannot handle the particular exception it has caught, we can rethrow the exception.
The rethrow expression causes the originally thrown object to be rethrown.
Because the exception has already been caught at the scope in which the rethrow expression occurs,
it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by catch blocks at
the scope in which the rethrow expression occurred.
Any catch blocks for the enclosing try block have an opportunity to catch the exception.
Example
class RethrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output:
Caught inside fun().
Caught in main.
CREATING OWN EXCEPTION(CUSTOM EXCEPTION IN JAVA)
If any exception is design by the user known as user defined or Custom Exception. Custom Exception is
created by user.
Rules to design user defined Exception
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class constructor.
6. Save the program with public class name.java
Example
package nage;
public class InvalidAgeException extends Exception
{
public InvalidAgeException (String s)
{
super(s);
}
}
A Class that uses above InvalidAgeException:
class CustomException
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...
BUILT IN EXCEPTIONS
The Java programming language has several built-in exception class that support exception handling.
Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
EXCEPTION TYPES IN JAVA
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not handled,
the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
List of checked exceptions in Java
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but
that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class, but the specified class object cannot be instantiated because it is an
interface or is an abstract class.
5 InterruptedException
S. No. Exception Class with Description
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use of
resources, etc.
In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
List of unchecked exceptions in Java
1 ArithmeticException
It handles the arithmetic exceptions like division by zero
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the
specified monitor.
S. No. Exception Class with Description
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the
state of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array
, vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but
the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.
STRING HANDLING
A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Example
String siteName = "javaprogramming";
siteName = "javaprogramminglanguage";
String handling methods
In java programming language, the String class contains various methods that can be used to handle
string data values.
The following table depicts all built-in methods of String class in java.
S.No Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
Replaces the first string with second string at all
replaceAll(String, String)
13 occurrences.
Extracts a sub-string from specified start and end index
substring(int, int)
14 values
15 toLowerCase() Converts a string to lower case letters
16 toUpperCase() Converts a string to upper case letters
17 trim() Removes whitespace from both ends
18 toString(int) Converts the value to a String object
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}
MULTI-TASKING AND MULTI-THREADING
Introduction
Multi-tasking and multi-threading are two techniques used in operating systems to manage multiple
processes and tasks.
Multi-tasking is the ability of an operating system to run multiple processes or tasks concurrently,
sharing the same processor and other resources.
In multi-tasking, the operating system divides the CPU time between multiple tasks, allowing them
to execute simultaneously.
Each task is assigned a time slice, or a portion of CPU time, during which it can execute its code.
Multi-tasking is essential for increasing system efficiency, improving user productivity, and
achieving optimal resource utilization.
Multi-threading is a technique in which an operating system divides a single process into multiple
threads, each of which can execute concurrently.
Threads share the same memory space and resources of the parent process, allowing them to
communicate and synchronize data easily.
Multi-threading is useful for improving application performance by allowing different parts of the
application to execute simultaneously.
DIFFERENCE BETWEEN MULTI-TASKING AND MULTI-THREADING
t2.start();
t3.start();
}
}
THREAD PRIORITIES
In a java programming language, every thread has a property called priority.
Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules
the threads according to their priority (known as preemptive scheduling).
The thread with more priority allocates the processor first.
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Three constants defined in Thread class:
1. MIN_PRIORITY
2. NORM_PRIORITY
3. MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread.
It takes an integer range from 1 to 10 as an argument and returns nothing (void).
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread.
It does not takes any argument and returns name of the thread as String.
Example
String threadName = threadObject.getPriority();
Example1
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("CurrentThread: " + Thread.currentThread().getName());
}
}
public class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}
}
Output:
Inside SampleThread
Inside SampleThread
CurrentThread: second
CurrentThread: first
Example2
class MultiThread 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[])
{
MultiThread m1=new MultiThread ();
MultiThread m2=new MultiThread ();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
SYNCHRONIZING THREADS
SYNCHRONIZATION
The java programming language supports multithreading.
The problem of shared resources occurs when two or more threads get execute at the same time.
In such a situation, we need some way to ensure that the shared resource will be accessed by only
one thread at a time, and this is performed by using the concept called synchronization.
The synchronization is the process of allowing only one thread to access a shared resource
at a time.
UNDERSTANDING THE PROBLEM WITHOUT SYNCHRONIZATION
In this example, there is no synchronization, so output is inconsistent.
Example:
class Table
{
void printTable(int n)
{
//method not synchronized
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);
}
}
class TestSynchronization
{
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();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
Thread Synchronization
In java, the synchronization is achieved using the following concepts.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by two ways in java:
1. by synchronized method
2. by synchronized block
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
When a method created using a synchronized keyword, it allows only one object to access it at a
time.
When an object calls a synchronized method, it put a lock on that method so that other objects or
thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads will
be allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example:
class Table
{
synchronized void printTable(int n)
{
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
class MyThread1 extends Thread
{
Table table = new Table();
int number;
MyThread1(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run()
{
table.printTable(number);
}
}
class MyThread2 extends Thread
{
Table table = new Table();
int number;
MyThread2(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run()
{
table.printTable(number);
}
}
class ThreadSynchronizationExample
{
public static void main(String[] args)
{
Table table = new Table();
MyThread1 thread1 = new MyThread1(table, 5);
MyThread2 thread2 = new MyThread2(table, 10);
thread1.start();
thread2.start();
}
}
Output:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Synchronized Block in Java
The synchronized block is used when we want to synchronize only a specific sequence of lines in a
method.
For example, let's consider a method with 20 lines of code where we want to synchronize only a
sequence of 5 lines code, we use the synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression)
{
//code block
}
Example of synchronized block
class Table
{
void printTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}//end of the method
}
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 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();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
INTERTHREAD COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to solve the
problem of polling.
In java, polling is the situation to check some condition repeatedly, to take appropriate action, once
the condition is true.
That means, in inter-thread communication, a thread waits until a condition becomes true such that
other threads can execute its task.
The inter-thread communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
1 public void setDaemon(boolean status) is used to mark the current thread as daemon
thread or user thread.
class TestAnnotation1
{
public static void main(String args[])
{
Animal a=new Dog();
a.eatSomething();
}
}
Output: Comple Time Error
@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.
Example
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();
}
}
Output
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
At Runtime:
hello n
JAVA GENERICS
Java Generics allows us to create a single class, interface, and method that can be used with different
types of data (objects).
This helps us to reuse our code.
Note: Generics does not work with primitive types (int, float, char, etc).