KEMBAR78
Unit3 Java | PDF | Class (Computer Programming) | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
12 views44 pages

Unit3 Java

Uploaded by

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

Unit3 Java

Uploaded by

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

Unit-3

Exception
An Exception is a run time error, which occurs during the execution of a program, that disrupts
the normal flow of the program's instructions.

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.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling.

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.

Types of Exception
There are two types of exceptions
1.Checked Exception
2.Un-Checked Exception
1.Checked Exception
Checked Exceptions are the exception which checked at compile-time. These exceptions are
directly sub-class of java.lang.Exception class.

The following are a few built-in classes used to handle checked exceptions in java.
 IOException
 FileNotFoundException
 ClassNotFoundException

2.Un-Checked Exception
Un-Checked Exceptions are the exception both identifies or raised at run time. These exceptions
are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.

The following are a few built-in classes used to handle unchecked exceptions in java:
 ArithmeticException: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
 ArrayIndexOutOfBounds Exception: It is thrown to indicate that 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.
 NullPointerException: This exception is raised when referring to the members of a null
object. Null represents nothing
 NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
 StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that
an index is either negative than the size of the string.

Exception Models in Java


In java, there are two exception models. Java programming language has two models of exception
handling. The exception models that java suports 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.

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 util the result is satisfactory.

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");
}
}
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".

Exception Hierarchy
The exception hierarchy in many programming languages typically follows a structure where more
specific exceptions inherit from more general ones. For example, in Java:
• Throwable
• Error
• Exception
• RuntimeException
• ArithmeticException
• NullPointerException
• IOException
• FileNotFoundException

This hierarchy allows for more specific handling of different types of exceptions
1. Throwable:
• Throwable is the superclass for all exceptions and errors in Java. Both exceptions
and errors inherit from this class.
2. Error:
• Errors represent serious, often unrecoverable issues that typically result from
problems external to the program. Examples include OutOfMemoryError or
StackOverflowError. These are not meant to be caught or handled by regular
application code because they usually indicate a severe problem that should be
addressed at the system level.
3. Exception:
• Exceptions are conditions that a program should catch and handle. They are meant
to indicate exceptional conditions that a well-behaved application should anticipate
and recover from. Exception itself is further divided into two main subclasses:
RuntimeException and IOException, among others.
4. RuntimeException:
• RuntimeException is a subclass of Exception and represents exceptions that can
occur during the normal operation of the Java Virtual Machine. These exceptions
are considered to be unchecked exceptions because they are not explicitly checked
at compile time. Programmers are not required to catch or declare them explicitly,
but they can still be caught and handled if desired.
• Examples of RuntimeException include:
• ArithmeticException: Thrown when an arithmetic operation exceeds the
limits of the data type, such as division by zero.
• NullPointerException: Thrown when attempting to access an object
reference that is null.
• ArrayIndexOutOfBoundsException: Thrown when attempting to access
an array with an index that is outside its bounds.
5. IOException:
• IOException is a subclass of Exception and represents input/output exceptions that
may occur during the execution of a program. These exceptions are checked at
compile time, meaning that the programmer is required to either catch them or
declare that the method throws these exceptions.
• Examples of IOException include:
• FileNotFoundException: Thrown when attempting to access a file that
cannot be found.
• IOException itself is a more general class for handling various input/output-
related issues.
The hierarchy allows for organized and structured handling of exceptions. By catching more
specific exceptions, developers can tailor their error-handling strategies to the specific issues that
might occur during program execution. This improves the robustness and reliability of the code by
allowing it to gracefully handle unexpected situations.

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
}
finally
{
// statements which will execute compulsory
}

Example(try&catch)
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");
}
}
}
Output:
Denominator should not be zero

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 keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not checking
the code before it being used.
Only checked exceptions are required to be thrown using the throws keyword. Unchecked
exceptions don’t need to be thrown or handled explicitly in code.

Syntax of Java throws

