SlideShare a Scribd company logo
Course Name Advanced Java Programming
Course Code 21UCSC51
Unit: I Classes and Interfaces
Classes and Interfaces: Introduction –Interfaces – marker Interfaces –Functional interfaces, default
and static methods – Abstract classes – Immutable classes – Anonymous classes – Visibility –
Inheritance and Multiple Inheritance – Encapsulation – Final classes and methods.
Unit: II Methods and General Programming Guidelines
Methods: Method Signatures – Methods body – Method overloading and overriding – Inlining –
Recursion – Method References – Immutability
Unit: III Exceptions & Thread and Thread Groups
Exceptions: Exceptions and when to use – Checked and unchecked exceptions – using try –with-
resources – Exceptions and lambdas – Standard Java exceptions .Threads and Thread Groups –
Concurrency, synchronization and Immutability
Unit: IV Dynamics Language Support and API
Dynamics languages support: Dynamic Languages Support – Scripting API - JavaScript on JVM –
Groovy on JVM – Ruby on JVM – Python on JVM – Using Scripting API.
Unit: V Java Annotation Processors and Java Agent Basics
Java Compiler API: Java Compiler API – Annotation Processors – Element Scanners – Java Compiler
Tree API.
___________________________________________________________________
Unit 1
1.1 Interface
1.2 Default Methods and Static Methods
1.3 Marker Interface
1.4 Functional Interface
1.5 Inheritance and Multiple Inheritance
_____________________________________________________________________________________
1.1 Interface in Java
Introduction
 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 Interfaces can have abstract methods and variables. It cannot have a method definition.
 Java Interface also represents the IS-A relationship.
 It cannot be instantiated just like the abstract class.
 We can have default and static methods in an interface.
Reasons to Use Interface
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
Declaring An Interface
 An interface is declared by using the interface keyword.
 It provides total abstraction; means all the methods in an interface are declared without any
definition, and all the fields are public, static and final by default.
 A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
}
Internal addition by the compiler
Interface fields are public, static and final by default, and the methods are public and abstract.
Relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in the
A6 class.
interface printable{
void print();
}
class A6 implements printable
{
public void print(){System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{ System.out.println("Hello"); }
public void show()
{ System.out.println("Welcome"); }
class TestInterface
{
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
1.2 Default Methods and Static Methods
Default Methods
Java provides a facility to create default methods inside the interface. Methods which are defined inside
the interface and tagged with default are known as default methods. These methods are non-abstract
methods.
Example :
interface Drawable
{
void draw();
default void msg()
{ System.out.println("default method"); }
}
class Rectangle implements Drawable
{
public void draw()
{ System.out.println("drawing rectangle"); }
}
class TestInterfaceDefault
{
public static void main(String args[])
{
Drawable d=new Rectangle();
d.draw();
d.msg();
}
}
Output:
drawing rectangle
default method
Static Methods
A static method is a method that belongs to a class rather than an instance of a class. This means you
can call a static method without creating an object of the class. Since Java 8, we can have static method
in interface.
Example:
interface Drawable
{
void draw();
static int cube(int x)
{ return x*x*x; }
}
class Rectangle implements Drawable
{
public void draw()
{ System.out.println("drawing rectangle"); }
}
class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}
}
Output:
drawing rectangle
27
1.3 Marker Interface
Introduction
 An interface that does not contain methods, fields, and constants is known as marker
interface.
 In other words, an empty interface is known as marker interface or tag interface.
 It delivers the run-time type information about an object.
 It is the reason that the JVM and compiler have additional information about an object.
 The Serializable and Cloneable interfaces are the example of marker interface.
Example:
public interface Serializable
{
}
Uses of Marker Interface
 Marker interface is used as a tag that informs the Java compiler by a message so that it can
add some special behavior to the class implementing it.
 It is used to logically divide the code and a good way to categorize code.
 It is more useful for developing API.
Built-in Marker Interface
In Java, built-in marker interfaces are the interfaces that are already present in the JDK and ready to use.
There are many built-in marker interfaces some of them are:
 Cloneable Interface
 Serializable Interface
 Remote Interface
i) Cloneable Interface
Cloneable interface in Java is also a marker interface that belong to java.lang package. It generates a
replica (copy) of an object with a different name. We can implement the interface in the class of which
class, object to be cloned.
ii) Serializable Interface
It is a marker interface in Java that is defined in the java.io package. If we want to make the class
serializable, we must implement the Serializable interface.
Serialization is a mechanism in which object state is read from the memory and written into a file or
database. Deserialization means that object state reading from a file or database and written back into
memory.
iii) Remote Interface
Remote interface is a marker interface that belong to java.rmi package. It marks an object as remote
that can be accessed from another machine (host). We must implement the Remote interface if we
want to make an object as remote.
Custom Marker Interface
Apart from built-in marker interface, Java also allows us to create our own marker interface.
Example:
interface Car
{
96
}
interface Engine
{
}
//class that implements the Car marker interface
class Vehicle implements Car
{
static void isVehicle()
{
System.out.println("Car is a vehicle.");
}
}
//class that implements the Engine marker interface
class Status implements Engine
{
static void isWorking()
{
System.out.println("Yes, engine is working.");
}
}
//main class
public class Program
{
public static void main(String args[])
{
//invoking the methods of the class
Vehicle.isVehicle();
Status.isWorking();
}
}
Output:
Car is a vehicle.
Yes, engine is working.
1.4 Functional Interfaces in Java
Introduction
 A functional interface is an interface that contains only one abstract method.
 They can have only one functionality to exhibit.
 From Java 8 onwards, lambda expressions can be used to represent the instance of a functional
