[go: up one dir, main page]

0% found this document useful (0 votes)
25 views31 pages

Unit 4

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

Unit 4

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

UNIT-4

1. A java package is a group of similar types of classes, interfaces and sub-packages.

2. Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

These packages consist of many classes which are a part of Java API.Some of the
commonly usedbuilt-inpackagesare:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types,mathoperations).Thispackageisautomaticallyimported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.2) Java package provides access protection.3) Java package removes naming
collision.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.* :If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
S. No. PATH CLASSPATH

An environment variable is used by


1. An environment variable is used by the
the operating system to find the
Java compiler to find the path of classes.
executable files.

PATH setting up an environment


Classpath setting up the environment for
2. for the operating system. Operating
Java. Java will use to find compiled
System will look in this PATH for
classes.
executables.

3. Refers to the operating system. Refers to the Developing Environment.

In classpath, we must place .\lib\jar file


4. In path variable, we must place .\
or directory path in which .java file is
bin folder path
available.

5. PATH is used by CMD prompt to CLASSPATH is used by the compiler


find binary files. and JVM to find library files.

Packages in java SE
The SE stands for Java Standard Edition is a computing platform in which we can
execute software, and it can be used for development and deployment of portable code for
desktop and server environments.

It is the core Java programming platform and provides all the libraries and APIs such
as java.lang, java.io, java.math, java.net, java.util etc.

The following are the few APIs which Java SE has -

o Applet- An applet is a small application, especially a utility program performing one


or a few simple functions. This API provides the classes necessary to create an applet.
The applet framework contains two entities. One is applet and the other is applet
context. The applet is an embeddable window with a few extra methods which the
applet context uses to initialize, start and stop the applet.
o AWT- AWT stands for Abstract window toolkit. This package contains all the classes
for creating a user interface and for painting graphics and images. Any UI object like
button and scrollbar is called as a component.
o RMI- RMI stands for Remote Method Invocation enables the programmer to create
distributed Java technology-based to Java technology-based application. RMI uses
object serialization to marshal and unmarshal parameters and does not shorten types.
o JDBC- It stands for Java Database Connectivity. It allows you to fetch data from any
data source be its relational database, be it a spreadsheet, be it flat file.
o Swing- Swing provides a set of 'lightweight' components mainly used for graphical
user interface enhancement. All swing components and related classes should be
accessed on the dispatching thread.
o Collections- Collection refers to a group of objects, known as its elements. There are
many methods in the collections Framework interface which depend on the equals
method. For example- the contains(Object o) method says that it will return true if the
collection contains an element which satisfies the condition that (o==null ? e==null:
o.equals(e))
o xml binding- It provides a run-time binding framework for client-side user
application allowing the user to Marshall, unmarshal, and validation capabilities.
JAXBContext is the client-entry point to the runtime binding framework.
o JavaFX (Merged to Java SE 8)- This contains several packages within it like
javafx.animation(provides set of classes for ease of animation),
javafx.application(provides set of classes for application life-cycle classes ) and
javafx.beans() etc.

java.lang package and its classes


It Provides classes that are fundamental to the design of the Java programming
language. The most important classes are Object, which is the root of the class hierarchy, and
Class, instances of which represent classes at run time.
Following are the Important Classes in Java.lang package :
1. Boolean: The Boolean class wraps a value of the primitive type boolean in an
object.
2. Byte: The Byte class wraps a value of primitive type byte in an object.
3. Character – Set 1, Set 2: The Character class wraps a value of the primitive type
char in an object.
4. Character.Subset: Instances of this class represent particular subsets of the
Unicode character set.
5. Character.UnicodeBlock: A family of character subsets representing the
character blocks in the Unicode specification.
6. Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces
in a running Java application.
7. ClassLoader: A class loader is an object that is responsible for loading classes.
8. ClassValue: Lazily associate a computed value with (potentially) every type.
9. Compiler: The Compiler class is provided to support Java-to-native-code
compilers and related services.
10. Double: The Double class wraps a value of the primitive type double in an
object.
11. Enum: This is the common base class of all Java language enumeration types.
12. Float: The Float class wraps a value of primitive type float in an object.
13. InheritableThreadLocal: This class extends ThreadLocal to provide inheritance
of values from parent thread to child thread: when a child thread is created, the
child receives initial values for all inheritable thread-local variables for which
the parent has values.
14. Integer :The Integer class wraps a value of the primitive type int in an object.
15. Long: The Long class wraps a value of the primitive type long in an object.
16. Math – Set 1, Set 2: The class Math contains methods for performing basic
numeric operations such as the elementary exponential, logarithm, square root,
and trigonometric functions.
17. Number: The abstract class Number is the superclass of classes BigDecimal,
BigInteger, Byte, Double, Float, Integer, Long, and Short.
18. Object: Class Object is the root of the class hierarchy.