return_type method_name() throws exception_class_name{


//method code
}

Advantage of Java throws keyword


Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws Example
Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.

import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

There are two cases:

Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.

Case 2: We have declared the exception i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether exception occurs during
the program or not.

import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

Case 2: Declare Exception

•In case we declare the exception, if exception does not occur, the code will be executed
fine.

•In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java

import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:

device operation performed


normal flow..

B) If exception occurs
importjava.io.*;

class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:
Exception in thread "main" java.io.IOException: device error
at M.method(Testthrows4.java:4)
at Testthrows4.main(Testthrows4.java:10)

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

Java’s Built-in Exceptions:


Inside the standard package java.lang, Java defines several exception classes.
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..
.
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.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append more
characters after its definition, but it can be modified.
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);

The String class defined in the package java.lang package.


The String class implements Serializable, Comparable, and CharSequence interfaces.
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.
String siteName = "btechsmartclass.com";
siteName = "www.btechsmartclass.com";
Creating String object in java
In java, we can use the following two ways to create a string object.
•Using string literal
•Using String constructor
String title = "Java Tutorials"; // Using literals

String siteName = new String("www.btechsmartclass.com"); // Using constructor


String handling methods
In java programming language, the String class contails various methods that can be used to handle
string data values. It containg methods like concat( ), compareTo( ), split( ), join( ), replace( ),
trim( ), length( ), intern( ), equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.

Method Description Return Value

charAt(int) Finds the character at given index char


length() Finds the length of given string int
Method Description Return Value

compareTo(String) Compares two strings int


compareToIgnoreCase(String)Compares two strings, ignoring case int
concat(String) Concatenates the object string with argument string. String
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
Checks whether a string starts with the specified
startsWith(String) boolean
string
Checks whether a string ends with the specified
endsWith(String) boolean
string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
Finds the first index of argument string in object
indexOf(String) int
string
Finds the last index of argument string in object
lastIndexOf(String) int
string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
Replaces the first string with second string at all
replaceAll(String, String) String
occurrences.
Extracts a sub-string from specified start and end
substring(int, int) String
index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String