interface.
 A functional interface can have any number of default methods.
 Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
 Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short,
they are also known as SAM interfaces.
 Functional interfaces are included in Java SE 8 with Lambda expressions and Method references
in order to make code more readable, clean, and straightforward.
Java Program to demonstrate functional interface
interface inter1{
void display(String msg);
}
public class C1 implements inter1
{
public void display(String msg)
{
System.out.println(msg);
}
public static void main(String[] args)
{
C1 C = new C1();
C.display("Hello there");
}
}
Output
New thread created
Functional interface using lambda expressions
interface FuncInterface
{
void abstractFun(int x);
default void normalFun()
{
System.out.println("Hello");
}
}
class Program
{
public static void main(String args[])
{
FuncInterface fobj = (int x)->System.out.println(2*x);
fobj.abstractFun(5);
}
}
Output
10
1.5 Inheritance in Java
Introduction
● Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
● It is an important part of Object Oriented programming system.
● The idea behind inheritance in Java is that we can create new classes that are built upon existing
classes.
● When we inherit from an existing class, we can reuse methods and fields of the parent class.
● Moreover, we can add new methods and fields in our current class also.
● Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
 For Method Overriding
 For Code Reusability.
Terms used in Inheritance
 Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Types of Inheritance
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
Example
class A
{
int a, b;
void display()
{
System.out.println(“a=”+a);
System.out.println(“b=”+b);
}
}
class B extends A
{
int c;
void show()
{
System.out.println(“c = ”+c); }
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10;
obj.b=20;
obj.c=30;
obj.display();
obj.show();
}
}
Output:
barking...
eating...
Multiple Inheritance
When the child class extends from more than one superclass, it is known as multiple inheritance.
However, Java does not support multiple inheritance.
To achieve multiple inheritance in Java, we must use the interface.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{ System.out.println("Hello"); }
public void show()
{ System.out.println("Welcome"); }
class TestInterface
{
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
__________________________________________________________________
Unit 2
2.1 Methods in Java
2.2 Method Overloading
2.3 Method Overriding
2.4 Recursion
2.5 Java Method References
___________________________________________________________________
2.1 Methods in Java
 A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
 It is used to achieve the reusability of code.
 We write a method once and use it many times.
 We need not require to write code again and again.
 It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
 The method is executed only when we call or invoke it.
Method Declaration
The method declaration provides information about method attributes, such as access specifier, return-
type, name, and parameters.
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:
 Public: The method is accessible by all classes when we use public specifier in our
application.
 Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
 Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction
of two numbers, the method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Defining Methods: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Types of Methods in Java
There are two types of methods in Java:
1. Predefined Method
● In Java, predefined methods are the method that is already defined in the Java class
libraries.
● It is also known as the standard library method or built-in method.
● We can directly use these methods just by calling them in the program at any point.
2. User-defined Method
● The method written by the user or programmer is known as a user-defined method.
● These methods are modified according to the requirement.
Example:
import java.io.*;
class Addition
{
int sum = 0;
public int sum(int a, int b)
{
sum = a + b;
return sum;
}
}
class sample
{
public static void main(String[] args)
{
Addition add = new Addition();
int s = add.sum(1, 2);
System.out.println("Sum of two integer values :" + s);
}
}
Output
Sum of two integer values :3
2.2 Method Overloading
Introduction
If a class has multiple methods having the same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having the same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters
then it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.
Advantages of Method Overloading
 Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods. The first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create an instance for calling
methods.
class Adder
{
static int add(int a,int b)
{ return a+b; }
static int add(int a,int b,int c)
{ return a+b+c; }
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differ in data type. The first add method receives
two integer arguments and the second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
2.3 Method Overriding
Introduction
 If a subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
 In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent classes, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Example of Method Overriding
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.
class Vehicle
{
void run()
{ System.out.println("Vehicle is running"); }
}
class Bike2 extends Vehicle
{
void run()
{ System.out.println("Bike is running safely"); }
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
Output:
Bike is running safely
2.4 Recursion
Introduction
 Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called a recursive method.
 It makes the code compact but complex to understand.
Advantages
 Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but
doesn't necessarily reduce space requirements or speed of execution).
 Reduces time complexity.
 Performs better in solving problems based on tree structures.
Syntax:
returntype methodname()
{
methodname();
}
Working of Recursion
 The idea is to represent a problem in terms of one or more smaller sub-problems and add base
conditions that stop the recursion.
 For example, we compute factorial n if we know the factorial of (n-1). The base case for factorial
would be n = 0. We return 1 when n = 0.
How is memory allocated to different function calls in recursion?
 When any function is called from main(), the memory is allocated to it on the stack.
 A recursive function calls itself, the memory for the called function is allocated on top of
memory allocated to the calling function and a different copy of local variables is created for
each function call.
 When the base case is reached, the function returns its value to the function by whom it is
called and memory is de-allocated and the process continues.
Example
public class RecursionExample3
{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args)
{
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output:
Factorial of 5 is: 120
2.5 Java Method References
Java provides a new feature called method reference in Java 8. Method reference is used to refer to a
method of functional interface. It is a compact and easy form of lambda expression. Each time when you
are using lambda expression to just refer to a method, you can replace your lambda expression with
method reference.
Types of Method References
There are following types of method references in java:
1. Reference to a static method.
2. Reference to an instance method.
3. Reference to a constructor.
1) Reference to a Static Method
We can refer to the static method defined in the class. Following is the syntax and example which
describe the process of referring to static methods in Java.
Syntax
ContainingClass::staticMethodName
Example
In the following example, we have defined a functional interface and referring a static method to its
functional method say().
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
Sayable sayable = MethodReference::saySomething;
sayable.say();
}
}
Output:
Hello, this is static method.
2) Reference to an Instance Method
Like static methods, We can refer to instance methods also. In the following example, we are describing
the process of referring to the instance method.
Syntax
containingObject::instanceMethodName
Example
In the following example, we are referring to non-static methods. We can refer to methods by class
object and anonymous object.
interface Sayable{
void say();
}
public class InstanceMethodReference {
public void saySomething(){
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args) {
InstanceMethodReference methodReference = new InstanceMethodReference();
Sayable sayable = methodReference::saySomething;
Ssayable.say();
Sayable sayable2 = new InstanceMethodReference()::saySomething;
Sayable2.say();
}
}
Output:
Hello, this is non-static method.
Hello, this is non-static method.
3) Reference to a Constructor
We can refer to a constructor by using the new keyword. Here, we are referring constructor with the
help of functional interfaces.
Syntax
ClassName::new
Example
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:
Hello
_____________________________________________________________________________________
___________________________________________________________________
Unit 3
3.1. Exceptions - When to use them - Checked and unchecked exceptions
3.2 Using try-with-resources
3.3 Standard Java exceptions
3.4 Threads and Thread Groups
___________________________________________________________________
3.1. Exceptions - Checked and Unchecked Exceptions
Introduction
● Exception Handling in Java is one of the effective means to handle the runtime errors so that the
regular flow of the application can be preserved.
● Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
What is an Exception?
● Exception 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
Differences between Error and Exception:
 Error: An Error indicates a serious problem that a reasonable application should not try
