Download as pdf or txt
Download as pdf or txt
You are on page 1of 159

JAVA PROGRAMMING

UNIT - I
Introduction to Java
 Java is an object-oriented programming
language developed by Sun Microsystems.
 Modeled after C++, the Java language was
designed to be small, simple, and portable
across platforms and operating systems.
 Java is also a platform.
 Any hardware or software environment in which a
program runs, is known as a platform.
 Since Java has its own runtime environment (JRE)
and API, it is called platform.
JDK Editions

 Java Standard Edition (J2SE)


 J2SE can be used to develop client-side standalone
applications or applets.
 Java Enterprise Edition (J2EE)
 J2EE can be used to develop server-side
applications such as Java servlets and Java
ServerPages.
 Java Micro Edition (J2ME)
 J2ME can be used to develop applications for
mobile devices such as cell phones.
JDK vs JRE vs JVM
 JDK (Java Development Kit)
 JDK contains everything that will be required
to develop and run Java application.

 JRE (Java Run time Environment)


 JRE contains everything required to run Java
application which has already been compiled.
 It doesn’t contain the code library required to
develop Java application.
JDK vs JRE vs JVM
 JVM (Java Virtual Machine)
 JVM is a virtual machine which work on top of
your operating system to provide a recommended
environment for your compiled Java code.
 JVM only works with bytecode.

 Hence you need to compile your Java


application(.java) so that it can be converted
to bytecode format (also known as the .class file).
 JVM uses .class to run application.
JDK vs JRE vs JVM
 Java Development Kit (JDK) consists of Java
Runtime Environment (JRE) along with tools
to compile and debug Java code for developing
Java applications.
 JRE consists of libraries, Java Virtual Machine

(JVM), Java Plug-in and Java Web Start to run


Java applications.
 JRE as a stand-alone does not contain

compilers and debugging tools.


JVM (Java Virtual Machine)
 JVM is a virtual machine or a program that
provides run-time environment in which java
byte code can be executed.
 JVMs are available for many hardware and

software platforms.
 The use of the same byte code for all JVMs on

all platforms make java platform independent.


JVM (Java Virtual Machine)
 Main task of JVM
1. Search and locate the required files
2. Convert byte code into executable code
3. Allocate the memory into ram
4. Execute the code
5. Delete the executable code
Java better than C++ ?

 No Typedefs, Defines, or Preprocessor


 No Global Variables
 No Goto statements
 No Pointers
 No Unsafe Structures
 No Multiple Inheritance
 No Operator Overloading
 No Automatic Coercions
Java Buzzwords
Java Buzzwords
 Simple
 Javais a simple Language because it contains many
features of other Languages like C and C++ and
removes complexity because it doesn’t support
pointers, storage classes, goto statements and
multiple inheritances.
 Object Oriented
 Java is purely an Object Oriented Programming
language i.e., all the code of the Java language is
written into the classes and objects.
Java Buzzwords
 Distributed
 Java is a distributed language because, because of
its ability to share the data and programs over the
LAN.
 Access remote objects.

 Multithreaded
 A Javaprogram can be divided into multiple threads
assigning different tasks for different threads and
have all the threads executing in parallel.
Java Buzzwords
 Dynamic
 The JVM maintains a lot of runtime information
about the program and the objects in the program.
 Libraries are dynamically linked during runtime.

 Architecture Neutral
 Java follows “Write-once-run-anywhere” approach.
 Java programs are compiled into byte code format
which does not depend on any machine architecture
but can be easily translated into a specific machine
by a JVM for that machine.
Java Buzzwords
 Portable
 In Java the size of the primitive data types are
machine independent.
 Int in Java is always a 32-bit integer, and float is
always a 32-bit IEEE 754 floating point number.
 Interpreted & High Performance
 Java programs are compiled to portable intermediate
form known as byte codes, rather than to native
machine level instructions and JVM executes the
byte codes on any machine on which it is installed.
 Just-in-time compiler.
