The document outlines the course units for an Advanced Java Programming course. Unit 1 covers classes, interfaces, inheritance and encapsulation. Unit 2 discusses methods, method overloading, overriding and recursion. Unit 3 focuses on exceptions, threads and immutability. Unit 4 covers dynamic language support and APIs. Unit 5 is about Java annotation processors and agents.
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Raffi Khatchadourian
The skeletal implementation pattern is a software design pattern
consisting of defining an abstract class that provides a partial interface implementation. However, since Java allows only single class inheritance, if implementers decide to extend a skeletal implementation, they will not be allowed to extend any other class. Also, discovering the skeletal implementation may require a global analysis. Java 8 enhanced interfaces alleviate these problems by allowing interfaces to contain (default) method implementations, which implementers inherit. Java classes are then free to extend a different class, and a separate abstract class is no longer needed; developers considering implementing an interface need only examine the interface itself. We argue that both these benefits improve software modularity, and discuss our ongoing work in developing an automated refactoring tool that would assist developers in taking advantage of the enhanced interface feature for their legacy Java software.
OOP with Java - Abstract Classes and InterfacesRatnaJava
In this session you will learn:
Overview of OOP continued…
Abstraction – using Abstract Classes and Interfaces.
For more information: https://www.mindsmapped.com/courses/software-development/become-a-java-developer-hands-on-training/
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and Inheritance , Exploring the Base Class Library -, Debugging and Error Handling , Data Types full knowledge about basic of .NET Framework
This slide about presentation of Object Oriented Programing or OOP contains Fundamental of OOP
Encapsulation
Inheritance
Abstract Class
Association
Polymorphism
Interface
Exceptional Handling
and more.
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Raffi Khatchadourian
The skeletal implementation pattern is a software design pattern
consisting of defining an abstract class that provides a partial interface implementation. However, since Java allows only single class inheritance, if implementers decide to extend a skeletal implementation, they will not be allowed to extend any other class. Also, discovering the skeletal implementation may require a global analysis. Java 8 enhanced interfaces alleviate these problems by allowing interfaces to contain (default) method implementations, which implementers inherit. Java classes are then free to extend a different class, and a separate abstract class is no longer needed; developers considering implementing an interface need only examine the interface itself. We argue that both these benefits improve software modularity, and discuss our ongoing work in developing an automated refactoring tool that would assist developers in taking advantage of the enhanced interface feature for their legacy Java software.
OOP with Java - Abstract Classes and InterfacesRatnaJava
In this session you will learn:
Overview of OOP continued…
Abstraction – using Abstract Classes and Interfaces.
For more information: https://www.mindsmapped.com/courses/software-development/become-a-java-developer-hands-on-training/
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and Inheritance , Exploring the Base Class Library -, Debugging and Error Handling , Data Types full knowledge about basic of .NET Framework
This slide about presentation of Object Oriented Programing or OOP contains Fundamental of OOP
Encapsulation
Inheritance
Abstract Class
Association
Polymorphism
Interface
Exceptional Handling
and more.
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Similar to 21UCAC31 Java Programming.pdf(MTNC)(BCA) (20)
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
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]
_____________________________________________________________________________________