to catch. Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, etc. Errors are usually
beyond the control of the programmer, and we should not try to handle errors.
 Exception: Exception indicates conditions that a reasonable application might try to
catch.
Types of Exceptions
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
A. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable
to explain certain error situations.
 Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
 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.
B. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases,
users can also create exceptions, which are called ‘user-defined Exceptions’.
Advantages of Exception Handling in Java:
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
Checked and unchecked exceptions
● Unchecked exceptions are used to signal about erroneous conditions related to program logic
and assumptions being made (invalid arguments, null pointers, unsupported operations, …).
● Any unchecked exception is a subclass of RuntimeException.
● Unchecked exceptions are not required to be caught by the caller.
● The NullPointerException is the most known member of unchecked exceptions and here is its
declaration from the Java standard library:
public class NullPointerException extends RuntimeException {
public NullPointerException() {
super();
}
public NullPointerException(String s) {
super(s);
}
}
● Checked exceptions represent invalid conditions in the areas which are outside of the
immediate control of the program (like memory, network, file system, …).
● Any checked exception is a subclass of Exception.
● Checked exceptions must be either caught by the caller.
● The IOException is, probably, the most known one among checked exceptions:
public class IOException extends Exception {
public IOException() {
super();
}
public IOException(String message) {
super(message);
}
public IOException(String message, Throwable cause) {
super(message, cause);
}
public IOException(Throwable cause) {
super(cause);
}
}
_____________________________________________________________________________________
3.2. Using try-with-resources
Introduction
● In Java, the Try-with-resources statement is a try statement that declares one or more resources
in it.
● A resource is an object that must be closed once your program is done using it.
● For example, a File resource or a Socket connection resource.
● The try-with-resources statement ensures that each resource is closed at the end of the
statement execution.
● If we don’t close the resources, it may constitute a resource leak and also the program could
exhaust the resources available to it.
● We can pass any object as a resource that implements java.lang.AutoCloseable, which includes
all objects which implement java.io.Closeable.
● By this, now we don’t need to add an extra finally block for just passing the closing statements
of the resources.
● The resources will be closed as soon as the try-catch block is executed.
Syntax: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
Exceptions:
● When it comes to exceptions, there is a difference in try-catch-finally block and try-with-
resources block.
● If an exception is thrown in both try block and finally block, the method returns the exception
thrown in finally block.
● For try-with-resources, if an exception is thrown in a try block and in a try-with-resources
statement, then the method returns the exception thrown in the try block.
● The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-
resources block throws suppressed exceptions.
Example : try-with-resources having a single resource
// Java Program for try-with-resources
// having single resource
import java.io.*;
class GFG {
public static void main(String[] args)
{
try (
FileOutputStream fos = new FileOutputStream("gfgtextfile.txt")) {
String text = "Hello World. This is my java program";
// Converting string to bytes
byte arr[] = text.getBytes();
fos.write(arr);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(
"Resource are closed and message has been written into the gfgtextfile.txt");
}
}
Output:
Resource are closed and message has been written into the gfgtextfile.txt
_____________________________________________________________________________________
3.3 Standard Java Exceptions
The Java standard library provides a plenty of exception classes which are designated to cover most of
the generic errors happening during program execution. The most widely used are presented in the
table below, please consider those before defining your own.
Exception Class Purpose
NullPointerException Attempts to use null in a case where an object is required.
IllegalArgumentException Method has been passed an illegal or inappropriate
argument.
IllegalStateException Method has been invoked at an illegal or inappropriate time.
IndexOutOfBoundsException Index of some sort (such as to an array, to a string, or to a
vector) is out of range.
UnsupportedOperationException Requested operation is not supported.
ArrayIndexOutOfBoundsException An array has been accessed with an illegal index.
ClassCastException Code has attempted to cast an object to a subclass of which
it is not an instance.
EnumConstantNotPresentException Attempt to access an enum constant by name and the enum
type contains no constant with the specified name (enums
have been on covered in the part 5 of the tutorial, How and
when to use Enums and Annotations).
NumberFormatException Attempts to convert a string to one of the numeric types, but
that the string does not have the appropriate format.
StringIndexOutOfBoundsException Index is either negative or greater than the size of the string.
IOException I/O exception of some sort has occurred. This class is the
general class of exceptions produced by failed or interrupted
I/O operations.
3.4 Threads and Thread Groups
Introduction
● The multiprocessor and multicore hardware architectures greatly influence the design and
execution model of applications which run on them nowadays.
● In order to utilize the full power of available computational units, the applications should be
ready to support multiple execution flows which are running concurrently and competing for
resources and memory.
Threads in Java
● Threads are the foundational building blocks of concurrent applications in Java.
● Threads are sometimes called lightweight processes and they allow multiple execution flows to
proceed concurrently.
● Every single application in Java has at least one thread called the main thread.
● Threads have a complex lifecycle and can be in one of the following states.
Thread State Description
NEW A thread that has not yet started is in this state.
RUNNABLE A thread executing in the Java virtual machine is in this state.
BLOCKED A thread that is blocked waiting for a monitor lock is in this state.
WAITING A thread that is waiting indefinitely for another thread to perform a particular
action is in this state.
TIMED_WAITING A thread that is waiting indefinitely for another thread to perform a particular
action is in this state.
TERMINATED A thread that has exited is in this state.
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.
Thread Groups
● Java thread group is implemented by java.lang.ThreadGroup class.
● 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.
2) ThreadGroup(ThreadGroup parent,
String name)
creates a thread group with a given parent group
and name.
Methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of ThreadGroup methods is given below.
S.N. Method Description
1) checkAccess() This method determines if the currently running thread has
permission to modify the thread group.
2) activeCount() This method returns an estimate of the number of active
threads in the thread group and its subgroups.
3) destroy() This method destroys the thread group and all of its
subgroups.
4) getMaxPriority() This method returns the maximum priority of the thread
group.
5) getName() This method returns the name of the thread group.
6) getParent() This method returns the parent of the thread group.
7) interrupt() This method interrupts all threads in the thread group.
8) list() This method prints information about the thread group to
the standard output.
9) suspend() This method is used to suspend all threads in the thread
group.
10) resume() This method is used to resume all threads in the thread
group which was suspended using suspend() method.
11) stop() This method is used to stop all threads in 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
File: ThreadGroupDemo.java
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]
_____________________________________________________________________________________