Java Buzzwords
 Robust
 A Program or an application is said to be robust
(reliable) when it is able to give some response in
any kind of context.
 Java’s features help to make the programs robust.
Some of those features are: type checking,
exception handling, etc.
 Secured
 Java provides data security through encapsulation.
Java Buzzwords
 Interpreted
 A Program or an application is said to be robust (reliable)
when it is able to give some response in any kind of
context.
 Java’s features help to make the programs robust.
Some of those features are: type checking,
exception handling, etc.
 Secured
 Java provides data security through encapsulation.
Types of Java Applications
 Standalone Application
 It is also known as desktop application or window-
based application.
 An application that we need to install on every
machine such as media player, antivirus etc.
 AWT and Swing are used in java for creating
standalone applications.
Types of Java Applications
 Web Application
 An application that runs on the server side and
creates dynamic page, is called web application.
 Currently, servlet, jsp, struts, jsf etc. technologies
are used for creating web applications in java.
Types of Java Applications
 Enterprise Application
 An application that is distributed in nature, such as
banking applications etc.
 It has the advantage of high level security, load
balancing and clustering. I
 n java, EJB is used for creating enterprise
applications.
 Mobile Application
 An application that is created for mobile devices.
 Currently Android and Java ME are used for
creating mobile applications.
An Overview of Java
 Object-Oriented Programming
 Object-oriented programming (OOP) is at the core
of Java.
 In fact, all Java programs are to at least some extent
object-oriented.

 Two Paradigms
1. Process-Oriented Model
2. Object-Oriented Programming
An Overview of Java
 Process-Oriented Model
 This approach characterizes a program as a series
of linear steps (that is, code).
 The process-oriented model can be thought of as
code acting on data.
 Object-Oriented Programming
 This approach organizes a program around its data
(that is, objects) and a set of well-defined interfaces
to that data.
 An object-oriented program can be characterized as
data controlling access to code.
Abstraction
 Abstraction is a process where you show only
“relevant” data and “hide” unnecessary details
of an object from the user.
 We use abstract classes and interfaces to

achieve abstraction in java.


 Ex: Working of a Car, Working of a Projector,

Working of a Computer Working of an ATM.


Three OOP Principles
1. Inheritance
 When one object acquires all the properties and
behaviors of parent object i.e. known as inheritance.
 It provides code reusability.

 It is used to achieve runtime polymorphism.


Three OOP Principles
1. Inheritance
 Without the use of hierarchies, each object would
need to define all of its characteristics explicitly.
 However, by the use of inheritance, an object need
only define those qualities that make it unique
within its class.
 It can inherit its general attributes from its parent.

 Thus, it is the inheritance mechanism that makes it


possible for one object to be a specific instance of a
more general case.
Three OOP Principles
2. Polymorphism
 Polymorphism is a feature that allows one interface
to be used for a general class of actions.
 In java, we use method overloading and method
overriding to achieve polymorphism.
 Ex: Your mobile phone, one name but many forms:
as phone, as camera, as mp3 player, as radio.
Three OOP Principles
3. Encapsulation
 Binding (or wrapping) code and data together into a
single unit is known as encapsulation.
 Access to the code and data inside the wrapper is
tightly controlled through a well-defined interface.
 A java class is the example of encapsulation.

 Ex: capsule, it is wrapped with different medicines.


First Java Program

public class HelloWorld


{
public static void main (String args[])
{
System.out.println("Hello World");
}
}
First Java Program
 The keyword 'public' says that, the main
function can be accessed even outside the
defining class.
 The keyword 'static' indicates that a function

can be accessed without an object.


 The keyword 'void' indicates that a function

returns nothing.
 The Keyword 'main' is the name of the
function and entry point for a Java application.
Variants of main() in Java
 Default:
 public static void main(String args[])

 Variants:
 staticpublic void main(String args[])
 public static void main(String[] args)
 public final static void main(String[] args)
 public synchronized static void main(String[] args)

 The main() can be overloaded but not


