Package
In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as a
folder in a file directory.
We use the packages to avoid naming conflicts and to organize project-related classes, interfaces,
and sub-packages into a bundle.
In java, the packages have divided into two types.
Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-defined
classes, interfaces, and sub-packages. The built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.
We need to import the built-in packages to use them in our program. To import a package, we
use the import statement.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own
packages.
Definig a Package in java
We use the package keyword to create or define a package in java programming language.
Syntax
package packageName;
🔔 The package statement must be the first statement in the program.
🔔 The package name must be a single word.
Let's consider the following code to create a user-defined package pack.
package pack;
public class welcome
{
public void display()
{
[Link]("Hi");
}
}
Now, save the above code in a file [Link], and compile it using the following command.
Before that you must create a directory pack.
javac [Link]
In java, the import keyword used to import built-in and user-defined packages. When a package
has imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
🔔 Using one import statement, we may import only one package or a class.
🔔 Using an import statement, we can not import a class directly, but it must be a part of a
package.
🔔 A program may contain any number of import statements.
Importing specific class
Using an importing statement, we can import a specific class. The following syntax is employed
to import a specific class.
Syntax
import [Link];
Example:
import pack.*;
public class welcome1
{
public static void main(String args[])
{
welcome w= new welcome();
[Link]();
}
}
Now come out from the pack directory and compile the above file from the current directory.
Javac [Link]
After successful complilation now run the code with the following command
Java welcome1
Output
Hi
In the above example it imports the package pack and executed function which is defined in the
package class i.e welcome.
🔔 The import statement imports only classes of the package, but not sub-packages and its
classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and
sub-package.
Consider the following import statement.
importnd [Link].*;
The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
Interface
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the interface
has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only
one interface, but a class may implement any number of interfaces.
🔔 An interface is a container of abstract methods and static final variables.
🔔 An interface, implemented by a class. (class implements interface).
🔔 An interface may extend another interface. (Interface extends Interface).
🔔 An interface never implements another interface, or class.
🔔 A class may implement any number of interfaces.
🔔 We can not instantiate an interface.
🔔 Specifying the keyword abstract for interface methods is optional, it automatically added.
🔔 All the members of an interface are public by default.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){[Link]("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. [Link]();
10. }
11. }
Output:
Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. [Link]();
14. [Link]();
15. }
16. }
17.
Output:Hello
Welcome
Variables in interface
In java, an interface is a completely abstract class. An interface is a container of abstract methods
and static final variables. The interface contains the static final variables. The variables defined
in an interface can not be modified by the class that implements the interface, but it may use as it
defined in the interface.
🔔 The variable in an interface is public, static, and final by default.
🔔 If any variable in an interface is defined without public, static, and final keywords then, the
compiler automatically adds the same.
🔔 No access modifier is allowed except the public for interface variables.
🔔 Every variable of an interface must be initialized in the interface itself.
🔔 The class that implements an interface can not modify the interface variable, but it may use as
it defined in the interface.
Let's look at an example code to illustrate variables in an interface.
When we run the above program, it produce the following output.
Extending interfaces.
In java, an interface can extend another interface. When an interface wants to extend another
interface, it uses the keyword extends. The interface that extends another interface has its own
members and all the members defined in its parent interface too. The class which implements a
child interface needs to provide code for the methods defined in both child and parent interfaces,
otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods defined in
both child and parent interfaces.
Let's look at an example code to illustrate extending an interface.
When we run the above program, it produce the following output.
Exception Handling
An exception in java programming is an abnormal situation that is araised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception occurs,
the program execution gets terminated, and the system generates an error. We use the exception
handling mechanism to avoid abnormal termination of program execution
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception handling
mechanism.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.
When we try to open a file that does not exist may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may lead to an
exception.
When we try to access the memory beyond the allocated range may lead to an exception.
The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
Checked Exception - An exception that is checked by the compiler at the time of
compilation is called a checked exception.
Unchecked Exception - An exception that can not be caught by the compiler but occurrs
at the time of program execution is called an unchecked exception.
In java, the exception handling mechanism uses five keywords namely try, catch, finally, throw,
and throws.
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
🔔 In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
When we run the above program, it produces the following output.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use of
resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
🔔 In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
When we run the above program, it produces the following output.
try and catch
In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurrence of an
exception. The keyword catch is used to define a block of code that handles the exception
occurred in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but automatically
caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
cannot use try without at least one catch, and catch without try is not allowed.
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Consider the following example code to illustrate try and catch blocks in Java.
When we run the above code, it produce the following output.
In the above example code, when an exception occurs in the try block the execution control
transferred to the catch block and the catch block handles it.
Multiple catch clauses
In java programming language, a try block may has one or more number of catch blocks. That
means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multiple catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
🔔 The try block generates only one exception at a time, and at a time only one catch block is
executed.
🔔 When there are multiple catch blocks, the order of catch blocks must be from the most specific
exception handler to most general.
🔔 The catch block with Exception class handler must be defined at the last.
Let's look at the following example Java code to illustrate multiple catch clauses.
When we run the above code, it produce the following output.
Nested try statements
The java allows writing a try statement inside another try statement. A try block within another
try block is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch blocks.
Let's look at the following example Java code to illustrate nested try statements.
When we run the above code, it produce the following output.
🔔 In case of nested try blocks, if an exception occured in the inner try block and it's catch blocks
are unable to handle it then it transfers the control to the outer try's catch block to handle it.
throw, throws and finally
In java, the keywords throw, throws, and finally are used in the exception handling concept. Let's
look at each of these keywords.
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
🔔 Using throw keyword only object of Throwable class or its sub classes can be thrown.
🔔 Using throw keyword only one exception can be thrown.
🔔 The throw keyword must followed by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instance must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
When we run the above code, it produce the following output.
throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
🔔 When a method throws an exception, we must put the calling statement of method in try-catch
block.
Let's look at the following example Java code to illustrate throws keyword.
When we run the above code, it produces the following output.
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurrence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
🔔 Only one finally block is allowed for each try block.
🔔 Use of finally block is optional.
Let's look at the following example Java code to illustrate throws keyword.
When we run the above code, it produce the following output.
Java programming language allow us to create our own exception classes which are basically
subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in Exception class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
Let's look at the following Java code that illustrates the creation of user-defined exception.
When we run this code, it produces the following output.
Program:
class AgebelowException extends RuntimeException
{ public String toString()
return "you are not eligible to add voter list ";
class Voter
{ void check (int Age)
if (Age<18)
throw new AgebelowException();
else
[Link]("you are eligible");
class Voterm
public static void main(String args[])
Voter V=new Voter();
Try
[Link](19);
catch(AgebelowException u)
[Link]("check"+u);
Output:
You are eligible