More Related Content

Similar to 21UCAC31 Java Programming.pdf(MTNC)(BCA)

Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
Mohammad Faizan
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Raffi Khatchadourian
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
ssuser84e52e
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
RatnaJava
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
yazad dumasia
 
Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \
Pritom Chaki
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
AdilAijaz3
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
talha ijaz
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
Raffi Khatchadourian
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
aptechaligarh
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
amitbhachne
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
Java Notes
Java Notes Java Notes
Java Notes
Sreedhar Chowdam
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Raffi Khatchadourian
 

Similar to 21UCAC31 Java Programming.pdf(MTNC)(BCA) (20)

Interface in java
Interface in javaInterface in java
Interface in java
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \Object Orinted Programing(OOP) concepts \
Object Orinted Programing(OOP) concepts \
 
Java 06
Java 06Java 06
Java 06
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 

More from ssuser7f90ae

21UCAE53 The-Internet-Of-Things.pptx(MTNC)
21UCAE53 The-Internet-Of-Things.pptx(MTNC)21UCAE53 The-Internet-Of-Things.pptx(MTNC)
21UCAE53 The-Internet-Of-Things.pptx(MTNC)
ssuser7f90ae
 
21UCAE61 Cyber Security.pptx(MTNC) (BCA)
21UCAE61 Cyber Security.pptx(MTNC) (BCA)21UCAE61 Cyber Security.pptx(MTNC) (BCA)
21UCAE61 Cyber Security.pptx(MTNC) (BCA)
ssuser7f90ae
 
21UCAE52 Software Project Management.ppt
21UCAE52 Software Project Management.ppt21UCAE52 Software Project Management.ppt
21UCAE52 Software Project Management.ppt
ssuser7f90ae
 
21UCAC 41 Database Management System.ppt
21UCAC 41 Database Management System.ppt21UCAC 41 Database Management System.ppt
21UCAC 41 Database Management System.ppt
ssuser7f90ae
 
23UCAEC21 Introduction to Data Science.pptx
23UCAEC21 Introduction to Data Science.pptx23UCAEC21 Introduction to Data Science.pptx
23UCAEC21 Introduction to Data Science.pptx
ssuser7f90ae
 
21UCAE65 Software Testing.pdf(MTNC)(BCA)
21UCAE65 Software Testing.pdf(MTNC)(BCA)21UCAE65 Software Testing.pdf(MTNC)(BCA)
21UCAE65 Software Testing.pdf(MTNC)(BCA)
ssuser7f90ae
 
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
ssuser7f90ae
 
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
ssuser7f90ae
 
23UCAFC11 Programming in C.pdf (MTNC)(BCA)
23UCAFC11 Programming in C.pdf (MTNC)(BCA)23UCAFC11 Programming in C.pdf (MTNC)(BCA)
23UCAFC11 Programming in C.pdf (MTNC)(BCA)
ssuser7f90ae
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVAPHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
ssuser7f90ae
 
கல்மரம் _ 21SUCS033.pdf
கல்மரம் _ 21SUCS033.pdfகல்மரம் _ 21SUCS033.pdf
கல்மரம் _ 21SUCS033.pdf
ssuser7f90ae
 