public class JavaStringExample {

public static void main(String[] args) {


String title = "Java Tutorials";
String siteName = "www.btechsmartclass.com";
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("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}

Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously. The aim of
multithreading is to achieve the concurrent execution.

What is Thread?
A thread is a light weight subprocess, a smallest unit of processing.
A thread is a subpart of a process that can run individually.

As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.
Note:At a time only one thread is executed.
Comparing Multitasking and Multithreading
Factors Multi-tasking Multi-threading
In multithreading, the CPU creates and
In multitasking, the CPU executes
Fundamentals processes multiple threads from a
multiple tasks simultaneously.
single task concurrently.
In multithreading, a CPU divides a
With multitasking, a user can
program into multiple threads to work
Operation perform multiple tasks
more efficiently, thereby enhancing
simultaneously on their CPU.
computer power.
In multitasking, the system In multithreading, the system allocates
Resources and allocates separate resources and a single memory to a process, and the
Memory memory to different programs threads derived from it share the same
running simultaneously. resources and memory.
The CPU constantly switches In multithreading, the CPU constantly
Switching between different programs in switches between threads, not
multitasking. programs.
Multitasking involves Multithreading does not involve
Multiprocessing multiprocessing among various multiprocessing among its
components. components.
Execution Execution in multitasking is Execution in multithreading is
Speed relatively slower. significantly faster.
Process The termination of a process in The termination of a process in
Termination multitasking takes more time. multithreading takes less time.

What is Main Thread?


We create Main Method in each and every Java Program, which acts as an entry point for the code
to get executed by JVM, Similarly in this Multithreading Concept, Each Program has one Main
Thread which was provided by default by JVM, hence whenever a program is being created in
java, JVM provides the Main Thread for its Execution.
We can create Threads in java using two ways, namely :
1.Extending Thread Class
2.Implementing a Runnable interface
1. By Extending Thread Class
We can run Threads in Java by using Thread Class, which provides constructors and methods for
creating and performing operations on a Thread, which extends a Thread class that can implement
Runnable Interface. We use the following constructors for creating the Thread:
•Thread
•Thread(Runnable r)
•Thread(String name)
•Thread(Runnable r, String name)
Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void suspend(): is used to suspend the thread(depricated).
15. public void resume(): is used to resume the suspended thread(depricated).
16. public void stop(): is used to stop the thread(depricated).

Example: By extending Thread class


class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...

2.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:
start() method of Thread class is used to start a newly created thread. It performs 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: By implementing the Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Output:
thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your class
that implements Runnable so that your class run() method may execute.

Thread Priorities
 Each thread have a 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).
 But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses.

Three constants defiend in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int 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.

Example of priority of a Thread:


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
Synchronization is the capability of control the access of multiple threads to any shared resource.
Synchronization is better in case we want only one thread can access the shared resource at a time.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronizations.
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

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

Java synchronized method


 If you declare any method as synchronized, it is known as synchronized method.
 Synchronized method is used to lock an object for any shared resource.
 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:
class Table
{
synchronized 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
10
15
20
25
100
200
300
400
500

Synchronized Block in Java


 Synchronized block can be used to perform synchronization on any specific resource of
the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
 Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 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

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.

Method Description
public final void wait()throws
It waits until object is notified.
InterruptedException
c
l
a
s
s
public final void wait(long It waits for the specified amount
M timeout)throws InterruptedException of time.
y
T
h 2) notify() method
r
e The notify() method wakes up a single thread that is waiting on this object's
a
d 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
i implementation.
m
p Syntax:
l
e public final void notify()
m
e
n 3) notifyAll() method
t
s Wakes up all threads that are waiting on this object's monitor.

R Syntax:
u
n public final void notifyAll()
n
a Difference between wait and sleep
b
l Let's see the important differences between wait and sleep methods.
e
{ wait() sleep()

i The wait() method releases the lock. The sleep() method doesn't release the lock.
n
t It is a method of Object class It is a method of Thread class

t It is the non-static method It is the static method


o
t It should be notified by notify() or After the specified amount of time, sleep is
a notifyAll() methods completed.
l
; Example of Inter Thread Communication
p
u class MyThread implements Runnable {
b int total;
l
i public void run() {
c synchronized(this) {
v for (int i = 1; i <= 10; i++)
o total += 100;
i
this.notify ();
d
} }
r
u
n

(
}
public class InnerThreadDemo {
public static void main (String []args)throws InterruptedException {
MyThread mt = new MyThread ();
Thread t = new Thread (mt);
t.start();
synchronized (mt) {
mt.wait();
System.out.println ("Total Earnings:" + mt.total);
}
} }
Output:
Main Thread total:1000

ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such
a way, we can suspend, resume or interrupt a group of threads by a single method
call.

A ThreadGroup represents a set of threads. A thread group can also include the
other thread group. The thread group creates a tree in which every thread group
except the initial thread group has a parent.

A thread is allowed to access information about its own thread group, but it cannot
access the information about its thread group's parent thread group or any other
thread groups.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.

No. Constructor Description


1) ThreadGroup(String name) creates a thread group with given name.

ThreadGroup(ThreadGroup parent, creates a thread group with a given


2)
String name) parent group and name.

Methods of ThreadGroup class


There are many methods in ThreadGroup class. A list of ThreadGroup methods is
given below.
Modifier and
S.N. Method Description
Type
This method determines if the currently
1) void checkAccess() running thread has permission to modify the
thread group.
This method returns an estimate of the
2) int activeCount() number of active threads in the thread
group and its subgroups.
This method returns an estimate of the
3) int activeGroupCount() number of active groups in the thread group
and its subgroups.
This method destroys the thread group and
4) void destroy()
all of its subgroups.
This method copies into the specified array
5) int enumerate(Thread[] list) every active thread in the thread group and
its subgroups.
This method returns the maximum priority
6) int getMaxPriority()
of the thread group.
This method returns the name of the thread
7) String getName()
group.
This method returns the parent of the thread
8) ThreadGroupgetParent()
group.
This method interrupts all threads in the
9) void interrupt()
thread group.
This method tests if the thread group is a
10) boolean isDaemon()
daemon thread group.
This method changes the daemon status of
11) void setDaemon(boolean daemon)
the thread group.
This method tests if this thread group has
12) boolean isDestroyed()
been destroyed.
This method prints information about the
13) void list()
thread group to the standard output.
This method tests if the thread group is
14) boolean parentOf(ThreadGroup g) either the thread group argument or one of
its ancestor thread groups.
This method is used to suspend all threads
15) void suspend()
in the thread group.
This method is used to resume all threads in
16) void resume() the thread group which was suspended using
suspend() method.
This method sets the maximum priority of
17) void setMaxPriority(int pri)
the group.
This method is used to stop all threads in
18) void stop()
the thread group.
This method returns a string representation
19) String toString()
of the Thread group.
Let's see a code to group multiple threads.