Enumeration in java : An enum is a special "class" that represents a group


of constants (unchangeable variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and separate
the constants with a comma. Note that they should be in uppercase letters:

Java Enums can be thought of as classes which have a fixed set of constants (a
variable that does not change). The Java enum constants are static and final implicitly. It is
available since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java

Simple Example of Java Enum


1. class EnumExample1{
2. //defining the enum inside the class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //main method
5. public static void main(String[] args) {
6. //traversing the enum
7. for (Season s : Season.values())
8. System.out.println(s);
9. }}
Class Math

Java Math class: Java Math class provides several methods to work on math calculations
like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7. // return the maximum of two numbers
8. System.out.println("Maximum number of x and y is: " +Math.max(x, y));
9. // return the square root of y
10. System.out.println("Square root of y is: " + Math.sqrt(y));
11. //returns 28 power of 4 i.e. 28*28*28*28
12. System.out.println("Power of x and y is: " + Math.pow(x, y));
13. // return the logarithm of given value
14. System.out.println("Logarithm of x is: " + Math.log(x));
15. System.out.println("Logarithm of y is: " + Math.log(y));
16. // return the logarithm of given value when base is 10
17. System.out.println("log10 of x is: " + Math.log10(x));
18. System.out.println("log10 of y is: " + Math.log10(y));
19. // return the log of x + 1
20. System.out.println("log1p of x is: " +Math.log1p(x));
21. // return a power of 2
22. System.out.println("exp of a is: " +Math.exp(x));
23. // return (a power of 2)-1
24. System.out.println("expm1 of a is: " +Math.expm1(x));
25. }
Wrapper classes
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Autoboxing: The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer,
long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.

1. //Java program to convert primitive into objects


2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
9. System.out.println(a+" "+i+" "+j);
10. }}
Unboxing: The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing.

1. /Java program to convert object into primitives


2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9. System.out.println(a+" "+i+" "+j);
10. }}

Java Util classes and interfaces

Class Description

AbstractCollection<E> The class is used for providing a rough


implementation of the Collection interface.
The class is declared as:
public abstract class AbstractCollection<E>
extends Object
implements Collection<E>
The class methods are extended from the
Object class.

AbstractList<E> The class is used for providing a rough


implementation of the List interface. The
class is declared as:
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
The class methods are extended from the
AbstractCollection<E> class.

AbstractMap<K,V> The class is used for providing a rough


implementation of the List interface. The
class is declared as:
public abstract class AbstractMap<K,V>
extends Object
implements Map<K,V>
The class methods are extended from the
Object class.
AbstractMap.SimpleEntry<K,V> The class instance is used for maintaining
the value and key. The class is declared as:
public static class
AbstractMap.SimpleEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the
Object class.

AbstractMap.SimpleImmutableEntry<K,V The class instance is used for maintaining


> the value and key which is immutable. The
class is declared as:
public static class
AbstractMap.SimpleImmutableEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the
Object class.

AbstractQueue<E> The class is used for providing a rough


implementation of the Queue interface. The
class is declared as:
public abstract class AbstractQueue<E>
extends AbstractCollection<E>
implements Queue<E>
The class methods are extended from the
AbstractCollection class.

Formatter class
The java.util.Formatter class provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.

1 Formatter()
This constructor constructs a new formatter.

Formatter(Appendable a)
2 This constructor constructs a new formatter with the specified
destination.

Formatter(Appendable a, Locale l)
3 This constructor constructs a new formatter with the specified destination
and locale.

4 Formatter(File file)
This constructor constructs a new formatter with the specified file.

5 Formatter(File file, String csn)


This constructor constructs a new formatter with the specified file and
charset.

Formatter(File file, String csn, Locale l)


6 This constructor constructs a new formatter with the specified file,
charset, and locale.

7 Formatter(Locale l)
This constructor constructs a new formatter with the specified locale.

Formatter(OutputStream os)
8 This constructor constructs a new formatter with the specified output
stream.

Formatter(OutputStream os, String csn)