More from ssuser7f90ae (12)

21UCAE53 The-Internet-Of-Things.pptx(MTNC)
21UCAE53 The-Internet-Of-Things.pptx(MTNC)21UCAE53 The-Internet-Of-Things.pptx(MTNC)
21UCAE53 The-Internet-Of-Things.pptx(MTNC)
 
21UCAE61 Cyber Security.pptx(MTNC) (BCA)
21UCAE61 Cyber Security.pptx(MTNC) (BCA)21UCAE61 Cyber Security.pptx(MTNC) (BCA)
21UCAE61 Cyber Security.pptx(MTNC) (BCA)
 
21UCAE52 Software Project Management.ppt
21UCAE52 Software Project Management.ppt21UCAE52 Software Project Management.ppt
21UCAE52 Software Project Management.ppt
 
21UCAC 41 Database Management System.ppt
21UCAC 41 Database Management System.ppt21UCAC 41 Database Management System.ppt
21UCAC 41 Database Management System.ppt
 
23UCAEC21 Introduction to Data Science.pptx
23UCAEC21 Introduction to Data Science.pptx23UCAEC21 Introduction to Data Science.pptx
23UCAEC21 Introduction to Data Science.pptx
 
21UCAE65 Software Testing.pdf(MTNC)(BCA)
21UCAE65 Software Testing.pdf(MTNC)(BCA)21UCAE65 Software Testing.pdf(MTNC)(BCA)
21UCAE65 Software Testing.pdf(MTNC)(BCA)
 
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
 
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
21UCAE55 Management Information Systems.pdf(MTNC)(BCA)
 
23UCAFC11 Programming in C.pdf (MTNC)(BCA)
23UCAFC11 Programming in C.pdf (MTNC)(BCA)23UCAFC11 Programming in C.pdf (MTNC)(BCA)
23UCAFC11 Programming in C.pdf (MTNC)(BCA)
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVAPHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
PHONE GUARD MOBILE ANTI THEFT SYSTEM JAVA
 
கல்மரம் _ 21SUCS033.pdf
கல்மரம் _ 21SUCS033.pdfகல்மரம் _ 21SUCS033.pdf
கல்மரம் _ 21SUCS033.pdf
 

Recently uploaded

Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 

Recently uploaded (20)

Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 