overridden.
Static Keyword in Java

 The static keyword can be applied for


 Variables (Known as a class variable)
 Methods

 Blocks

 Nested classes
Instance Variables and Class
Variables
 Variables within the class created without the
keyword 'static' prefixed are called instance
variables or object variables or non-static
variables.

 A separate memory space for these types of


variables will be created for each instance of a
class.
Instance Variables and Class
Variables
 Variables within the class created with the
keyword 'static' prefixed are called class
variables or static variables.

 This type of variables actually shares the value


among all the instances of a class.

 Instance variables declared as static are,


essentially, global variables.
Instance Variables and Class
Variables
Understanding static
 We can define a class member that will be used
independently of any object of that class.
 When a member (variable or method) is
declared static, it can be accessed before any
objects of its class are created.
 Methods declared as static have several
restrictions
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Understanding static
Understanding static
Understanding static
Introducing final
 A field can be declared as final.
 Doing so prevents its contents from being modified,
making it, essentially, a constant.
 This means that you must initialize a final field when
it is declared.
 You can do this in one of two ways:
 First, you can give it a value when it is declared.
 Second, you can assign it a value within a
constructor.
 final int FILE_NEW = 1;
 final int FILE_OPEN = 2;
Arrays in Java
 Arrays are implemented as objects in Java.
Stack Implementation
Stack Implementation
Introducing Nested and Inner
Classes
 Defining a class within another class is known as
nested class.
 The scope of a nested class is bounded by the

scope of its enclosing class.


 Thus, if class B is defined within class A, then B
does not exist independently of A.
 A nested class has access to the members,

including private members, of the class in which


it is nested.
Introducing Nested and Inner
Classes
 However, the enclosing class does not have
access to the members of the nested class.
 A nested class that is declared directly within its
enclosing class scope is a member of its
enclosing class.
 It is also possible to declare a nested class that is
local to a block.
 There are two types of nested classes:
 Static
 Non-Static.
Introducing Nested and Inner
Classes
 The most important type of nested class is the
inner class.
 An inner class is a non-static nested class.

 It has access to all of the variables and methods

of its outer class and may refer to them directly in


the same way that other non-static members of
the outer class do.
Non-Static Inner Classes
Inner Classes within a Scope
Static Inner Class
Inheritance
 The process of obtaining properties of one entity
in another entity is known as Inheritance.
 “extends” keywords is used for the purpose of

inheritance.
 A class can only extend “only one class”.

 Inheritance can also be referred to the concept of


Generalization, which is the process of extracting
common characteristics (states and behavior)
from two or more classes, and combining them
into a generalized super class.
Types of Inheritance
Constructors
 It is a special method will be automatically
called at the time of instantiating the class.
 Rules:

 It must have same name as that of class name.


 It doesn’t contain any return type even void also.

 If we want we can provide access specifiers like


default, protected and public other than private.
 By using any parameterized constructor in our class,
if we want to create instance for the class by using
default constructor then we need to provide default
constructor implementation explicitly in the class.
Using super
 super has 3 uses
 The first calls the superclass’ constructor.
Using super
 The second is used to access a member of the
superclass that has been hidden by a member of
a subclass.
Using super
 The third is used to access a member function
of the superclass that has been hidden by a
member function of a subclass.
Method Overloading
 Defining two or more methods in a same java
class that share the same name but their
parameter declarations are different.
 When an overloaded method is invoked, Java

uses the type and/or number of arguments as its


guide to determine which version of the
overloaded method to actually call.
 While overloaded methods may have different
return types, the return type alone is insufficient
to distinguish two versions of a method.
Method Overloading
Method Overloading
Method Overloading
 When the exact match is not found, Java’s
automatic type conversion is used to find the
match.
Method Overriding
 In a class hierarchy, when a method in a