9 This constructor constructs a new formatter with the specified output
stream and charset.

Formatter(OutputStream os, String csn, Locale l)


10 This constructor constructs a new formatter with the specified output
stream, charset, and locale.

Formatter(PrintStream ps)
11 This constructor constructs a new formatter with the specified print
stream.

12 Formatter(String fileName)
This constructor constructs a new formatter with the specified file name.

Formatter(String fileName, String csn)


13 This constructor constructs a new formatter with the specified file name
and charset.

Formatter(String fileName, String csn, Locale l)


14 This constructor constructs a new formatter with the specified file name,
charset, and locale.

Class methods

void close()
1
This method closes this formatter.

void flush()
2
This method flushes this formatter.

3 Formatter format(Locale l, String format, Object... args)


This method writes a formatted string to this object's destination using the
specified locale, format string, and arguments.

Formatter format(String format, Object... args)


4
This method writes a formatted string to this object's destination using the
specified format string and arguments.

IOException ioException()
5
This method returns the IOException last thrown by this formatter's
Appendable.

Locale locale()
6
This method returns the locale set by the construction of this formatter.

Appendable out()
7
This method returns the destination for the output.

String toString()
8
This method returns the result of invoking toString() on the destination for the
output.

Java Random class: Java Random class is used to generate a stream of pseudorandom
numbers. The algorithms implemented by Random class use a protected utility method than
can supply up to 32 pseudorandomly generated bits on each invocation.

Methods

Methods Description

doubles() Returns an unlimited stream of pseudorandom double values.

ints() Returns an unlimited stream of pseudorandom int values.

longs() Returns an unlimited stream of pseudorandom long values.

next() Generates the next pseudorandom number.

nextBoolean() Returns the next uniformly distributed pseudorandom boolean value from the
random number generator's sequence

nextByte() Generates random bytes and puts them into a specified byte array.
nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0 from the
random number generator's sequence

nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0
and 1.0 from this random number generator's sequence

nextGaussian( Returns the next pseudorandom Gaussian double value with mean 0.0 and
) standard deviation 1.0 from this random number generator's sequence.

nextInt() Returns a uniformly distributed pseudorandom int value generated from this
random number generator's sequence

nextLong() Returns the next uniformly distributed pseudorandom long value from the
random number generator's sequence.

setSeed() Sets the seed of this random number generator using a single long seed.

Example:

1. import java.util.Random;
2. public class JavaRandomExample2 {
3. public static void main(String[] args) {
4. Random random = new Random();
5. //return the next pseudorandom integer value
6. System.out.println("Random Integer value : "+random.nextInt());
7. // setting seed
8. long seed =20;
9. random.setSeed(seed);
10. //value after setting seed
11. System.out.println("Seed value : "+random.nextInt());
12. //return the next pseudorandom long value
13. Long val = random.nextLong();
14. System.out.println("Random Long value : "+val);
15. }
16. }

Time package
Java Dates
Java does not have a built-in Date class, but we can import the java.time package to work
with the date and time API. The package includes many date and time classes. For example:

Class Description

LocalDate Represents a date (year, month, day (yyyy-MM-dd))

LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-


ns))

LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)

DateTimeFormatter Formatter for displaying and parsing date-time objects

Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method:

import java.time.LocalDate; // import the LocalDate class