ThreadGroup tg1 = new ThreadGroup("Group A");

Thread t1 = new Thread(tg1,new MyRunnable(),"one");

Thread t2 = new Thread(tg1,new MyRunnable(),"two");


Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name,
MyRunnable is the class that implements Runnable interface and "one", "two" and
"three" are the thread names.

Now we can interrupt all threads by a single line of code only.

Thread.currentThread().getThreadGroup().interrupt();

ThreadGroup Example
public class ThreadGroupDemo implements Runnable{

public void run() {

System.out.println(Thread.currentThread().getName());

public static void main(String[] args) {

ThreadGroupDemo runnable = new ThreadGroupDemo();

ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");

t1.start();

Thread t2 = new Thread(tg1, runnable,"two");

t2.start();

Thread t3 = new Thread(tg1, runnable,"three");

t3.start();

System.out.println("Thread Group Name: "+tg1.getName());

tg1.list();

} }

Output:

one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Let's look at an example problem of producer and consumer.
 The producer produces the item and the consumer consumes the same.
 But here, the consumer cannot consume until the producer produces the item, and producer
cannot produce until the consumer consumes the item that already been produced.
 So here, the consumer has to wait until the producer produces the item, and the producer also
needs to wait until the consumer consumes the same.
 Here we use the inter-thread communication to implement the producer and consumer
problem.

Example
class ItemQueue
{
int item;
boolean valueSet = false;
synchronized int getItem()
{
while (!valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
return item;
}
synchronized void putItem(int item)
{
while (valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
}
}
class Producer implements Runnable
{
ItemQueue itemQueue;
Producer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true)
{
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable
{
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
itemQueue.getItem();
}
}
}
class ProducerConsumer
{
public static void main(String args[])
{
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}

Output:
Produced: 0
Consummed:0
Produced: 1
Consummed:1
Produced: 2
Consummed:2
Produced: 3
Consummed:3
Produced: 4
Consummed:4
Produced: 5
Consummed:5
Produced: 6
Consummed:6
Produced: 7
Consummed:7
Produced: 8
Consummed:8

Daemon Thread
Daemon thread in Java is a service provider thread that provides services to the
user thread. Its life depend on the mercy of user threads i.e. when all the user
threads dies, JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

Points to remember for Daemon Thread in Java


• It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.

• Its life depends on user threads.

• It is a low priority thread.

Methods for Java Daemon thread by Thread class

The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description


public void is used to mark the current thread as daemon
1)
setDaemon(boolean status) thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.

public class TestDaemonThread1 extends Thread{


public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
} }
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread

t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:

daemon thread work


user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException

Annotations in Java
Annotations are used to provide supplemental information about a program.

•Annotations start with ‘@’.

•Annotations do not change the action of a compiled program.

•Annotations help to associate metadata (information) to the program elements

i.e. instance variables, constructors, methods, classes, etc.


•Annotations are not pure comments as they can change the way a program is

treated by the compiler.


•Annotations basically are used to provide additional information, so could be an

alternative to XML and Java marker interfaces.

Note: This program throws compiler error because we have mentioned override, but
not overridden, we have overloaded display
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[]) {

Derived obj = new Derived();

obj.display();

}}