subclass has the same name and type signature
as a method in its superclass, then the method in
the subclass is said to override the method in the
superclass.
 When an overridden method is called from
within its subclass, it will always refer to the
version of that method defined by the subclass.
 The version of the method defined by the

superclass will be hidden.


Method Overriding
Constructor Overloading
Constructor Overloading
Dynamic Method Dispatch
 Method overriding forms the basis for one of
Java’s most powerful concepts: Dynamic
Method Dispatch.
 Dynamic method dispatch is the mechanism by

which a call to an overridden method is


resolved at run time, rather than compile time.
 Dynamic method dispatch is important because

this is how Java implements run-time


polymorphism.
Dynamic Method Dispatch
 Superclass reference variable can refer to a
subclass object.
 When an overridden method is called through a

superclass reference, Java determines which


version of that method to execute based upon
the type of the object being referred to at the
time the call occurs.
 It is the type of the object being referred to that
determines which version of an overridden
method will be executed.
Dynamic Method Dispatch
Dynamic Method Dispatch
Dynamic Method Dispatch
Dynamic Method Dispatch
Using Abstract Classes
 There are situations in which you will want to
define a superclass that declares the structure of
a given abstraction without providing a
complete implementation of every method.
 Create a superclass that only defines a

generalized form that will be shared by all of its


subclasses, leaving it to each subclass to fill in
the details.
 Such a class determines the nature of the

methods that the subclasses must implement.


Using Abstract Classes
 Any class that contains one or more abstract
methods must also be declared abstract.
 abstract class A{}
 There can be no objects of an abstract class.
 That is, an abstract class cannot be directly
instantiated with the new operator.
 Any subclass of an abstract class must either

implement all of the abstract methods in the


superclass, or be declared abstract itself.
Using Abstract Classes
Using Abstract Classes
 Abstract classes cannot be used to instantiate
objects.
 But, they can be used to create object

references.
 Possible to create a reference to an abstract
class so that it can be used to point to a
subclass object.
Using Abstract Classes
Using Abstract Classes
Using Abstract Classes
Using Abstract Classes
Using final with Inheritance
 Using final to Prevent Overriding:
 To disallow a method from being overridden,
specify final as a modifier at the start of its
declaration. Methods declared as final cannot
be overridden.
Using final with Inheritance
 Using final to Prevent Inheritance
 Sometimes you will want to prevent a class
from being inherited.
 Declaring a class as final implicitly declares all

of its methods as final, too.


Interfaces
 Using the keyword interface, you can fully
abstract a class’ interface from its
implementation.
 Using interface, you can specify what a class

must do, but not how it does it.


 Interfaces are syntactically similar to classes,

but they lack instance variables.


 Methods in interfaces are declared without any
body and are by default “public nonstatic and
abstract” in nature.
Interfaces
 All the variables present in the interface are by
default “public static and final”.
 “implements” keyword is used for implementing
interfaces to the class.
 One class can implement any number of
interfaces.
 To implement an interface, a class must implement
all the methods of the interface.
 If a class includes an interface but does not fully
implement the methods required by that interface,
then that class must be declared as abstract.
Defining an Interface
 An interface is defined much like a class. This is
a simplified general form of an interface:

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
}
Implementing Interfaces
Accessing Implementations
Through Interface References
 You can declare variables as object references
that use an interface rather than a class type.
 Any instance of any class that implements the

declared interface can be referred to by such a


variable.
 When you call a method through one of these

references, the correct version will be called


based on the actual instance of the interface
being referred to.
 This is one of the key features of interfaces.
Accessing Implementations
Through Interface References
Nested Interfaces
 An interface can be declared a member of a
class or another interface.
 Such an interface is called a member interface

or a nested interface.
 A nested interface can be declared as public,
private, or protected.
 When a nested interface is used outside of its

enclosing scope, it must be qualified by the


name of the class or interface of which it is a
member.
Interface in a Class
Interface in a Class
Interface in another Interface
Variables in Interfaces
 You can use interfaces to import shared