public class Main {

public static void main(String[] args) {

LocalDate myObj = LocalDate.now(); // Create a date object

System.out.println(myObj); // Display the current date

Display Current Time

To display the current time (hour, minute, second, and nanoseconds), import
the java.time.LocalTime class, and use its now() method:

Example

import java.time.LocalTime; // import the LocalTime class


public class Main {

public static void main(String[] args) {

LocalTime myObj = LocalTime.now();

System.out.println(myObj);

Display Current Date and Time

To display the current date and time, import the java.time.LocalDateTime class, and use
its now() method:

Example

import java.time.LocalDateTime; // import the LocalDateTime class

public class Main {

public static void main(String[] args) {

LocalDateTime myObj = LocalDateTime.now();

System.out.println(myObj);

Temporal adjusters classes


TemporalAdjusters Class in Java provides Adjusters, which are a key tool for modifying
temporal objects
The following two ways of using TemporalAdjuster are equivalent, but it is recommended
to use the second approach, as it is cleaner and readable
temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);
Examples include an adjuster that sets the date like “Second Saturday of the Month” or
“Next Tuesday”, or one that sets the date to the last day of the month.

Method Description

dayOfWeekInMonth(int ordinal, This method is used to


DayOfWeek dayOfWeek) return the day-of-week in
Method Description

month adjuster, which


returns a new date object
within the same month
with the ordinal day-of-
week.

This method is used to


return the “first day of
month” adjuster, which
firstDayOfMonth()
returns a new date set to
the first day of the current
month.

This method is used to


return the “first day of
next month” adjuster,
firstDayOfNextMonth()
which returns a new date
set to the first day of the
next month.

This method is used to


return the “first day of
next year” adjuster, which
firstDayOfNextYear()
returns a new date set to
the first day of the next
year.

This method is used to


return the “first day of
year” adjuster, which
firstDayOfYear()
returns a new date set to
the first day of the current
year.

This method is used to


return the first in month
adjuster, which returns a
firstInMonth(DayOfWeek dayOfWeek)
new date in the same
month with the first
matching day-of-week.

This method is used to


lastDayOfMonth()
return the “last day of
Method Description

month” adjuster, which


returns a new date set to
the last day of the current
month.

This method is used to


return the “last day of
year” adjuster, which
lastDayOfYear()
returns a new date set to
the last day of the current
year.

This method is used to


return the last in month
adjuster, which returns a
lastInMonth(DayOfWeek dayOfWeek)
new date in the same
month with the last
matching day-of-week.

This method is used to


return the next day-of-
week adjuster, which
adjusts the date to the first
next(DayOfWeek dayOfWeek)
occurrence of the
specified day-of-week
after the date being
adjusted.

This method is used to


return the next-or-same
day-of-week adjuster,
which adjusts the date to
the first occurrence of the
nextOrSame(DayOfWeek dayOfWeek) specified day-of-week
after the date being
adjusted unless it is
already on that day in
which case the same
object is returned.

This method is used to


ofDateAdjuster(UnaryOperator<LocalDate> obtain a
dateBasedAdjuster) TemporalAdjuster that
wraps a date adjuster.
Method Description

This method is used to


return the previous day-
of-week adjuster, which
adjusts the date to the first
previous(DayOfWeek dayOfWeek)
occurrence of the
specified day-of-week
before the date being
adjusted.

This method is used to


return the previous-or-
same day-of-week
adjuster, which adjusts the
date to the first
occurrence of the
previousOrSame(DayOfWeek dayOfWeek)
specified day-of-week
before the date being
adjusted unless it is
already on that day in
which case the same
object is returned.

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

public class Java8Tester {


public static void main(String args[]) {
Java8Tester java8tester = new Java8Tester();
java8tester.testAdjusters();
}

public void testAdjusters() {


//Get the current date
LocalDate date1 = LocalDate.now();
System.out.println("Current date: " + date1);

//get the next tuesday


LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
System.out.println("Next Tuesday on : " + nextTuesday);
//get the second saturday of next month
LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);

LocalDate secondSaturday = firstInYear.with(


TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(
TemporalAdjusters.next(DayOfWeek.SATURDAY));
System.out.println("Second saturday on : " + secondSaturday);
}
}
Exception Handling: The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Difference between Error and Exception
 Error: An Error indicates a serious problem that a reasonable application should
not try to catch.
 Exception: Exception indicates conditions that a reasonable application might
try to catch.

Hierarchy of Java Exception classes

 The java.lang.Throwable class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table
describes each.

Keywor Description
d

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.

Java Exception Handling Exampl

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Throw and Throws


The throw and throws is the concept of exception handling where the throw keyword throw
the exception explicitly from a method or a block of code whereas the throws keyword is
used in signature of the method.

Basis of throw throws


Differences

1. Definition Java throw keyword Java throws keyword is


is used throw an used in the method
exception explicitly signature to declare an
in the code, inside exception which might
the function or the be thrown by the
block of code. function while the
execution of the code.

2. Type of exception Using Using throws


throw keyword, we can keyword, we can
only propagate declare both checked
unchecked exception and unchecked
i.e., the checked exceptions.
exception cannot be However, the throws
propagated using throw keyword can be used
only. to propagate checked
exceptions only.

3. Syntax The throw keyword The throws keyword is


is followed by an followed by class names
instance of of Exceptions to be
Exception to be thrown.
thrown.

4. Declaration throw is used within throws is used with the


the method. method signature.

5. Internal implementation We are allowed to We can declare multiple


throw only one exceptions using throws
exception at a time keyword that can be
i.e. we cannot throw thrown by the method.
multiple exceptions. For example, main()
throws IOException,
SQLException.

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate squa
re");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Java throws Example

TestThrows.java

1. public class TestThrows {


2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }

Java finally Example

Let's see the below example where the Java code throws an exception and the catch block
handles that exception. Later the finally block is executed after the try-catch block. Further,
the rest of the code is also executed normally.

FinallyExample.java

1. public class FinallyExample {


2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }

Multiple catch classes


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Class throwable
The Throwable class is the superclass of every error and exception in the Java language.
Only objects that are one of the subclasses this class are thrown by any “Java Virtual
Machine” or may be thrown by the Java throw statement.
Throwable class is the root class of Java Exception Hierarchy and is inherited by
two subclasses:
1.Exception
2.Error
The throwable class implements Serializable Interface and the direct known classes to
Throwable are Error and Exception.
Class MyThrowable extends Throwable{
//Here the user can create his own custom throwable
}
Class GFG{
Public void test() throws MyThrowable{
// the custom throwable created can be used as follows
throw new MyThrowable();
}
}
Public Constructors
1. Throwable(): It is a non-parameterized constructor which constructs a new
Throwable with null as its detailed message.
2. Throwable(String message): It is a parameterized constructor which constructs a
new Throwable with the specific detailed message.
3. Throwable(String message, Throwable cause): It is a parameterized constructor
which constructs a new Throwable with the specific detailed message and a
cause.
4. Throwable(Throwable cause): It is a parameterized constructor which constructs
a new Throwable with the specific cause and a detailed message of the cause by
converting the case to the String using toString() method.
Checked Exceptions in Java
These are the exceptions that are checked at compile time. If some code within a
method throws a checked exception, then the method must either handle the exception or it
must specify the exception using the throws keyword.
In checked exceptions, there are two types: fully checked and partially checked
exceptions. A fully checked exception is a checked exception where all its child classes are
also checked, like IOException, and InterruptedException.
A partially checked exception is a checked exception where some of its child
classes are unchecked, like an Exception.
Unchecked Exceptions in Java
These are the exceptions that are not checked at compile time. In C++, all
exceptions are unchecked, so it is not forced by the compiler’s to either handle or specify
the exception. It is up to the programmers to be civilized and specify or catch the
exceptions.
In Java, exceptions under Error and RuntimeException classes are unchecked
exceptions, everything else under throwable is checked.
Consider the following Java program. It compiles fine, but it
throws ArithmeticException when run. The compiler allows it to compile
because ArithmeticException is an unchecked exception.

Catching subclass exception


In any object-oriented programming language, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes. When a method in a subclass has the
same name, same parameters or signature, and same return type(or sub-type) as a method in
its super-class, then the method in the subclass is said to override the method in the super-
class.
Exception Handling with Method Overriding

When Exception handling is involved with Method overriding, ambiguity occurs.


The compiler gets confused as to which definition is to be followed.

1. If SuperClass doesn’t declare any exception and subclass declare checked exception.

// Java Program to Illustrate Exception Handling


// with Method Overriding
// Where SuperClass does not declare any exception and
// subclass declare checked exception

// Importing required classes


import java.io.*;

class SuperClass {

// SuperClass doesn't declare any exception


void method() {
System.out.println("SuperClass");
}
}
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {

// method() declaring Checked Exception IOException


void method() throws IOException {

// IOException is of type Checked Exception


// so the compiler will give Error

System.out.println("SubClass");
}

// Driver code
public static void main(String args[]) {
SuperClass s = new SubClass();
s.method();
}
}
Java Custom Exception :In Java, we can create our own exceptions that are derived classes
of the Exception class. Creating our own Exception is known as custom exception or user-
defined exception. Basically, Java custom exceptions are used to customize the exception
according to user need.
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10.
11. // class that uses custom exception InvalidAgeException
12. public class TestCustomException1
13. {
14.
15. // method to check the age
16. static void validate (int age) throws InvalidAgeException{
17. if(age < 18){
18.
19. // throw an object of user defined exception
20. throw new InvalidAgeException("age is not valid to vote");
21. }
22. else {
23. System.out.println("welcome to vote");
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45. }
Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.

Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

NestedTryBlock.java

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }
Rethrowing an exception

An exception can be rethrown in a catch block using throw keyword, if catch block is unable
to handle it. This process is called as re-throwing an exception.

You might also like