Output:

10: error: method does not override or implement a method from a supertype
If we remove parameter (int x) or we remove @override, the program compiles fine.

Categories of Annotations
There are broadly 5 categories of annotations as listed:

1.Marker Annotations
2.Single value Annotations
3.Full Annotations
4.Type Annotations
5.Repeating Annotations
Category 1: Marker Annotations
The only purpose is to mark a declaration. These annotations contain no members
and do not consist of any data. Thus, its presence as an annotation is sufficient.
Since the marker interface contains no members, simply determining whether it is
present or absent is sufficient. @Override is an example of Marker Annotation.
Example
@TestAnnotation()
Category 2: Single value Annotations
These annotations contain only one member and allow a shorthand form of
specifying the value of the member. We only need to specify the value for that
member when the annotation is applied and don’t need to specify the name of the
member. However, in order to use this shorthand, the name of the member must be
a value.

@TestAnnotation(“testing”);
Category 3: Full Annotations
These annotations consist of multiple data members, names, values, pairs.

Example
@TestAnnotation(owner=”Rahul”, value=”Class Geeks”)
Category 4: Type Annotations
These annotations can be applied to any place where a type is being used. For
example, we can annotate the return type of a method. These are declared
annotated with @Target annotation.
Category 5: Repeating Annotations
These are the annotations that can be applied to a single item more than once. For
an annotation to be repeatable it must be annotated with the @Repeatable
annotation, which is defined in the java.lang.annotation package. Its value field
specifies the container type for the repeatable annotation. The container is specified
as an annotation whose value field is an array of the repeatable annotation type.
Hence, to create a repeatable annotation, firstly the container annotation is created,
and then the annotation type is specified as an argument to the @Repeatable
annotation.

ENUMERATION
In java, an Enumeration is a list of named constants. The enum concept was
introduced in Java SE 5 version.
The enum in Java programming the concept of enumeration is greatly expanded
with lot more new features
compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we
create an enum in java, it
converts into a class type. This concept enables the java enum to have constructors,
methods, and instance
variables.
All the constants of an enum are public, static, and final. As they are static, we can
access directly using
enum name.
The main objective of enum is to define our own data types in Java, and they are
said to be enumeration data
types.
Creating enum in Java
To create enum in Java, we use the keyword enum. The syntax for creating enum is
similar to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a
method.
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.FRIDAY;
System.out.println("Today is " + day);
System.out.println("\nAll WeekDays: ");
for(WeekDay d:WeekDay.values())
System.out.println(d);}
}

• Every enum is converted to a class that extends the built-in class Enum.
• Every constant of an enum is defined as an object.
• As an enum represents a class, it can have methods, constructors. It also gets
a few extra methods from the
Enum class, and one of them is the values() method.

Constructors enum
In a java programming language, an enum can have both the type of constructors
default and parameterized.
The execution of constructor depends on the constants we defined in the enum. For
every constant in an
enum, the constructor is executed.
If an enum has a parameterized constructor, the parameter value should be passed
when we define constant.
Example
enum WeekDay{
MONDAY,
TUESDAY,
SUNDAY("Holiday");
WEDNESSDAY,
THURSDAY,
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
FRIDAY,
SATURDAY,msg = str;
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day + " and its " + day.msg);
}
}

In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other
constants created by calling default constructor.