constants into multiple classes by simply
declaring an interface that contains variables
that are initialized to the desired values.
 When you include that interface in a class all of

those variable names will be in scope as


constants.
Interfaces Can Be Extended
Interfaces Can Be Extended
Interfaces in Java 8
 By providing the interface keyword, Java allows
you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
 Java 8 allows the interfaces to have default and
static methods.
 Allows the developers to add new methods to the
interfaces without affecting the classes that
implements these interfaces.
 Static methods in interfaces are similar to the
default methods except that we cannot override
these methods in the classes that implements these
interfaces.
Interfaces in Java 8
Interfaces in Java 8
 JDK 8 supports the ability to define one or
more static methods in interfaces.
 Like static methods in a class, a static method
defined by an interface can be called
independently of any object.
 No implementation of the interface is
necessary.
 No instance of the interface is required.

 Instead, a static method is called by specifying


the interface name:
 InterfaceName.staticMethodName
Interfaces in Java 8

 The getDefaultNumber( ) method can be called,


as shown here:
int defNum = MyIF.getDefaultNumber();
Stack Interface Example
Interface Example
Packages
 Packages are containers for classes.
 They are used to keep the class name space
compartmentalized.
 You also need some way to be assured that the

name you choose for a class will be reasonably


unique and not collide with class names chosen
by other programmers.
 The package is both a naming and a visibility
control mechanism.
Defining a Package
 To create a package is quite easy: simply
include a package command as the first
statement in a Java source file.
 The package statement defines a name space in

which classes are stored.


 If you omit the package statement, the class

names are put into the default package, which


has no name.
 This is the general form of the package
statement: package pkg;
Defining a Package
 Java uses file system directories to store
packages.
 For example, the .class files for any classes you

declare to be part of MyPackage must be stored


in a directory called MyPackage.
 More than one file can include the same

package statement. The package statement


simply specifies to which package the classes
defined in a file belong.
 You can create a hierarchy of packages.
Defining a Package
 To do so, simply separate each package name
from the one above it by use of a period.
 The general form of a multileveled package
statement is shown here:
 package pkg1[.pkg2[.pkg3]];

 A package hierarchy must be reflected in the


file system of your Java development system.
 For example, a package declared as package
java.awt.image; needs to be stored in
java\awt\image in a Windows environment.
Advantages of Packages
 Advantages of using a package in Java
 Reusability

 BetterOrganization
 No Name Conflicts

 Access Protection
Importing a Packages
 import pkg1 [.pkg2].(classname | *);
 Once imported, a class can be referred to
directly, using only its name.
 Note: Import statement is optional.

 Any place you use a class name, you can

use its fully qualified name, which


includes its full package hierarchy
Importing a Packages
import java.util.*;
class MyDate extends Date {
}

 The same example without the import


statement looks like this:

class MyDate extends java.util.Date {


}
Importing a Packages
 All of the standard Java classes included with
Java are stored in a package called java.
 The basic language functions are stored in a

package inside of the java package called


java.lang.
 The package java.lang, it is implicitly

imported by the compiler for all programs


Access Protection
 Java addresses four categories of visibility for
class members:
 Subclasses in the same package
 Non-subclasses in the same package

 Subclasses in different packages

 Classes that are neither in the same package nor


subclasses
 The three access modifiers, private, public,
and protected.
Access Protection
 Anything declared public can be accessed from
anywhere.
 Anything declared private cannot be seen
outside of its class.
 When a member does not have an explicit
access specification, it is visible to subclasses
as well as to other classes in the same package.
This is the default access.
 If you want to allow an element to be seen
outside your current package, but only to
classes that subclass your class directly, then
declare that element protected.
Access Protection
Package Example
Package Example
Package Example
 Call this file Balance.java and put it in a
directory called MyPack.
 Next, compile the file.

 Make sure that the resulting .class file is also in