21UCAC31 Java Programming.pdf(MTNC)(BCA)

  • 1. Course Name Advanced Java Programming Course Code 21UCSC51 Unit: I Classes and Interfaces Classes and Interfaces: Introduction –Interfaces – marker Interfaces –Functional interfaces, default and static methods – Abstract classes – Immutable classes – Anonymous classes – Visibility – Inheritance and Multiple Inheritance – Encapsulation – Final classes and methods. Unit: II Methods and General Programming Guidelines Methods: Method Signatures – Methods body – Method overloading and overriding – Inlining – Recursion – Method References – Immutability Unit: III Exceptions & Thread and Thread Groups Exceptions: Exceptions and when to use – Checked and unchecked exceptions – using try –with- resources – Exceptions and lambdas – Standard Java exceptions .Threads and Thread Groups – Concurrency, synchronization and Immutability Unit: IV Dynamics Language Support and API Dynamics languages support: Dynamic Languages Support – Scripting API - JavaScript on JVM – Groovy on JVM – Ruby on JVM – Python on JVM – Using Scripting API. Unit: V Java Annotation Processors and Java Agent Basics Java Compiler API: Java Compiler API – Annotation Processors – Element Scanners – Java Compiler Tree API.
  • 2. ___________________________________________________________________ Unit 1 1.1 Interface 1.2 Default Methods and Static Methods 1.3 Marker Interface 1.4 Functional Interface 1.5 Inheritance and Multiple Inheritance _____________________________________________________________________________________ 1.1 Interface in Java Introduction  An interface in Java is a blueprint of a class. It has static constants and abstract methods.  The interface in Java is a mechanism to achieve abstraction.  Interfaces can have abstract methods and variables. It cannot have a method definition.  Java Interface also represents the IS-A relationship.  It cannot be instantiated just like the abstract class.  We can have default and static methods in an interface. Reasons to Use Interface  It is used to achieve abstraction.  By interface, we can support the functionality of multiple inheritance.  It can be used to achieve loose coupling. Declaring An Interface  An interface is declared by using the interface keyword.  It provides total abstraction; means all the methods in an interface are declared without any definition, and all the fields are public, static and final by default.  A class that implements an interface must implement all the methods declared in the interface. Syntax: interface <interface_name> { // declare constant fields // declare methods that abstract }
  • 3. Internal addition by the compiler Interface fields are public, static and final by default, and the methods are public and abstract. Relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface. Java Interface Example In this example, the Printable interface has only one method, and its implementation is provided in the A6 class. interface printable{ void print(); } class A6 implements printable { public void print(){System.out.println("Hello"); } public static void main(String args[]) { A6 obj = new A6(); obj.print(); } } Output: Hello
  • 4. Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance. interface Printable { void print(); } interface Showable { void show(); } class A7 implements Printable,Showable { public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } class TestInterface { public static void main(String args[]) { A7 obj = new A7(); obj.print(); obj.show(); } } Output: Hello Welcome
  • 5. 1.2 Default Methods and Static Methods Default Methods Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with default are known as default methods. These methods are non-abstract methods. Example : interface Drawable { void draw(); default void msg() { System.out.println("default method"); } } class Rectangle implements Drawable { public void draw() { System.out.println("drawing rectangle"); } } class TestInterfaceDefault { public static void main(String args[]) { Drawable d=new Rectangle(); d.draw(); d.msg(); } } Output: drawing rectangle default method Static Methods A static method is a method that belongs to a class rather than an instance of a class. This means you can call a static method without creating an object of the class. Since Java 8, we can have static method in interface. Example:
  • 6. interface Drawable { void draw(); static int cube(int x) { return x*x*x; } } class Rectangle implements Drawable { public void draw() { System.out.println("drawing rectangle"); } } class TestInterfaceStatic { public static void main(String args[]) { Drawable d=new Rectangle(); d.draw(); System.out.println(Drawable.cube(3)); } } Output: drawing rectangle 27 1.3 Marker Interface Introduction  An interface that does not contain methods, fields, and constants is known as marker interface.  In other words, an empty interface is known as marker interface or tag interface.  It delivers the run-time type information about an object.  It is the reason that the JVM and compiler have additional information about an object.  The Serializable and Cloneable interfaces are the example of marker interface. Example: public interface Serializable
  • 7. { } Uses of Marker Interface  Marker interface is used as a tag that informs the Java compiler by a message so that it can add some special behavior to the class implementing it.  It is used to logically divide the code and a good way to categorize code.  It is more useful for developing API. Built-in Marker Interface In Java, built-in marker interfaces are the interfaces that are already present in the JDK and ready to use. There are many built-in marker interfaces some of them are:  Cloneable Interface  Serializable Interface  Remote Interface i) Cloneable Interface Cloneable interface in Java is also a marker interface that belong to java.lang package. It generates a replica (copy) of an object with a different name. We can implement the interface in the class of which class, object to be cloned. ii) Serializable Interface It is a marker interface in Java that is defined in the java.io package. If we want to make the class serializable, we must implement the Serializable interface. Serialization is a mechanism in which object state is read from the memory and written into a file or database. Deserialization means that object state reading from a file or database and written back into memory. iii) Remote Interface Remote interface is a marker interface that belong to java.rmi package. It marks an object as remote that can be accessed from another machine (host). We must implement the Remote interface if we want to make an object as remote. Custom Marker Interface Apart from built-in marker interface, Java also allows us to create our own marker interface. Example:
  • 8. interface Car { 96 } interface Engine { } //class that implements the Car marker interface class Vehicle implements Car { static void isVehicle() { System.out.println("Car is a vehicle."); } } //class that implements the Engine marker interface class Status implements Engine { static void isWorking() { System.out.println("Yes, engine is working."); } } //main class public class Program { public static void main(String args[]) { //invoking the methods of the class Vehicle.isVehicle(); Status.isWorking(); } } Output: Car is a vehicle. Yes, engine is working.
  • 9. 1.4 Functional Interfaces in Java Introduction  A functional interface is an interface that contains only one abstract method.  They can have only one functionality to exhibit.  From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface.  A functional interface can have any number of default methods.  Runnable, ActionListener, Comparable are some of the examples of functional interfaces.  Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces.  Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Java Program to demonstrate functional interface interface inter1{ void display(String msg); } public class C1 implements inter1 { public void display(String msg) { System.out.println(msg); } public static void main(String[] args) { C1 C = new C1(); C.display("Hello there"); } } Output New thread created Functional interface using lambda expressions interface FuncInterface {
  • 10. void abstractFun(int x); default void normalFun() { System.out.println("Hello"); } } class Program { public static void main(String args[]) { FuncInterface fobj = (int x)->System.out.println(2*x); fobj.abstractFun(5); } } Output 10 1.5 Inheritance in Java Introduction ● Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. ● It is an important part of Object Oriented programming system. ● The idea behind inheritance in Java is that we can create new classes that are built upon existing classes. ● When we inherit from an existing class, we can reuse methods and fields of the parent class. ● Moreover, we can add new methods and fields in our current class also. ● Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java  For Method Overriding  For Code Reusability. Terms used in Inheritance  Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • 11.  Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.  Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.  Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. Syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } Types of Inheritance On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only.
  • 12. Example class A { int a, b; void display() { System.out.println(“a=”+a); System.out.println(“b=”+b); } } class B extends A { int c; void show() { System.out.println(“c = ”+c); } } class SingleInheritance { public static void main(String args[]) { B obj = new B(); //derived class object obj.a=10; obj.b=20; obj.c=30; obj.display(); obj.show(); } } Output: barking... eating... Multiple Inheritance When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java does not support multiple inheritance. To achieve multiple inheritance in Java, we must use the interface.
  • 13. interface Printable { void print(); } interface Showable { void show(); } class A7 implements Printable,Showable { public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } class TestInterface { public static void main(String args[]) { A7 obj = new A7(); obj.print(); obj.show(); } } Output: Hello Welcome
  • 14. __________________________________________________________________ Unit 2 2.1 Methods in Java 2.2 Method Overloading 2.3 Method Overriding 2.4 Recursion 2.5 Java Method References ___________________________________________________________________ 2.1 Methods in Java  A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation.  It is used to achieve the reusability of code.  We write a method once and use it many times.  We need not require to write code again and again.  It also provides the easy modification and readability of code, just by adding or removing a chunk of code.  The method is executed only when we call or invoke it. Method Declaration The method declaration provides information about method attributes, such as access specifier, return- type, name, and parameters.
  • 15. Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier:  Public: The method is accessible by all classes when we use public specifier in our application.  Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.  Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package.  Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Defining Methods: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. Types of Methods in Java There are two types of methods in Java: 1. Predefined Method ● In Java, predefined methods are the method that is already defined in the Java class libraries. ● It is also known as the standard library method or built-in method. ● We can directly use these methods just by calling them in the program at any point. 2. User-defined Method ● The method written by the user or programmer is known as a user-defined method. ● These methods are modified according to the requirement.
  • 16. Example: import java.io.*; class Addition { int sum = 0; public int sum(int a, int b) { sum = a + b; return sum; } } class sample { public static void main(String[] args) { Addition add = new Addition(); int s = add.sum(1, 2); System.out.println("Sum of two integer values :" + s); } } Output Sum of two integer values :3 2.2 Method Overloading Introduction If a class has multiple methods having the same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having the same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. Advantages of Method Overloading  Method overloading increases the readability of the program.
  • 17. Different ways to overload the method There are two ways to overload the method in java  By changing number of arguments  By changing the data type 1) Method Overloading: changing no. of arguments In this example, we have created two methods. The first add() method performs addition of two numbers and second add method performs addition of three numbers. In this example, we are creating static methods so that we don't need to create an instance for calling methods. class Adder { static int add(int a,int b) { return a+b; } static int add(int a,int b,int c) { return a+b+c; } } class TestOverloading1 { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); } } Output: 22 33
  • 18. 2) Method Overloading: changing data type of arguments In this example, we have created two methods that differ in data type. The first add method receives two integer arguments and the second add method receives two double arguments. class Adder{ static int add(int a, int b){return a+b;} static double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} Output: 22 24.9 2.3 Method Overriding Introduction  If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.  In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent classes, it is known as method overriding. Usage of Java Method Overriding  Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.  Method overriding is used for runtime polymorphism Rules for Java Method Overriding  The method must have the same name as in the parent class  The method must have the same parameter as in the parent class.
  • 19.  There must be an IS-A relationship (inheritance). Example of Method Overriding In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding. class Vehicle { void run() { System.out.println("Vehicle is running"); } } class Bike2 extends Vehicle { void run() { System.out.println("Bike is running safely"); } public static void main(String args[]) { Bike2 obj = new Bike2(); obj.run(); } } Output: Bike is running safely 2.4 Recursion Introduction  Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called a recursive method.  It makes the code compact but complex to understand. Advantages
  • 20.  Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn't necessarily reduce space requirements or speed of execution).  Reduces time complexity.  Performs better in solving problems based on tree structures. Syntax: returntype methodname() { methodname(); } Working of Recursion  The idea is to represent a problem in terms of one or more smaller sub-problems and add base conditions that stop the recursion.  For example, we compute factorial n if we know the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0. How is memory allocated to different function calls in recursion?  When any function is called from main(), the memory is allocated to it on the stack.  A recursive function calls itself, the memory for the called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call.  When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues. Example public class RecursionExample3 { static int factorial(int n) { if (n == 1) return 1; else return(n * factorial(n-1)); } public static void main(String[] args) { System.out.println("Factorial of 5 is: "+factorial(5)); }
  • 21. } Output: Factorial of 5 is: 120 2.5 Java Method References Java provides a new feature called method reference in Java 8. Method reference is used to refer to a method of functional interface. It is a compact and easy form of lambda expression. Each time when you are using lambda expression to just refer to a method, you can replace your lambda expression with method reference. Types of Method References There are following types of method references in java: 1. Reference to a static method. 2. Reference to an instance method. 3. Reference to a constructor. 1) Reference to a Static Method We can refer to the static method defined in the class. Following is the syntax and example which describe the process of referring to static methods in Java. Syntax ContainingClass::staticMethodName Example In the following example, we have defined a functional interface and referring a static method to its functional method say(). interface Sayable{ void say(); } public class MethodReference {
  • 22. public static void saySomething(){ System.out.println("Hello, this is static method."); } public static void main(String[] args) { Sayable sayable = MethodReference::saySomething; sayable.say(); } } Output: Hello, this is static method. 2) Reference to an Instance Method Like static methods, We can refer to instance methods also. In the following example, we are describing the process of referring to the instance method. Syntax containingObject::instanceMethodName Example In the following example, we are referring to non-static methods. We can refer to methods by class object and anonymous object. interface Sayable{ void say(); } public class InstanceMethodReference { public void saySomething(){ System.out.println("Hello, this is non-static method."); } public static void main(String[] args) { InstanceMethodReference methodReference = new InstanceMethodReference(); Sayable sayable = methodReference::saySomething; Ssayable.say(); Sayable sayable2 = new InstanceMethodReference()::saySomething; Sayable2.say(); } }
  • 23. Output: Hello, this is non-static method. Hello, this is non-static method. 3) Reference to a Constructor We can refer to a constructor by using the new keyword. Here, we are referring constructor with the help of functional interfaces. Syntax ClassName::new Example interface Messageable{ Message getMessage(String msg); } class Message{ Message(String msg){ System.out.print(msg); } } public class ConstructorReference { public static void main(String[] args) { Messageable hello = Message::new; hello.getMessage("Hello"); } } Output: Hello _____________________________________________________________________________________
  • 24. ___________________________________________________________________ Unit 3 3.1. Exceptions - When to use them - Checked and unchecked exceptions 3.2 Using try-with-resources 3.3 Standard Java exceptions 3.4 Threads and Thread Groups ___________________________________________________________________ 3.1. Exceptions - Checked and Unchecked Exceptions Introduction ● Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. ● Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. What is an Exception? ● Exception 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
  • 25. Differences between Error and Exception:  Error: An Error indicates a serious problem that a reasonable application should not try to catch. Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.  Exception: Exception indicates conditions that a reasonable application might try to catch. Types of Exceptions Exceptions can be categorized in two ways: 1. Built-in Exceptions  Checked Exception  Unchecked Exception 2. User-Defined Exceptions Let us discuss the above-defined listed exception that is as follows: A. Built-in Exceptions:
  • 26. Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations.  Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler.  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. B. User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’. Advantages of Exception Handling in Java: 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 Checked and unchecked exceptions ● Unchecked exceptions are used to signal about erroneous conditions related to program logic and assumptions being made (invalid arguments, null pointers, unsupported operations, …). ● Any unchecked exception is a subclass of RuntimeException. ● Unchecked exceptions are not required to be caught by the caller. ● The NullPointerException is the most known member of unchecked exceptions and here is its declaration from the Java standard library:
  • 27. public class NullPointerException extends RuntimeException { public NullPointerException() { super(); } public NullPointerException(String s) { super(s); } } ● Checked exceptions represent invalid conditions in the areas which are outside of the immediate control of the program (like memory, network, file system, …). ● Any checked exception is a subclass of Exception. ● Checked exceptions must be either caught by the caller. ● The IOException is, probably, the most known one among checked exceptions: public class IOException extends Exception { public IOException() { super(); } public IOException(String message) { super(message); } public IOException(String message, Throwable cause) { super(message, cause); } public IOException(Throwable cause) { super(cause); } } _____________________________________________________________________________________
  • 28. 3.2. Using try-with-resources Introduction ● In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. ● A resource is an object that must be closed once your program is done using it. ● For example, a File resource or a Socket connection resource. ● The try-with-resources statement ensures that each resource is closed at the end of the statement execution. ● If we don’t close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it. ● We can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable. ● By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. ● The resources will be closed as soon as the try-catch block is executed. Syntax: Try-with-resources try(declare resources here) { // use resources } catch(FileNotFoundException e) { // exception handling } Exceptions: ● When it comes to exceptions, there is a difference in try-catch-finally block and try-with- resources block. ● If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block. ● For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block.
  • 29. ● The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with- resources block throws suppressed exceptions. Example : try-with-resources having a single resource // Java Program for try-with-resources // having single resource import java.io.*; class GFG { public static void main(String[] args) { try ( FileOutputStream fos = new FileOutputStream("gfgtextfile.txt")) { String text = "Hello World. This is my java program"; // Converting string to bytes byte arr[] = text.getBytes(); fos.write(arr); } catch (Exception e) { System.out.println(e); } System.out.println( "Resource are closed and message has been written into the gfgtextfile.txt"); } } Output: Resource are closed and message has been written into the gfgtextfile.txt _____________________________________________________________________________________
  • 30. 3.3 Standard Java Exceptions The Java standard library provides a plenty of exception classes which are designated to cover most of the generic errors happening during program execution. The most widely used are presented in the table below, please consider those before defining your own. Exception Class Purpose NullPointerException Attempts to use null in a case where an object is required. IllegalArgumentException Method has been passed an illegal or inappropriate argument. IllegalStateException Method has been invoked at an illegal or inappropriate time. IndexOutOfBoundsException Index of some sort (such as to an array, to a string, or to a vector) is out of range. UnsupportedOperationException Requested operation is not supported. ArrayIndexOutOfBoundsException An array has been accessed with an illegal index. ClassCastException Code has attempted to cast an object to a subclass of which it is not an instance. EnumConstantNotPresentException Attempt to access an enum constant by name and the enum type contains no constant with the specified name (enums have been on covered in the part 5 of the tutorial, How and when to use Enums and Annotations). NumberFormatException Attempts to convert a string to one of the numeric types, but that the string does not have the appropriate format. StringIndexOutOfBoundsException Index is either negative or greater than the size of the string. IOException I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
  • 31. 3.4 Threads and Thread Groups Introduction ● The multiprocessor and multicore hardware architectures greatly influence the design and execution model of applications which run on them nowadays. ● In order to utilize the full power of available computational units, the applications should be ready to support multiple execution flows which are running concurrently and competing for resources and memory. Threads in Java ● Threads are the foundational building blocks of concurrent applications in Java. ● Threads are sometimes called lightweight processes and they allow multiple execution flows to proceed concurrently. ● Every single application in Java has at least one thread called the main thread. ● Threads have a complex lifecycle and can be in one of the following states. Thread State Description NEW A thread that has not yet started is in this state. RUNNABLE A thread executing in the Java virtual machine is in this state. BLOCKED A thread that is blocked waiting for a monitor lock is in this state. WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state. TIMED_WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state. TERMINATED A thread that has exited is in this state. 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. Thread Groups ● Java thread group is implemented by java.lang.ThreadGroup class.
  • 32. ● 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. 2) ThreadGroup(ThreadGroup parent, String name) creates a thread group with a given parent group and name. Methods of ThreadGroup class There are many methods in ThreadGroup class. A list of ThreadGroup methods is given below. S.N. Method Description 1) checkAccess() This method determines if the currently running thread has permission to modify the thread group. 2) activeCount() This method returns an estimate of the number of active threads in the thread group and its subgroups. 3) destroy() This method destroys the thread group and all of its subgroups. 4) getMaxPriority() This method returns the maximum priority of the thread group.
  • 33. 5) getName() This method returns the name of the thread group. 6) getParent() This method returns the parent of the thread group. 7) interrupt() This method interrupts all threads in the thread group. 8) list() This method prints information about the thread group to the standard output. 9) suspend() This method is used to suspend all threads in the thread group. 10) resume() This method is used to resume all threads in the thread group which was suspended using suspend() method. 11) stop() This method is used to stop all threads in 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 File: ThreadGroupDemo.java
  • 34. 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] _____________________________________________________________________________________