Methods enum
In a java programming language, an enum can have methods. These methods are
similar to the methods of a
class. All the methods defined in an enum can be used with all the constants
defined by the same enum.
Example
enum WeekDay{
MONDAY,
TUESDAY,
SUNDAY("Holiday");
WEDNESSDAY,
String msg;
WeekDay(){
System.out.println("Default constructor!");
THURSDAY,
FRIDAY,
SATURDAY,}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
void printMessage() {
System.out.println("Today is also " + msg);
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day);
day.printMessage();
}
}


• enum can not extend another enum and a class.
• enum can implement interfaces.
• enum does not allow to create an object of it.
• Every enum extends a built-in class Enum by default.

AUTOBOXING AND UNBOXING


All the primitive data types have defined using the class concept, these classes
known as wrapper classes.
In java, every primitive type has its corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
The Java 1.5 version introduced a concept that converts primitive type to
corresponding wrapper type and
reverses of it.
Autoboxing
The process of converting a primitive type value into its corresponding wrapper class
object is called
autoboxing or simply boxing. For example, converting an int value to an Integer
class object.
The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of
the corresponding wrapper class.
We can also perform autoboxing manually using the method valueOf( ), which is
provided by every wrapper
class.
Example - Autoboxing
import java.lang.*;
public class AutoBoxingExample {
public static void main(String[] args) {// Auto boxing : primitive to Wrapper
int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Auto un-boxing
The process of converting an object of a wrapper class type to a primitive type
value is called auto un-boxing
or simply unboxing. For example, converting an Integer object to an int value.
The compiler automatically performs the auto un-boxing when a wrapper class
object has assigned to
aprimitive type.
We can also perform auto un-boxing manually using the method intValue( ), which
is provided by Integer
wrapper class. Similarly every wrapper class has a method for auto un-boxing.
Example - Auto unboxing
import java.lang.*;
public class AutoUnboxingExample {
public static void main(String[] args) {
// Auto un-boxing : Wrapper to primitive
Integer num = 200;
int i = num;
int j = num.intValue();
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}

GENERICS
The java generics is a language feature that allows creating methods and class which
can handle any type of
data values. The generic programming is a way to write generalized programs, java
supports it by java
generics.
The java generics is similar to the templates in the C++ programming language.
• Most of the collection framework classes are generic classes.
• The java generics allows only non-primitive type, it does not support primitive
types like int, float, char, etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used
angular brackets “< >”.
In java, the generics feature implemented using the following.

• Generic Method
• Generic Classes
Generic methods
Generics allows creating generic methods which can work with a different type of
data values.
Using a generic method, we can create a single method that can be called with
arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler
handles each method call
appropriately.
Example - Generic method

public class GenericFunctions {


public <T, U> void displayData(T value1, U value2) {
System.out.println("(" + value1.getClass().getName() + ", " + value2.getClass().
GetName() + ")");
}
public static void main(String[] args) {
GenericFunctions obj = new GenericFunctions();
obj.displayData(45.6f, 10);
obj.displayData(10, 10);
obj.displayData("Hi", 'c');
}
}
In the above example code, the method displayData( ) is a generic method that
allows a different type of
parameter values for every function call.

Generic Class
A class can be defined as a generic class that allows creating a class that can work
with different types.
A generic class declaration looks like a non-generic class declaration, except that the
class name is followed by a type parameter section.
Example - Generic class
public class GenericsExample<T> {
T obj;
public GenericsExample(T anotherObj) {
this.obj = anotherObj;
}
public T getData() {
return this.obj;
}
public static void main(String[] args) {
GenericsExample<Integer> actualObj1 = new GenericsExample<Integer>(100);
System.out.println(actualObj1.getData());
GenericsExample<String> actualObj2 = new GenericsExample<String>("Java");
System.out.println(actualObj2.getData());
GenericsExample<Float> actualObj3 = new GenericsExample<Float>(25.9f);
System.out.println(actualObj3.getData());
}
}

You might also like