the MyPack directory.


 Compile and Run TestBalance.java file.

 javac TestBalance.java

 java TestBalance
Exception Handling
 Exceptions are abnormal conditions which
change the normal flow of execution of a
program.

 Exceptions are used for signaling erroneous


(exceptional) conditions which occur during the
run time processing.

 In Java, Exception is an object that describes


an exceptional condition that has occurred in
a piece of code.
Exception Handling
 When an exceptional condition arises, an object
representing that exception is created and
thrown in the method that caused the error.

 Exceptions can be generated by the Java run-


time system, or they can be manually generated
by your code.
Throwable
Throwable
 All exception types are subclasses of the built-
in class Throwable.
 Exception is a subclass of Throwable.

 Exception class is used for catching exceptional

conditions arise in the user programs.


 This is also the class that you will subclass to
create your own custom exception types.
 There is an important subclass of Exception,

called RuntimeException.
Throwable
 Error is another subclass of Throwable.
 These are not exceptions at all, but problems
that arise beyond the control of the user or the
programmer.
 Errors are typically ignored in your code
because you can rarely do anything about an
error.
 For example, if a stack overflow occurs, an
error will arise.
Types of Exception
 Two Types
1. Checked Exception
2. Unchecked Exception

 Checked Exception: A checked exception is an


exception that occurs at the compile time.
 Example : File that need to be opened is not

found. These type of exceptions must be


checked at compile time.
Types of Exception
 Unchecked Exception: An unchecked
exception is an exception that occurs at the
time of execution. These are also called
as Runtime Exceptions.

 These include programming bugs, such as logic


errors or improper use of an API.
 Runtime exceptions are ignored at the time of
compilation.
Exception Handling Mechanism
Exception Handling Mechanism
Exception Handling Mechanism
 To make use of Exception Handling we have to
use mainly 5 keywords.
1. try
2. catch
3. throw
4. throws
5. finally
Exception Handling Mechanism
 try:
 It
is a block of executable statements which may or
may not throw an expression.

 catch:
 Itis a method which is used to catch the Exception
arises in the try block and which is thrown by Java
Runtime Environment(JRE).
Exception Handling Mechanism
 throw:
 To manually throw an exception, use the keyword
throw.
 throws:
 Any exception that is thrown out of a method must
be specified as such by a throws clause.
 finally:
 Any code that absolutely must be executed after a
try block completes is put in a finally block.
Exception Handling Mechanism
Exception Handling Mechanism
 Note:
1. try must be followed by catch
2. try & catch must be perfect pairs.
3. A try can be followed by multiple catches.
Exception Handling Mechanism
Multiple Catch Statements
Exception Handling Mechanism
 When you use multiple catch statements,
exception subclasses must come before any of
their super classes.
 This is because a catch statement that uses a
superclass will catch exceptions of that type
plus any of its subclasses.
 Thus, a subclass would never be reached if it
came after its superclass.
 In Java, unreachable code is an error.
Exception Handling Mechanism
Nested try Statements
Nested try Statements
Throw
 Normally JRE will identify the Exception and
throw the Exception but as a developer if you
want to throw manually you have to use
:throw” or “throws”.
 “throw” is to throw Exception manually in the

“body level”.

 General form:
 throw ThrowableInstance;
Throw
Throws
 If a method is capable of causing an exception that
it does not handle, it must specify this behavior so
that callers of the method can guard themselves
against that exception.
 Including a throws clause in the method’s
declaration.
 A throws clause lists the types of exceptions that a
method might throw.
 This is necessary for all exceptions, except those of
type Error or RuntimeException, or any of their
subclasses.
Throws
finally
 When exceptions are thrown, execution in a
method takes a rather abrupt, nonlinear path
that alters the normal flow through the method.
 This could be a problem in some methods.

 For example, if a method opens a file upon


