Abstract Class Interface: Types of Packages: Built-In and User Defined
Abstract Class Interface: Types of Packages: Built-In and User Defined
1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non- Interface has only static and final
static variables. variables.
4) Abstract class can provide the implementation of Interface can't provide the
interface. implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Built-in Package: Existing Java package for example java.lang, java.util etc.
User-defined-package: Java package created by user to categorize their project's
classes and interface.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
package mypack;
public class employee
{
statement;
}
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.
Additional points about package:
A package is always defined as a separate folder having the same name as the
package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package must be
declared public.
All classes within the package must have the package statement as its first line.
All classes of the package must be compiled before use (So that they are error free)
If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the
same package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time you
are accessing the class or the interface, which can look a little untidy if the package
name is long.
This is generally used when two packages have classes with same names. For
example: java.util and java.sql packages contain Date class.
Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:
Hello
If you import packagename.classname then only the class with name classname in the
package with name packagename will be available for use.
Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output:
Hello
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example :
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}
//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}
Output:
Hello
Points to remember
When a package name is not specified, the classes are defined into the default package (the
current working directory) and the package itself is given no name. That is why, you were
able to execute assignments earlier.
While creating a package, care should be taken that the statement for creating package must
be written before any other import statements.
// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;
Creating Packages
To make a class as part of a package, you have to include the package statement as the first
statement in the source file.
Example 1
We shall write a class called Circle in package com.yyy. It is a good practice to store the source
codes and the classes in separate directories, to facilitate the distribution of classes without the
source codes. Suppose that we save the source as d:\myJavaProject\src\com\yyy\Circle.java,
and the compiled class as d:\myJavaProject\classes\com\yyy\Circle.class. Let's write the
source as follows:
// d:\myJavaProject\src\com\yyy\Circle.java
package com.yyy;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
To compile the source using JDK, we need to use the -d option to specify the package base directory
of the compiled class d:\myJavaProject\classes as follows (-d defaulted to the current directory):
> javac -d d:\myJavaProject\classes d:\myJavaProject\src\com\yyy\Circle.java
d:> cd \myOtherProject
NOTES:
To compile the program, you specify the directory path using directory separator '\'.
To execute the class, you specify the fully-qualified class name using the dot '.'.
Alternatively, you can launch the class from any directory, provided that the $BASE_DIR is included in
the CLASSPATH environment variable. You can also use command-line option -classpath or -cp to
specify CLASSPATH used for this command:
> java –cp $BASE_DIR com.zzz.project1.subproject2.MyClass3
Suppose that you decided to keep the source files and classes in separate directories (for distribution
of classes without the sources), and the directory structure of your source files and classes is as
follows:
To compile the source files and place the classes in the desired directory, you can use the " -d" (for
destination) command-line option of the Java compiler, which specifies the location of the compiled
classes. You also need to specify the CLASSPATH of the classes, as MyClass3 uses MyClass4, as
follows:
> cd $SRC_BASE_DIR\zzz\project1\subproject2
> javac –d $CLASS_BASE_DIR -classpath .;$CLASS_BASE_DIR *.java
// try omitting the classpath and compile just MyClass3 which uses MyClass4
> javac –d $CLASS_BASE_DIR MyClass3.java
The sub-directory structure corresponding to the package name for the classes will be created
automatically if it does not already exist. In summary, during the compilation, you need to set both -
d (for destination of the classes), and -classpath (if one class references other classes in the
package).
In the above example, the source directory $SRC_BASE_DIR is "c:\javaproject\src" and the classes'
base directory $CLASS_BASE_DIR is "c:\javaproject\classes"
To execute the MyClass3:
> cd $CLASS_BASE_DIR
> java com.zzz.project1.subproject2.MyClass3
Using IDE
Managing packages and CLASSPATH yourself with obly JDK is troublesome. IDE such as Eclipses and
NetBeans could manage the packages and CLASSPATH for you!!
The Default Package
Every Java class must belong to a package. You can explicitly name the package by providing
a package statement in the beginning of the source file. If the package statement is omitted, the
class belongs to the so-called default package, with no sub-directory structure. Use of default
package is not recommended other than writing toy program and for quick testing.
CLASSPATH - For Locating Classes
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all
the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java
program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is
used by the CMD shell to find the executable programs.
CLASSPATH can be set in one of the following ways:
1. CLASSPATH can be set permanently in the environment: In Windows, choose control panel ⇒
System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables" (for all the users)
or "User Variables" (only the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists)
or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the required directories and JAR
files (separated by semicolons) as the value (e.g.,
".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need
to include the current working directory (denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
3. > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,
5. > java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the
program. When an exception occurs program execution gets terminated. In such
cases we get a system generated error message. The good thing about
exceptions is that they can be handled in Java. By handling the exceptions we
can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
Exception Handling
If an exception occurs, which has not been handled by programmer then
program execution gets terminated and a system generated error message is
shown to the user. For example look at the system generated exception below:
An exception generated by the system is given below
Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when
you try to divide a number by zero this exception occurs because dividing a
number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an
array out of its bounds, for example array size is 5 (which means it has five
elements) and you are trying to access the 10th element.
Errors Exceptions
Errors in java are of type java.lang.Error. Exceptions in java are of type java.lang.Exception.
Errors happen at run time. They will not be known to unchecked exceptions are not known to compiler
Examples :
java.lang.OutOfMemoryError NullPointerException
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions
as the compiler checks them during compilation to see whether the programmer
has handled them or not. If these exceptions are not handled/declared in the
program, you will get compilation error. For example, SQLException,
IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time so compiler does not check whether
the programmer has handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe exit. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
Compiler will never force you to catch such exception or force you to declare it in
the method using throws keyword.
Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block. A try block must be followed by catch blocks or
finally block or both.
Catch block
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You
can catch different exceptions in different catch blocks. When an exception
occurs in try block, the corresponding catch block that handles that particular
exception executes. For example if an arithmetic exception occurs in try block
then the statements enclosed in catch block for arithmetic exception executes.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic
that can handle all. This is because in generic exception handler you can display
a message but you are not sure for which type of exception it may trigger so it
will display the same message for all the exceptions and user may not be able to
understand which exception occurred. Thats the reason you should place is at
the end of all the specific exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely
ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException
catch(NullPointerException e) is a catch block that can handle
NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered
it in separate tutorials: user defined exception, throws keyword, throw vs throws.
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks
executes sequentially when an exception occurs in try block. Which means if you
put the last catch block ( catch(Exception e)) at the first place, just after try block
then in case of any exception this block will execute as it can handle
all exceptions. This catch block should be placed at the last to avoid such
situations.
Finally block
I have covered this in a separate tutorial here: java finally block. For now you just
need to know that this block executes whether an exception occurs or not. You
should place those statements in finally blocks, that must execute whether
exception occurs or not.
When a try catch block is present in another try block then it is called the nested
try catch block. Each time a try block does not have a catch handler for a
particular exception, then the catch blocks of parent try block are inspected for
that exception, if match is found that that catch block executes.
If neither catch block nor parent catch block handles exception then the system
generated message would be shown for the exception, similar to what we see
when we don’t handle exception.
Lets see the syntax first then we will discuss this with an example.
Syntax of Nested try Catch
....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Nested Try Catch Example
Here we have deep (two level) nesting which means we have a try-catch block
inside a nested try block. To make you understand better I have given the names
to each try block in comments like try-block2, try-block3 etc.
This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside
main try-block, you can say that the main try-block is a grand parent of the try-
block3. Refer the explanation which is given at the end of this code.
class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:
Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..
This is another example that shows how the nested try block works. You can see
that there are two try-catch block inside main try block’s body. I’ve marked them
as block 1 and block 2 in above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException,
since the catch of block1 is handling ArithmeticException "Exception: e1" displayed.
The important point to note here is that whenever the child catch blocks are not
handling any exception, the jumps to the parent catch blocks, if the exception is
not handled there as well then the program will terminate abruptly showing
system generated message.
There are two types of exceptions: checked exception and unchecked exception.
In this guide, we will discuss them. The main difference between checked and
unchecked exception is that the checked exceptions are checked at compile-
time while unchecked exceptions are checked at runtime.
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception
*/
fis = new FileInputStream("B:/myfile.txt");
int k;
import java.io.*;
class Example {
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("B:/myfile.txt");
int k;
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
try{
fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe){
System.out.println("The specified file is not " +
"present at the given path");
}
int k;
try{
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}catch(IOException ioe){
System.out.println("I/O error occurred: "+ioe);
}
}
}
This code will run fine and will display the file content.
SQLException
IOException
ClassNotFoundException
InvocationTargetException
What are Unchecked exceptions?
Unchecked exceptions are not checked at compile time. It means if your program
is throwing an unchecked exception and even if you didn’t handle/declare that
exception, the program won’t give a compilation error. Most of the times these
exception occurs due to the bad data provided by user during the user-program
interaction. It is up to the programmer to judge the conditions in advance, that
can cause such exceptions and handle them appropriately. All Unchecked
exceptions are direct sub classes of RuntimeException class.
class Example {
public static void main(String args[])
{
int arr[] ={1,2,3,4,5};
/* My array has only 5 elements but we are trying to
* display the value of 8th element. It should throw
* ArrayIndexOutOfBoundsException
*/
System.out.println(arr[7]);
}
}
This code would also compile successfully since ArrayIndexOutOfBoundsException is
also an unchecked exception.
Note: It doesn’t mean that compiler is not checking these exceptions so we
shouldn’t handle them. In fact we should handle them more carefully. For e.g. In
the above example there should be a exception message to user that they are
trying to display a value which doesn’t exist in array so that user would be able to
correct the issue.
class Example {
public static void main(String args[]) {
try{
int arr[] ={1,2,3,4,5};
System.out.println(arr[7]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("The specified index does not exist " +
"in array. Please correct the error.");
}
}
}
Output:
The specified index does not exist in array. Please correct the error.
Here are the few unchecked exception classes:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException
NumberFormatException
class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
e.printStackTrace();
}
}
}
Output:
class Example1{
void method1() throws ArithmeticException{
throw new ArithmeticException("Calculation error");
}
void method2() throws ArithmeticException{
method1();
}
void method3(){
try{
method2();
}
catch(ArithmeticException e){
System.out.println("ArithmeticException handled");
}
}
public static void main(String args[]){
Example1 obj=new Example1();
obj.method3();
System.out.println("End Of Program");
}
}
Output:
ArithmeticException handled
End Of Program
Java finally block when return statement is
encountered
BY CHAITANYA SINGH | FILED UNDER: EXCEPTION HANDLING
In my last tutorial, we discussed about finally block, which is used with a try block
and always execute whether exception occurs or not. Here we will see few
examples to understand the behaviour of finally block when a return statement is
encountered in try block.
Lets see this code snippet, What do you think? Will finally would execute even if
there is a return statement in try block as well as in catch block?
try {
//try block
...
return success;
}
catch (Exception ex) {
//catch block
.....
return failure;
}
finally {
System.out.println("Inside finally");
}
The answer is yes. finally block will execute. The only case where it will not
execute is when it encounters System.exit().