entry and closes it upon exit, then you will not
want the code that closes the file to be
bypassed by the exception-handling
mechanism.
finally
 The finally keyword is designed to address this
contingency.
 finally creates a block of code that will be

executed after a try /catch block has completed


and before the code following the try/catch
block.
 The finally block will execute whether or not

an exception is thrown.
finally
 If an exception is thrown, the finally block will
execute even if no catch statement matches the
exception.
 Any time a method is about to return to the

caller from inside a try/catch block, via an


uncaught exception or an explicit return
statement, the finally clause is also executed.
finally
finally
Java’s Built-in Exceptions
 Java defines several exception classes inside
the standard package java.lang.
 Unchecked exception or RuntimeException

need not be included in the method’s throws


list.
 Compiler does not check to see if a method

handles or throws these exceptions.


 Checked exception must be included in the
method’s throws list.
Java’s Unchecked RuntimeException
Subclasses in java.lang
Java’s Checked Exceptions in
java.lang
Creating Your Own Exception
Subclasses
 Java’s built-in exceptions handle most common
errors.
 You need to create your own exception types to

handle situations specific to the applications.


 Define a subclass of Exception.

 Your subclasses don’t need to actually


implement anything.
 The Exception class does not define any

methods of its own.


 It inherits those methods from Throwable.
Creating Your Own
Exception Subclasses
 Exception defines four public constructors.
 Exception( ): This creates an exception that has no
description.
 Exception(String msg): This form lets you specify a
description of the exception.
 Exception(Throwable cause): Constructs a new
exception with the specified cause and a detailed
message.
 Exception(String message, Throwable cause):
Constructs a new exception with the specified detail
message and cause.
Creating Your Own Exception
Subclasses
Creating Your Own Exception
Subclasses
Custom Exception Example
Custom Exception Example
Chained Exception
 The chained exception feature allows you to
associate another exception with an exception.
 This second exception describes the cause of

the first exception


 For example, imagine a situation in which a
method throws an ArithmeticException
because of an attempt to divide by zero.
 However, the actual cause of the problem was
that an I/O error occurred, which caused the
divisor to be set improperly.
Chained Exception
 Although the method must certainly throw an
ArithmeticException, since that is the error that
occurred, you might also want to let the calling code
know that the underlying cause was an I/O error.
 To allow chained exceptions, two constructors and two
methods were added to Throwable.
 Throwable(Throwable causeExc): causeExc is the
exception that causes the current exception.
 Throwable(String msg, Throwable causeExc): Specify a
description at the same time that you specify a cause
exception.
Chained Exception
 The chained exception methods supported by
Throwable are getCause() & initCause().

 Throwable getCause(): Returns the exception


that underlies the current exception.

 Throwable initCause(Throwable causeExc):


Associates causeExc with the invoking
exception and returns a reference to the
exception
Chained Exception
 The cause exception can be set only once.
 You can call initCause( ) only once for each
exception object.
 If the cause exception was set by a constructor,

then you can’t set it again using initCause( ).


 In general, initCause( ) is used to set a cause
for legacy exception classes that don’t support
the two additional constructors.
Chained Exceptions
Chained Exceptions
New Exception Features in JDK7

 Three new features are added in JDK 7.


1. try-with-resources
2. multi-catch
3. final rethrow
New Exception Features in JDK7
 try-with-resources: It is an exception handling
mechanism that can automatically close
resources when you are done with them.
 You must open and use the resource within a
Java try-with-resources block.
 When the execution leaves the try-with-
resources block, any resource opened within
the try-with-resources block is automatically
closed.
 try(FileInputStream input = new
FileInputStream("file.txt")) {….}
New Exception Features in JDK7

 multi-catch : The multi-catch feature allows


two or more exceptions to be caught by the
same catch clause.
New Exception Features in JDK7

 final rethrow : Often times you want to


rethrow caught exception to propagate it.
 Then you use throw mechanism and declare

your method signature as throwing certain


exception type.
THANK YOU

You might also like